GroupBook MAC-randomization device pairing, channel stats, probe + deauth alerts
Browse files at this commitc5d9e1afec5cb29ed0bd5bd9b0c1479e17b39eeaParent: 3b3768a- feat
- GroupBook MAC-randomization device pairing, channel stats, probe + deauth alerts
1 changed file +1029 -28
- src/scanner.rs +1029 -28
src/scanner.rsmodified+1029 -28
| @@ -3,8 +3,8 @@ | |||
| 3 | //! via [`Event`]s until `stop` flips true. Pure discovery — handshake | 3 | //! via [`Event`]s until `stop` flips true. Pure discovery — handshake |
| 4 | //! correlation happens in [`crate::handshake`]. | 4 | //! correlation happens in [`crate::handshake`]. |
| 5 | 5 | ||
| 6 | -use std::collections::BTreeMap; | 6 | +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; |
| 7 | -use std::sync::Arc; | 7 | +use std::sync::{Arc, Mutex}; |
| 8 | use std::sync::atomic::{AtomicBool, Ordering}; | 8 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 9 | use std::time::{Duration, Instant}; | 9 | use std::time::{Duration, Instant}; |
| 10 | // `Instant` is still used for dwell timing; timestamps going into shared | 10 | // `Instant` is still used for dwell timing; timestamps going into shared |
| @@ -13,7 +13,11 @@ use std::time::{Duration, Instant}; | |||
| 13 | use anyhow::{Context, Result}; | 13 | use anyhow::{Context, Result}; |
| 14 | use crossbeam_channel::Sender; | 14 | use crossbeam_channel::Sender; |
| 15 | 15 | ||
| 16 | -use crate::common::{AccessPoint, ClientInfo, Event, HOP_FREQS_ALL, MacAddr, now_ms}; | 16 | +use crate::common::{ |
| 17 | + AccessPoint, ChannelStat, ClientInfo, Event, HOP_FREQS_ALL, IdentConfidence, MacAddr, | ||
| 18 | + ProbeInfo, now_ms, | ||
| 19 | +}; | ||
| 20 | +use crate::pcapout::PcapWriter; | ||
| 17 | use crate::radiotap::RxMeta; | 21 | use crate::radiotap::RxMeta; |
| 18 | use crate::rawsock::RawSocket; | 22 | use crate::rawsock::RawSocket; |
| 19 | use crate::{dot11, iface, radiotap}; | 23 | use crate::{dot11, iface, radiotap}; |
| @@ -22,6 +26,223 @@ use crate::{dot11, iface, radiotap}; | |||
| 22 | const AP_EXPIRE_MS: u64 = 30_000; | 26 | const AP_EXPIRE_MS: u64 = 30_000; |
| 23 | /// Clients go stale after this much silence (ms). | 27 | /// Clients go stale after this much silence (ms). |
| 24 | const CLIENT_EXPIRE_MS: u64 = 60_000; | 28 | const 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. | ||
| 31 | +const PROBE_DEDUP_MS: u64 = 60_000; | ||
| 32 | +/// Sliding window for the foreign-deauth storm detector (ms). | ||
| 33 | +const DEAUTH_WINDOW_MS: u64 = 10_000; | ||
| 34 | +/// Deauths inside the window triggering a [`Event::DeauthAlert`]. | ||
| 35 | +const DEAUTH_ALERT_THRESHOLD: u32 = 10; | ||
| 36 | +/// Per-pair cooldown after an alert fired (ms). | ||
| 37 | +const 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). | ||
| 40 | +const DEAUTH_HIST_CAP: usize = 32; | ||
| 41 | + | ||
| 42 | +// --------------------------------------------------------------------------- | ||
| 43 | +// device identity groups (MAC-randomization pairing) | ||
| 44 | +// --------------------------------------------------------------------------- | ||
| 45 | + | ||
| 46 | +/// Pairing state for a single station MAC inside a group. | ||
| 47 | +struct MacSeen { | ||
| 48 | + last_seen_ms: u64, | ||
| 49 | + last_seq: Option<u16>, | ||
| 50 | + /// Confidence assigned when THIS MAC joined (or first created) the | ||
| 51 | + /// group — assignment-time semantics; later frames only refresh times. | ||
| 52 | + conf: IdentConfidence, | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// One correlated physical radio: the set of MACs we have witnessed on it, | ||
| 56 | +/// plus correlation keys (ordered-IE fingerprints it sent, SSIDs it probed | ||
| 57 | +/// for, its WPS UUID). | ||
| 58 | +struct IdGroup { | ||
| 59 | + id: u64, | ||
| 60 | + macs: HashMap<MacAddr, MacSeen>, | ||
| 61 | + fps: HashSet<u32>, | ||
| 62 | + /// SSIDs any member probed for (capped — a paranoia bound, not a rule). | ||
| 63 | + ssids: HashSet<String>, | ||
| 64 | + uuid: Option<[u8; 16]>, | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// Correlation book: pairs rotated/randomized MACs that belong to one | ||
| 68 | +/// physical radio. Witnesses, strongest first: WPS UUID-E (the device | ||
| 69 | +/// names itself), then shared ordered-IE fingerprint upgraded by a | ||
| 70 | +/// per-frame witness — a shared probed SSID or uninterrupted 12-bit | ||
| 71 | +/// sequence numbers across the rotation (seq continuity almost never | ||
| 72 | +/// happens by chance: 1/4096 per direct successor pair). | ||
| 73 | +struct GroupBook { | ||
| 74 | + groups: Vec<IdGroup>, | ||
| 75 | + mac_to_group: HashMap<MacAddr, usize>, | ||
| 76 | + fp_to_groups: HashMap<u32, Vec<usize>>, | ||
| 77 | + next_id: u64, | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/// Group bookkeeping retention: group members and keys outlive the client | ||
| 81 | +/// row by this long so a rotated MAC that appears *after* the old row | ||
| 82 | +/// expired still lands in the same group. 15 min covers the typical | ||
| 83 | +/// rotation cadence (iOS ~24 h per-network, Android on-screen ~10 min during | ||
| 84 | +/// scanning bursts). | ||
| 85 | +const GROUP_TTL_MS: u64 = 15 * 60 * 1000; | ||
| 86 | + | ||
| 87 | +impl GroupBook { | ||
| 88 | + fn new() -> Self { | ||
| 89 | + Self { | ||
| 90 | + groups: Vec::new(), | ||
| 91 | + mac_to_group: HashMap::new(), | ||
| 92 | + fp_to_groups: HashMap::new(), | ||
| 93 | + next_id: 1, | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + /// `(group id, assignment confidence)` for an already-assigned MAC. | ||
| 98 | + fn id_of(&self, mac: &MacAddr) -> Option<(u64, IdentConfidence)> { | ||
| 99 | + let &gi = self.mac_to_group.get(mac)?; | ||
| 100 | + let m = self.groups[gi].macs.get(mac)?; | ||
| 101 | + Some((self.groups[gi].id, m.conf)) | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + /// Record one frame's worth of correlation material for `sta`. | ||
| 105 | + /// Returns `Some((group, confidence))` only when the MAC's group | ||
| 106 | + /// assignment was newly decided (first assignment or re-assignment | ||
| 107 | + /// after expiry) — callers emit [`Event::ClientIdent`] on Some. | ||
| 108 | + fn note( | ||
| 109 | + &mut self, | ||
| 110 | + sta: MacAddr, | ||
| 111 | + fp: u32, | ||
| 112 | + uuid: Option<[u8; 16]>, | ||
| 113 | + ssid: Option<&str>, | ||
| 114 | + seq: Option<u16>, | ||
| 115 | + now: u64, | ||
| 116 | + ) -> Option<(u64, IdentConfidence)> { | ||
| 117 | + if let Some(&gi) = self.mac_to_group.get(&sta) { | ||
| 118 | + let g = &mut self.groups[gi]; | ||
| 119 | + if let Some(m) = g.macs.get_mut(&sta) { | ||
| 120 | + m.last_seen_ms = now; | ||
| 121 | + m.last_seq = seq.or(m.last_seq); | ||
| 122 | + } | ||
| 123 | + g.fps.insert(fp); | ||
| 124 | + if let Some(s) = ssid { | ||
| 125 | + if !s.is_empty() && g.ssids.len() < 64 { | ||
| 126 | + g.ssids.insert(s.to_string()); | ||
| 127 | + } | ||
| 128 | + } | ||
| 129 | + return None; | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + // UUID-E is a certain witness on its own: match it even when the | ||
| 133 | + // radio's IE chain changed so much the fingerprint misses (new | ||
| 134 | + // driver/firmware between rotations). | ||
| 135 | + let mut best: Option<(usize, IdentConfidence)> = uuid.and_then(|u| { | ||
| 136 | + self.groups | ||
| 137 | + .iter() | ||
| 138 | + .position(|g| g.uuid == Some(u) && !g.macs.contains_key(&sta)) | ||
| 139 | + .map(|gi| (gi, IdentConfidence::Exact)) | ||
| 140 | + }); | ||
| 141 | + | ||
| 142 | + if best.is_none() { | ||
| 143 | + let mut hits: Vec<usize> = self.fp_to_groups.get(&fp).cloned().unwrap_or_default(); | ||
| 144 | + hits.retain(|&gi| gi < self.groups.len()); | ||
| 145 | + hits.sort_unstable(); | ||
| 146 | + hits.dedup(); | ||
| 147 | + for gi in hits { | ||
| 148 | + let g = &self.groups[gi]; | ||
| 149 | + let fresh = g.macs.values().max_by_key(|m| m.last_seen_ms); | ||
| 150 | + let ssid_match = | ||
| 151 | + ssid.is_some_and(|s| !s.is_empty() && g.ssids.contains(s)); | ||
| 152 | + let seq_continues = seq | ||
| 153 | + .zip(fresh.and_then(|m| m.last_seq)) | ||
| 154 | + .is_some_and(|(a, b)| { | ||
| 155 | + let d = a.wrapping_sub(b); | ||
| 156 | + d >= 1 && d <= 32 | ||
| 157 | + }); | ||
| 158 | + let conf = if ssid_match || seq_continues { | ||
| 159 | + IdentConfidence::Strong | ||
| 160 | + } else { | ||
| 161 | + IdentConfidence::Probable | ||
| 162 | + }; | ||
| 163 | + if best.is_none_or(|(_, c)| conf > c) { | ||
| 164 | + best = Some((gi, conf)); | ||
| 165 | + } | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + | ||
| 169 | + let (gi, conf) = match best { | ||
| 170 | + Some(x) => x, | ||
| 171 | + None => { | ||
| 172 | + self.groups.push(IdGroup { | ||
| 173 | + id: self.next_id, | ||
| 174 | + macs: HashMap::new(), | ||
| 175 | + fps: HashSet::new(), | ||
| 176 | + ssids: HashSet::new(), | ||
| 177 | + uuid: None, | ||
| 178 | + }); | ||
| 179 | + self.next_id += 1; | ||
| 180 | + (self.groups.len() - 1, IdentConfidence::Probable) | ||
| 181 | + } | ||
| 182 | + }; | ||
| 183 | + | ||
| 184 | + let g = &mut self.groups[gi]; | ||
| 185 | + g.macs.insert(sta, MacSeen { last_seen_ms: now, last_seq: seq, conf }); | ||
| 186 | + g.fps.insert(fp); | ||
| 187 | + if uuid.is_some() { | ||
| 188 | + g.uuid = uuid; | ||
| 189 | + } | ||
| 190 | + if let Some(s) = ssid { | ||
| 191 | + if !s.is_empty() && g.ssids.len() < 64 { | ||
| 192 | + g.ssids.insert(s.to_string()); | ||
| 193 | + } | ||
| 194 | + } | ||
| 195 | + self.mac_to_group.insert(sta, gi); | ||
| 196 | + self.fp_to_groups.entry(fp).or_default().push(gi); | ||
| 197 | + Some((self.groups[gi].id, conf)) | ||
| 198 | + } | ||
| 199 | + | ||
| 200 | + /// Reap members — and whole empty groups — past the pairing TTL. | ||
| 201 | + fn expire(&mut self, now: u64) { | ||
| 202 | + for g in self.groups.iter_mut() { | ||
| 203 | + g.macs.retain(|m, seen| { | ||
| 204 | + let live = now.saturating_sub(seen.last_seen_ms) <= GROUP_TTL_MS; | ||
| 205 | + if !live { | ||
| 206 | + self.mac_to_group.remove(m); | ||
| 207 | + } | ||
| 208 | + live | ||
| 209 | + }); | ||
| 210 | + } | ||
| 211 | + // Keep memory bounded against one-off probe storms: a group whose | ||
| 212 | + // members all reaped gives up its keys too. | ||
| 213 | + self.groups.retain(|g| !g.macs.is_empty()); | ||
| 214 | + // Rebuild the secondary indexes so integer group positions stay | ||
| 215 | + // valid after retain-compaction. | ||
| 216 | + self.mac_to_group.clear(); | ||
| 217 | + self.fp_to_groups.clear(); | ||
| 218 | + for (gi, g) in self.groups.iter().enumerate() { | ||
| 219 | + for m in g.macs.keys() { | ||
| 220 | + self.mac_to_group.insert(*m, gi); | ||
| 221 | + } | ||
| 222 | + for fp in &g.fps { | ||
| 223 | + self.fp_to_groups.entry(*fp).or_default().push(gi); | ||
| 224 | + } | ||
| 225 | + } | ||
| 226 | + } | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +/// Push `now` onto `counts`, prune stamps older than the 10 s window, and | ||
| 230 | +/// report `Some(n)` when the window holds ≥ [`DEAUTH_ALERT_THRESHOLD`] | ||
| 231 | +/// stamps. Pure — unit-tested directly. | ||
| 232 | +pub(crate) fn deauth_alert(counts: &mut VecDeque<u64>, now: u64) -> Option<u32> { | ||
| 233 | + counts.push_back(now); | ||
| 234 | + while counts.len() > DEAUTH_HIST_CAP { | ||
| 235 | + counts.pop_front(); | ||
| 236 | + } | ||
| 237 | + while let Some(&t) = counts.front() { | ||
| 238 | + if now.saturating_sub(t) > DEAUTH_WINDOW_MS { | ||
| 239 | + counts.pop_front(); | ||
| 240 | + } else { | ||
| 241 | + break; | ||
| 242 | + } | ||
| 243 | + } | ||
| 244 | + (counts.len() >= DEAUTH_ALERT_THRESHOLD as usize).then_some(counts.len() as u32) | ||
| 245 | +} | ||
| 25 | 246 | ||
| 26 | pub struct ScannerConfig { | 247 | pub struct ScannerConfig { |
| 27 | pub ifname: String, | 248 | pub ifname: String, |
| @@ -33,6 +254,18 @@ pub struct ScannerConfig { | |||
| 33 | /// RSSI below this blocks creation of new AP/client entries (updates to | 254 | /// RSSI below this blocks creation of new AP/client entries (updates to |
| 34 | /// already-known entries are always accepted). | 255 | /// already-known entries are always accepted). |
| 35 | pub rssi_floor: i8, | 256 | pub rssi_floor: i8, |
| 257 | + /// Channel arbitration with attack workers ([`iface::ChannelPin`]): | ||
| 258 | + /// nonzero → dwell on the pinned frequency instead of hopping. | ||
| 259 | + pub pin: Arc<iface::ChannelPin>, | ||
| 260 | + /// Own MAC of the monitor interface — deauth frames sourced from it | ||
| 261 | + /// are ours and must not trip the foreign-deauth detector. | ||
| 262 | + pub own_mac: MacAddr, | ||
| 263 | + /// BSSIDs we are deauthenticating on behalf of the user right now | ||
| 264 | + /// (our blasts use the AP as transmitter) — suppressed like `own_mac`. | ||
| 265 | + pub deauth_suppress: Arc<Mutex<HashSet<MacAddr>>>, | ||
| 266 | + /// Shared pcap spool writer (raw frames WITH radiotap header are | ||
| 267 | + /// appended in the recv loop). `None` = no spooling. | ||
| 268 | + pub spool: Option<Arc<Mutex<PcapWriter>>>, | ||
| 36 | } | 269 | } |
| 37 | 270 | ||
| 38 | /// Channel-frequency → channel number for the bands we hop. | 271 | /// Channel-frequency → channel number for the bands we hop. |
| @@ -55,14 +288,37 @@ struct Scanner { | |||
| 55 | aps: BTreeMap<MacAddr, AccessPoint>, | 288 | aps: BTreeMap<MacAddr, AccessPoint>, |
| 56 | clients: BTreeMap<MacAddr, ClientInfo>, | 289 | clients: BTreeMap<MacAddr, ClientInfo>, |
| 57 | rssi_floor: i8, | 290 | rssi_floor: i8, |
| 291 | + /// Own monitor-interface MAC + user-triggered deauth BSSIDs: frames | ||
| 292 | + /// sourced from these are suppressed in the storm detector. | ||
| 293 | + own_mac: MacAddr, | ||
| 294 | + deauth_suppress: Arc<Mutex<HashSet<MacAddr>>>, | ||
| 295 | + /// (client, probed-ssid) → last emit; 60 s suppression of repeats. | ||
| 296 | + probe_dedup: HashMap<(MacAddr, Option<String>), u64>, | ||
| 297 | + /// (deauth src, dst) → ms stamps inside the sliding window. | ||
| 298 | + deauth_hist: HashMap<(MacAddr, MacAddr), VecDeque<u64>>, | ||
| 299 | + /// (src, dst) → cooldown-until ms after a fired alert. | ||
| 300 | + alert_cooldown: HashMap<(MacAddr, MacAddr), u64>, | ||
| 301 | + /// MAC-randomization pairing: correlated device groups built from | ||
| 302 | + /// probe/assoc frames. | ||
| 303 | + groups: GroupBook, | ||
| 58 | } | 304 | } |
| 59 | 305 | ||
| 60 | impl Scanner { | 306 | impl Scanner { |
| 61 | - fn new(rssi_floor: i8) -> Self { | 307 | + fn new( |
| 308 | + rssi_floor: i8, | ||
| 309 | + own_mac: MacAddr, | ||
| 310 | + deauth_suppress: Arc<Mutex<HashSet<MacAddr>>>, | ||
| 311 | + ) -> Self { | ||
| 62 | Self { | 312 | Self { |
| 63 | aps: BTreeMap::new(), | 313 | aps: BTreeMap::new(), |
| 64 | clients: BTreeMap::new(), | 314 | clients: BTreeMap::new(), |
| 65 | rssi_floor, | 315 | rssi_floor, |
| 316 | + own_mac, | ||
| 317 | + deauth_suppress, | ||
| 318 | + probe_dedup: HashMap::new(), | ||
| 319 | + deauth_hist: HashMap::new(), | ||
| 320 | + alert_cooldown: HashMap::new(), | ||
| 321 | + groups: GroupBook::new(), | ||
| 66 | } | 322 | } |
| 67 | } | 323 | } |
| 68 | 324 | ||
| @@ -98,6 +354,10 @@ impl Scanner { | |||
| 98 | ap.security = m.security; | 354 | ap.security = m.security; |
| 99 | changed = true; | 355 | changed = true; |
| 100 | } | 356 | } |
| 357 | + if m.akms != ap.akms { | ||
| 358 | + ap.akms = m.akms.clone(); | ||
| 359 | + changed = true; | ||
| 360 | + } | ||
| 101 | ap.beacons += 1; | 361 | ap.beacons += 1; |
| 102 | ap.last_seen_ms = now; | 362 | ap.last_seen_ms = now; |
| 103 | if changed { | 363 | if changed { |
| @@ -116,6 +376,7 @@ impl Scanner { | |||
| 116 | rssi_dbm: meta.rssi_dbm, | 376 | rssi_dbm: meta.rssi_dbm, |
| 117 | beacons: 1, | 377 | beacons: 1, |
| 118 | last_seen_ms: now, | 378 | last_seen_ms: now, |
| 379 | + akms: m.akms.clone(), | ||
| 119 | }; | 380 | }; |
| 120 | self.aps.insert(m.bssid, ap.clone()); | 381 | self.aps.insert(m.bssid, ap.clone()); |
| 121 | let _ = tx.send(Event::ApUpdated(ap)); | 382 | let _ = tx.send(Event::ApUpdated(ap)); |
| @@ -125,14 +386,100 @@ impl Scanner { | |||
| 125 | } | 386 | } |
| 126 | 387 | ||
| 127 | // Client probing. | 388 | // Client probing. |
| 128 | - if let Some((sta, _ssid)) = dot11::parse_probe_req(frame) { | 389 | + if let Some(ident) = dot11::parse_probe_ident(frame) { |
| 390 | + let sta = ident.sta; | ||
| 129 | if sta.is_multicast() || sta.is_zero() { | 391 | if sta.is_multicast() || sta.is_zero() { |
| 130 | return; | 392 | return; |
| 131 | } | 393 | } |
| 394 | + // Probe panel: one event per (client, ssid) per 60 s — retries | ||
| 395 | + // from reconnect-happy phones would flood the UI otherwise. | ||
| 396 | + let key = (sta, ident.ssid.clone()); | ||
| 397 | + let fresh = match self.probe_dedup.get(&key) { | ||
| 398 | + Some(&last) => now.saturating_sub(last) > PROBE_DEDUP_MS, | ||
| 399 | + None => true, | ||
| 400 | + }; | ||
| 401 | + if fresh { | ||
| 402 | + self.probe_dedup.insert(key, now); | ||
| 403 | + let _ = tx.send(Event::ProbeObserved(ProbeInfo { | ||
| 404 | + client: sta, | ||
| 405 | + ssid: ident.ssid.clone(), | ||
| 406 | + rssi_dbm: meta.rssi_dbm, | ||
| 407 | + at_ms: now, | ||
| 408 | + })); | ||
| 409 | + } | ||
| 410 | + // Pairing first: the creation event from `note_client` then | ||
| 411 | + // already carries the group id (no follow-up stamp needed). | ||
| 412 | + self.note_ident( | ||
| 413 | + sta, | ||
| 414 | + ident.fingerprint, | ||
| 415 | + ident.uuid, | ||
| 416 | + ident.ssid.as_deref(), | ||
| 417 | + dot11::seq_of(frame), | ||
| 418 | + now, | ||
| 419 | + tx, | ||
| 420 | + ); | ||
| 132 | self.note_client(sta, None, meta, now, tx); | 421 | self.note_client(sta, None, meta, now, tx); |
| 133 | return; | 422 | return; |
| 134 | } | 423 | } |
| 135 | 424 | ||
| 425 | + // Association/reassociation request: the station names the SSID it | ||
| 426 | + // joins — the only on-air witness that reveals a hidden AP's SSID. | ||
| 427 | + if let Some(ident) = dot11::parse_assoc_ident(frame) { | ||
| 428 | + let sta = ident.sta; | ||
| 429 | + if !sta.is_multicast() && !sta.is_zero() { | ||
| 430 | + // Pairing first: the creation event then already carries | ||
| 431 | + // the group id. | ||
| 432 | + self.note_ident( | ||
| 433 | + sta, | ||
| 434 | + ident.fingerprint, | ||
| 435 | + ident.uuid, | ||
| 436 | + ident.ssid.as_deref(), | ||
| 437 | + dot11::seq_of(frame), | ||
| 438 | + now, | ||
| 439 | + tx, | ||
| 440 | + ); | ||
| 441 | + self.note_client(sta, Some(ident.bssid), meta, now, tx); | ||
| 442 | + } | ||
| 443 | + if let Some(ssid) = ident.ssid | ||
| 444 | + && let Some(ap) = self.aps.get_mut(&ident.bssid) | ||
| 445 | + && ap.ssid.is_empty() | ||
| 446 | + { | ||
| 447 | + ap.ssid = ssid; | ||
| 448 | + ap.last_seen_ms = now; | ||
| 449 | + let _ = tx.send(Event::ApUpdated(ap.clone())); | ||
| 450 | + } | ||
| 451 | + return; | ||
| 452 | + } | ||
| 453 | + | ||
| 454 | + // Deauth/disassoc: flag the affected station disconnected so the UI | ||
| 455 | + // separates it now instead of waiting for 60 s of silence to expire | ||
| 456 | + // the row. Either side can be the station: AP → client (target) or | ||
| 457 | + // client-initiated (transmitter). Frames between unknown parties are | ||
| 458 | + // noise — we only flip state on stations we already track. | ||
| 459 | + if let Some((from, target)) = dot11::parse_deauth(frame) { | ||
| 460 | + self.track_foreign_deauth(from, target, now, tx); | ||
| 461 | + let sta = if !target.is_multicast() && !target.is_zero() { | ||
| 462 | + self.clients.contains_key(&target).then_some(target) | ||
| 463 | + } else { | ||
| 464 | + None | ||
| 465 | + } | ||
| 466 | + .or_else(|| { | ||
| 467 | + (!from.is_multicast() && !from.is_zero()) | ||
| 468 | + .then(|| self.clients.contains_key(&from).then_some(from)) | ||
| 469 | + .flatten() | ||
| 470 | + }); | ||
| 471 | + if let Some(sta) = sta | ||
| 472 | + && let Some(c) = self.clients.get_mut(&sta) | ||
| 473 | + && c.connected | ||
| 474 | + { | ||
| 475 | + // State change only — repeated deauths against an already | ||
| 476 | + // flagged station are silent (no event storm). | ||
| 477 | + c.connected = false; | ||
| 478 | + let _ = tx.send(Event::ClientUpdated(c.clone())); | ||
| 479 | + } | ||
| 480 | + return; | ||
| 481 | + } | ||
| 482 | + | ||
| 136 | // Clients talking data: learn station side; the bssid side refreshes | 483 | // Clients talking data: learn station side; the bssid side refreshes |
| 137 | // the AP liveness (channel/time) without bumping beacon count. | 484 | // the AP liveness (channel/time) without bumping beacon count. |
| 138 | if let Some((bssid, sta)) = dot11::data_endpoints(frame) { | 485 | if let Some((bssid, sta)) = dot11::data_endpoints(frame) { |
| @@ -145,6 +492,78 @@ impl Scanner { | |||
| 145 | } | 492 | } |
| 146 | } | 493 | } |
| 147 | 494 | ||
| 495 | + /// Foreign-deauth storm detector: ≥10 deauths/disassocs from one | ||
| 496 | + /// (src, dst) pair inside 10 s → one [`Event::DeauthAlert`], then a 30 s | ||
| 497 | + /// per-pair cooldown. Frames WE transmitted (monitor MAC as source, or | ||
| 498 | + /// an AP we're user-deauthing — our blasts carry its BSSID as addr2) | ||
| 499 | + /// never count. | ||
| 500 | + fn track_foreign_deauth( | ||
| 501 | + &mut self, | ||
| 502 | + from: MacAddr, | ||
| 503 | + target: MacAddr, | ||
| 504 | + now: u64, | ||
| 505 | + tx: &Sender<Event>, | ||
| 506 | + ) { | ||
| 507 | + if from == self.own_mac | ||
| 508 | + || self | ||
| 509 | + .deauth_suppress | ||
| 510 | + .lock() | ||
| 511 | + .map(|s| s.contains(&from)) | ||
| 512 | + .unwrap_or(false) | ||
| 513 | + { | ||
| 514 | + return; | ||
| 515 | + } | ||
| 516 | + let key = (from, target); | ||
| 517 | + if self | ||
| 518 | + .alert_cooldown | ||
| 519 | + .get(&key) | ||
| 520 | + .is_some_and(|&until| now < until) | ||
| 521 | + { | ||
| 522 | + return; | ||
| 523 | + } | ||
| 524 | + let counts = self.deauth_hist.entry(key).or_default(); | ||
| 525 | + if let Some(n) = deauth_alert(counts, now) { | ||
| 526 | + self.alert_cooldown | ||
| 527 | + .insert(key, now + DEAUTH_ALERT_COOLDOWN_MS); | ||
| 528 | + let _ = tx.send(Event::DeauthAlert { | ||
| 529 | + source: from, | ||
| 530 | + target, | ||
| 531 | + count: n, | ||
| 532 | + }); | ||
| 533 | + } | ||
| 534 | + } | ||
| 535 | + | ||
| 536 | + /// MAC-randomization pairing: fold one frame's correlation material | ||
| 537 | + /// into the group book; emit [`Event::ClientIdent`] exactly once per | ||
| 538 | + /// pairing decision (first assignment or re-entry after expiry). | ||
| 539 | + fn note_ident( | ||
| 540 | + &mut self, | ||
| 541 | + sta: MacAddr, | ||
| 542 | + fp: u32, | ||
| 543 | + uuid: Option<[u8; 16]>, | ||
| 544 | + ssid: Option<&str>, | ||
| 545 | + seq: Option<u16>, | ||
| 546 | + now: u64, | ||
| 547 | + tx: &Sender<Event>, | ||
| 548 | + ) { | ||
| 549 | + let Some((group, confidence)) = self.groups.note(sta, fp, uuid, ssid, seq, now) else { | ||
| 550 | + return; | ||
| 551 | + }; | ||
| 552 | + let _ = tx.send(Event::ClientIdent { | ||
| 553 | + mac: sta, | ||
| 554 | + group, | ||
| 555 | + confidence, | ||
| 556 | + }); | ||
| 557 | + // If the station row already exists, stamp it so the ID column | ||
| 558 | + // reflects the pairing immediately (UI also overlays from its own | ||
| 559 | + // ident map — belt and suspenders for event-order observers). | ||
| 560 | + if let Some(c) = self.clients.get_mut(&sta) { | ||
| 561 | + c.ident_group = Some(group); | ||
| 562 | + c.ident_conf = Some(confidence); | ||
| 563 | + let _ = tx.send(Event::ClientUpdated(c.clone())); | ||
| 564 | + } | ||
| 565 | + } | ||
| 566 | + | ||
| 148 | fn note_client( | 567 | fn note_client( |
| 149 | &mut self, | 568 | &mut self, |
| 150 | sta: MacAddr, | 569 | sta: MacAddr, |
| @@ -166,6 +585,13 @@ impl Scanner { | |||
| 166 | changed = true; | 585 | changed = true; |
| 167 | } | 586 | } |
| 168 | } | 587 | } |
| 588 | + // Any frame from the station proves liveness: clear the | ||
| 589 | + // deauth-flagged disconnect (the flip rides the normal | ||
| 590 | + // `changed` emit below — no separate storm). | ||
| 591 | + if !c.connected { | ||
| 592 | + c.connected = true; | ||
| 593 | + changed = true; | ||
| 594 | + } | ||
| 169 | c.frames += 1; | 595 | c.frames += 1; |
| 170 | c.last_seen_ms = now; | 596 | c.last_seen_ms = now; |
| 171 | if changed { | 597 | if changed { |
| @@ -176,12 +602,16 @@ impl Scanner { | |||
| 176 | if meta.rssi_dbm != 0 && meta.rssi_dbm < self.rssi_floor { | 602 | if meta.rssi_dbm != 0 && meta.rssi_dbm < self.rssi_floor { |
| 177 | return; | 603 | return; |
| 178 | } | 604 | } |
| 605 | + let ident = self.groups.id_of(&sta); | ||
| 179 | let c = ClientInfo { | 606 | let c = ClientInfo { |
| 180 | mac: sta, | 607 | mac: sta, |
| 181 | ap, | 608 | ap, |
| 182 | rssi_dbm: meta.rssi_dbm, | 609 | rssi_dbm: meta.rssi_dbm, |
| 183 | frames: 1, | 610 | frames: 1, |
| 184 | last_seen_ms: now, | 611 | last_seen_ms: now, |
| 612 | + connected: true, | ||
| 613 | + ident_group: ident.map(|(g, _)| g), | ||
| 614 | + ident_conf: ident.map(|(_, c)| c), | ||
| 185 | }; | 615 | }; |
| 186 | self.clients.insert(sta, c.clone()); | 616 | self.clients.insert(sta, c.clone()); |
| 187 | let _ = tx.send(Event::ClientUpdated(c)); | 617 | let _ = tx.send(Event::ClientUpdated(c)); |
| @@ -189,8 +619,8 @@ impl Scanner { | |||
| 189 | } | 619 | } |
| 190 | } | 620 | } |
| 191 | 621 | ||
| 192 | - /// Expire silent entries, emitting ApLost / (clients just drop out — | 622 | + /// Expire silent entries, emitting ApLost / ClientLost so the UI drops |
| 193 | - /// contract has no ClientLost event; stale clients stop being updated). | 623 | + /// the rows too (stale clients must not accumulate on screen). |
| 194 | fn expire(&mut self, now: u64, tx: &Sender<Event>) { | 624 | fn expire(&mut self, now: u64, tx: &Sender<Event>) { |
| 195 | let gone: Vec<MacAddr> = self | 625 | let gone: Vec<MacAddr> = self |
| 196 | .aps | 626 | .aps |
| @@ -202,8 +632,32 @@ impl Scanner { | |||
| 202 | self.aps.remove(&b); | 632 | self.aps.remove(&b); |
| 203 | let _ = tx.send(Event::ApLost(b)); | 633 | let _ = tx.send(Event::ApLost(b)); |
| 204 | } | 634 | } |
| 205 | - self.clients | 635 | + let gone: Vec<MacAddr> = self |
| 206 | - .retain(|_, c| now.saturating_sub(c.last_seen_ms) <= CLIENT_EXPIRE_MS); | 636 | + .clients |
| 637 | + .iter() | ||
| 638 | + .filter(|(_, c)| now.saturating_sub(c.last_seen_ms) > CLIENT_EXPIRE_MS) | ||
| 639 | + .map(|(m, _)| *m) | ||
| 640 | + .collect(); | ||
| 641 | + for m in gone { | ||
| 642 | + self.clients.remove(&m); | ||
| 643 | + let _ = tx.send(Event::ClientLost(m)); | ||
| 644 | + } | ||
| 645 | + // Reap detector/dedup state alongside the row expiry so long | ||
| 646 | + // scans don't accumulate dead keys. | ||
| 647 | + self.probe_dedup | ||
| 648 | + .retain(|_, &mut last| now.saturating_sub(last) <= PROBE_DEDUP_MS); | ||
| 649 | + self.deauth_hist.retain(|_, q| { | ||
| 650 | + while let Some(&t) = q.front() { | ||
| 651 | + if now.saturating_sub(t) > DEAUTH_WINDOW_MS { | ||
| 652 | + q.pop_front(); | ||
| 653 | + } else { | ||
| 654 | + break; | ||
| 655 | + } | ||
| 656 | + } | ||
| 657 | + !q.is_empty() | ||
| 658 | + }); | ||
| 659 | + self.alert_cooldown.retain(|_, &mut until| now < until); | ||
| 660 | + self.groups.expire(now); | ||
| 207 | } | 661 | } |
| 208 | } | 662 | } |
| 209 | 663 | ||
| @@ -249,22 +703,46 @@ pub fn run(cfg: ScannerConfig, tx: Sender<Event>, stop: Arc<AtomicBool>) -> Resu | |||
| 249 | cfg.ifname | 703 | cfg.ifname |
| 250 | ))); | 704 | ))); |
| 251 | 705 | ||
| 252 | - let mut scanner = Scanner::new(cfg.rssi_floor); | 706 | + let mut scanner = Scanner::new(cfg.rssi_floor, cfg.own_mac, cfg.deauth_suppress.clone()); |
| 253 | let mut buf = vec![0u8; 4096]; | 707 | let mut buf = vec![0u8; 4096]; |
| 254 | let mut ch_idx = 0usize; | 708 | let mut ch_idx = 0usize; |
| 255 | let mut stats = ScanStats::default(); | 709 | let mut stats = ScanStats::default(); |
| 256 | let mut last_stats_log = Instant::now(); | 710 | let mut last_stats_log = Instant::now(); |
| 711 | + // Cumulative per-channel counters → Event::ChannelStats every 2 s. | ||
| 712 | + let mut chan_hist: BTreeMap<u8, (u64, u64)> = BTreeMap::new(); | ||
| 713 | + let mut last_chan_emit = Instant::now(); | ||
| 714 | + // Spool error latch: 3 consecutive append failures → one log, then | ||
| 715 | + // the spool is dropped silently for the rest of the scan. | ||
| 716 | + let mut spool_failures: u32 = 0; | ||
| 717 | + let mut spool_enabled = cfg.spool.is_some(); | ||
| 718 | + // Last frequency actually tuned — suppresses re-asserting the same | ||
| 719 | + // channel every dwell (iw spam) while the pin is steady. | ||
| 720 | + let mut last_set: u16 = 0; | ||
| 257 | 721 | ||
| 258 | while !stop.load(Ordering::Relaxed) { | 722 | while !stop.load(Ordering::Relaxed) { |
| 259 | - let freq = freqs[ch_idx]; | 723 | + // Channel arbitration: a nonzero pin (capture hold or deauth |
| 724 | + // override) wins over the hop plan for this cycle. While pinned | ||
| 725 | + // the hop index stands still — we resume the plan on release. | ||
| 726 | + let pinned = cfg.pin.get(); | ||
| 727 | + let freq = if pinned != 0 { | ||
| 728 | + pinned | ||
| 729 | + } else { | ||
| 730 | + let f = freqs[ch_idx]; | ||
| 731 | + ch_idx = (ch_idx + 1) % freqs.len(); | ||
| 732 | + f | ||
| 733 | + }; | ||
| 260 | // Display channel number (2.4/5 GHz exact; 6 GHz reported as its | 734 | // Display channel number (2.4/5 GHz exact; 6 GHz reported as its |
| 261 | // own channel number — cosmetic only). | 735 | // own channel number — cosmetic only). |
| 262 | let cur_ch = freq_to_channel(freq).map(|c| c as i32).unwrap_or(-1); | 736 | let cur_ch = freq_to_channel(freq).map(|c| c as i32).unwrap_or(-1); |
| 263 | - ch_idx = (ch_idx + 1) % freqs.len(); | 737 | + if freq != last_set { |
| 264 | - if let Err(e) = iface::set_freq(&cfg.ifname, freq) { | 738 | + match iface::set_freq(&cfg.ifname, freq) { |
| 265 | - let _ = tx.send(Event::Log(format!( | 739 | + Ok(()) => last_set = freq, |
| 266 | - "scanner: hop to {freq} MHz failed: {e:#}" | 740 | + Err(e) => { |
| 267 | - ))); | 741 | + let _ = tx.send(Event::Log(format!( |
| 742 | + "scanner: tune to {freq} MHz failed: {e:#}" | ||
| 743 | + ))); | ||
| 744 | + } | ||
| 745 | + } | ||
| 268 | } | 746 | } |
| 269 | 747 | ||
| 270 | // Drain frames until the dwell elapses (recv timeout bounds it). | 748 | // Drain frames until the dwell elapses (recv timeout bounds it). |
| @@ -274,12 +752,53 @@ pub fn run(cfg: ScannerConfig, tx: Sender<Event>, stop: Arc<AtomicBool>) -> Resu | |||
| 274 | Ok(n) => { | 752 | Ok(n) => { |
| 275 | stats.raw_frames_received += 1; | 753 | stats.raw_frames_received += 1; |
| 276 | let now = now_ms(); | 754 | let now = now_ms(); |
| 755 | + // Pcap spool: the RAW frame straight off the socket, | ||
| 756 | + // radiotap header included (linktype 127). | ||
| 757 | + if spool_enabled && let Some(w) = &cfg.spool { | ||
| 758 | + match w.lock() { | ||
| 759 | + Ok(mut w) => match w.append(&buf[..n]) { | ||
| 760 | + Ok(()) => spool_failures = 0, | ||
| 761 | + Err(e) => { | ||
| 762 | + spool_failures += 1; | ||
| 763 | + if spool_failures >= 3 { | ||
| 764 | + spool_enabled = false; | ||
| 765 | + let _ = tx.send(Event::Log(format!( | ||
| 766 | + "pcap spool disabled: {e}" | ||
| 767 | + ))); | ||
| 768 | + } | ||
| 769 | + } | ||
| 770 | + }, | ||
| 771 | + Err(e) => { | ||
| 772 | + spool_failures += 1; | ||
| 773 | + if spool_failures >= 3 { | ||
| 774 | + spool_enabled = false; | ||
| 775 | + let _ = tx.send(Event::Log(format!( | ||
| 776 | + "pcap spool disabled: {e}" | ||
| 777 | + ))); | ||
| 778 | + } | ||
| 779 | + } | ||
| 780 | + } | ||
| 781 | + } | ||
| 277 | if let Some((meta, frame)) = radiotap::strip(&buf[..n]) { | 782 | if let Some((meta, frame)) = radiotap::strip(&buf[..n]) { |
| 278 | stats.radiotap_strip_ok += 1; | 783 | stats.radiotap_strip_ok += 1; |
| 784 | + // Per-channel attribution: trust the radiotap | ||
| 785 | + // carrier frequency; fall back to the channel we | ||
| 786 | + // last tuned to (radiotap freq is occasionally 0). | ||
| 787 | + let ch = freq_to_channel(meta.freq_mhz) | ||
| 788 | + .or_else(|| freq_to_channel(last_set)); | ||
| 789 | + let is_beacon_fc = | ||
| 790 | + frame.len() >= 24 && (frame[0] == 0x80 || frame[0] == 0x50); | ||
| 791 | + if let Some(ch) = ch { | ||
| 792 | + let e = chan_hist.entry(ch).or_insert((0, 0)); | ||
| 793 | + e.0 += 1; | ||
| 794 | + if is_beacon_fc { | ||
| 795 | + e.1 += 1; | ||
| 796 | + } | ||
| 797 | + } | ||
| 279 | // Parser-independent witness: beacon (0x80) and | 798 | // Parser-independent witness: beacon (0x80) and |
| 280 | // probe-response (0x50) frames carry the transmitter | 799 | // probe-response (0x50) frames carry the transmitter |
| 281 | // BSSID at addr3 (bytes 16..22) before any IE parse. | 800 | // BSSID at addr3 (bytes 16..22) before any IE parse. |
| 282 | - if frame.len() >= 24 && (frame[0] == 0x80 || frame[0] == 0x50) { | 801 | + if is_beacon_fc { |
| 283 | stats.beacon_fc_rx += 1; | 802 | stats.beacon_fc_rx += 1; |
| 284 | let mut mac = [0u8; 6]; | 803 | let mut mac = [0u8; 6]; |
| 285 | mac.copy_from_slice(&frame[16..22]); | 804 | mac.copy_from_slice(&frame[16..22]); |
| @@ -319,6 +838,20 @@ pub fn run(cfg: ScannerConfig, tx: Sender<Event>, stop: Arc<AtomicBool>) -> Resu | |||
| 319 | } | 838 | } |
| 320 | } | 839 | } |
| 321 | 840 | ||
| 841 | + // 2 s per-channel cumulative snapshot for the channel-activity UI. | ||
| 842 | + if last_chan_emit.elapsed() >= Duration::from_secs(2) { | ||
| 843 | + last_chan_emit = Instant::now(); | ||
| 844 | + let snap: Vec<ChannelStat> = chan_hist | ||
| 845 | + .iter() | ||
| 846 | + .map(|(&channel, &(frames, beacons))| ChannelStat { | ||
| 847 | + channel, | ||
| 848 | + frames, | ||
| 849 | + beacons, | ||
| 850 | + }) | ||
| 851 | + .collect(); | ||
| 852 | + let _ = tx.send(Event::ChannelStats(snap)); | ||
| 853 | + } | ||
| 854 | + | ||
| 322 | // 10 s wall-time diagnostic heartbeat: distinguishes RX-silence | 855 | // 10 s wall-time diagnostic heartbeat: distinguishes RX-silence |
| 323 | // (rx==0) from radiotap/parser drops (rx>0 but beacons==0) when a | 856 | // (rx==0) from radiotap/parser drops (rx>0 but beacons==0) when a |
| 324 | // report says "only my own AP shows up". | 857 | // report says "only my own AP shows up". |
| @@ -422,10 +955,60 @@ mod tests { | |||
| 422 | } | 955 | } |
| 423 | } | 956 | } |
| 424 | 957 | ||
| 958 | + /// Scanner under test: no suppression, unknown own MAC. | ||
| 959 | + fn test_scanner() -> Scanner { | ||
| 960 | + Scanner::new( | ||
| 961 | + -85, | ||
| 962 | + MacAddr::ZERO, | ||
| 963 | + Arc::new(Mutex::new(HashSet::new())), | ||
| 964 | + ) | ||
| 965 | + } | ||
| 966 | + | ||
| 967 | + // -- frames with a caller-picked sequence number (pairing tests) ------ | ||
| 968 | + | ||
| 969 | + fn ie_bytes(id: u8, body: &[u8]) -> Vec<u8> { | ||
| 970 | + let mut v = vec![id, body.len() as u8]; | ||
| 971 | + v.extend_from_slice(body); | ||
| 972 | + v | ||
| 973 | + } | ||
| 974 | + | ||
| 975 | + /// Probe request with full control over IEs and sequence number. | ||
| 976 | + fn probe_req_ies(sta: &MacAddr, ssid: Option<&str>, ies: &[Vec<u8>], seq: u16) -> Vec<u8> { | ||
| 977 | + let mut v = Vec::new(); | ||
| 978 | + v.extend_from_slice(&0x0040u16.to_le_bytes()); // FC: probe request | ||
| 979 | + v.extend_from_slice(&0u16.to_le_bytes()); // duration | ||
| 980 | + v.extend_from_slice(&MacAddr::BROADCAST.0); // addr1 | ||
| 981 | + v.extend_from_slice(&sta.0); // addr2 | ||
| 982 | + v.extend_from_slice(&MacAddr::BROADCAST.0); // addr3 | ||
| 983 | + v.extend_from_slice(&(seq << 4).to_le_bytes()); // seq<<4 | frag 0 | ||
| 984 | + match ssid { | ||
| 985 | + Some(s) => v.extend_from_slice(&ie_bytes(dot11::IE_SSID, s.as_bytes())), | ||
| 986 | + None => v.extend_from_slice(&ie_bytes(dot11::IE_SSID, b"")), | ||
| 987 | + } | ||
| 988 | + for body in ies { | ||
| 989 | + v.extend_from_slice(body); | ||
| 990 | + } | ||
| 991 | + v | ||
| 992 | + } | ||
| 993 | + | ||
| 994 | + fn probe_seq(sta: &MacAddr, ssid: Option<&str>, seq: u16) -> Vec<u8> { | ||
| 995 | + let ies = [ie_bytes(1, &[0x82, 0x84, 0x8b, 0x96]), ie_bytes(50, &[0x0c, 0x12])]; | ||
| 996 | + probe_req_ies(sta, ssid, &ies, seq) | ||
| 997 | + } | ||
| 998 | + | ||
| 999 | + /// Minimal WPS UUID-E attribute in a vendor IE. | ||
| 1000 | + fn wps_uuid_ie(uuid: &[u8; 16]) -> Vec<u8> { | ||
| 1001 | + let mut body = vec![0x00, 0x50, 0xf2, 0x04]; | ||
| 1002 | + body.extend_from_slice(&0x1047u16.to_be_bytes()); | ||
| 1003 | + body.extend_from_slice(&16u16.to_be_bytes()); | ||
| 1004 | + body.extend_from_slice(uuid); | ||
| 1005 | + ie_bytes(dot11::IE_VENDOR, &body) | ||
| 1006 | + } | ||
| 1007 | + | ||
| 425 | #[test] | 1008 | #[test] |
| 426 | fn beacon_attached_creates_ap_with_ssid_and_channel() { | 1009 | fn beacon_attached_creates_ap_with_ssid_and_channel() { |
| 427 | let (tx, rx) = crossbeam_channel::unbounded(); | 1010 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 428 | - let mut sc = Scanner::new(-85); | 1011 | + let mut sc = test_scanner(); |
| 429 | let now: u64 = 0; | 1012 | let now: u64 = 0; |
| 430 | sc.ingest(&meta(-42, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); | 1013 | sc.ingest(&meta(-42, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); |
| 431 | match rx.try_recv() { | 1014 | match rx.try_recv() { |
| @@ -442,7 +1025,7 @@ mod tests { | |||
| 442 | #[test] | 1025 | #[test] |
| 443 | fn beacon_uses_freq_hint_when_no_ds_ie() { | 1026 | fn beacon_uses_freq_hint_when_no_ds_ie() { |
| 444 | let (tx, rx) = crossbeam_channel::unbounded(); | 1027 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 445 | - let mut sc = Scanner::new(-85); | 1028 | + let mut sc = test_scanner(); |
| 446 | let now: u64 = 0; | 1029 | let now: u64 = 0; |
| 447 | let mut f = beacon_frame(&ap(), "parafin", 6); | 1030 | let mut f = beacon_frame(&ap(), "parafin", 6); |
| 448 | f.truncate(f.len() - 3); // drop DS IE | 1031 | f.truncate(f.len() - 3); // drop DS IE |
| @@ -456,7 +1039,7 @@ mod tests { | |||
| 456 | #[test] | 1039 | #[test] |
| 457 | fn weak_beacon_not_created_but_update_accepted_later() { | 1040 | fn weak_beacon_not_created_but_update_accepted_later() { |
| 458 | let (tx, rx) = crossbeam_channel::unbounded(); | 1041 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 459 | - let mut sc = Scanner::new(-85); | 1042 | + let mut sc = test_scanner(); |
| 460 | let now: u64 = 0; | 1043 | let now: u64 = 0; |
| 461 | // -90 < floor: no event, no entry. | 1044 | // -90 < floor: no event, no entry. |
| 462 | sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); | 1045 | sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); |
| @@ -473,7 +1056,7 @@ mod tests { | |||
| 473 | #[test] | 1056 | #[test] |
| 474 | fn rssi_improvement_emits_update_worsening_does_not() { | 1057 | fn rssi_improvement_emits_update_worsening_does_not() { |
| 475 | let (tx, rx) = crossbeam_channel::unbounded(); | 1058 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 476 | - let mut sc = Scanner::new(-85); | 1059 | + let mut sc = test_scanner(); |
| 477 | let now: u64 = 0; | 1060 | let now: u64 = 0; |
| 478 | sc.ingest(&meta(-70, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); | 1061 | sc.ingest(&meta(-70, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); |
| 479 | let _ = rx.try_recv(); // creation | 1062 | let _ = rx.try_recv(); // creation |
| @@ -489,28 +1072,169 @@ mod tests { | |||
| 489 | #[test] | 1072 | #[test] |
| 490 | fn probe_req_creates_client_and_data_freshens() { | 1073 | fn probe_req_creates_client_and_data_freshens() { |
| 491 | let (tx, rx) = crossbeam_channel::unbounded(); | 1074 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 492 | - let mut sc = Scanner::new(-85); | 1075 | + let mut sc = test_scanner(); |
| 493 | let now: u64 = 0; | 1076 | let now: u64 = 0; |
| 494 | sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), Some("parafin")), now, &tx); | 1077 | sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), Some("parafin")), now, &tx); |
| 1078 | + // Novel probe → ProbeObserved first, then the pairing decision, | ||
| 1079 | + // then the client creation carrying the group id already. | ||
| 1080 | + match rx.try_recv() { | ||
| 1081 | + Ok(Event::ProbeObserved(p)) => { | ||
| 1082 | + assert_eq!(p.client, sta()); | ||
| 1083 | + assert_eq!(p.ssid.as_deref(), Some("parafin")); | ||
| 1084 | + assert_eq!(p.rssi_dbm, -55); | ||
| 1085 | + } | ||
| 1086 | + other => panic!("expected ProbeObserved, got {other:?}"), | ||
| 1087 | + } | ||
| 1088 | + match rx.try_recv() { | ||
| 1089 | + Ok(Event::ClientIdent { mac, group, confidence }) => { | ||
| 1090 | + assert_eq!(mac, sta()); | ||
| 1091 | + assert_eq!(confidence, IdentConfidence::Probable); | ||
| 1092 | + let _ = group; | ||
| 1093 | + } | ||
| 1094 | + other => panic!("expected ClientIdent, got {other:?}"), | ||
| 1095 | + } | ||
| 495 | match rx.try_recv() { | 1096 | match rx.try_recv() { |
| 496 | Ok(Event::ClientUpdated(c)) => { | 1097 | Ok(Event::ClientUpdated(c)) => { |
| 497 | assert_eq!(c.mac, sta()); | 1098 | assert_eq!(c.mac, sta()); |
| 498 | assert_eq!(c.ap, None); | 1099 | assert_eq!(c.ap, None); |
| 1100 | + assert_eq!(c.ident_group, Some(1), "creation carries the group id"); | ||
| 499 | } | 1101 | } |
| 500 | other => panic!("expected ClientUpdated, got {other:?}"), | 1102 | other => panic!("expected ClientUpdated, got {other:?}"), |
| 501 | } | 1103 | } |
| 1104 | + // A repeat of the SAME probe inside 60 s is deduped — no | ||
| 1105 | + // ProbeObserved (the client liveness refresh is silent here since | ||
| 1106 | + // neither RSSI nor ap changed). | ||
| 1107 | + sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), Some("parafin")), now, &tx); | ||
| 1108 | + assert!(rx.try_recv().is_err()); | ||
| 1109 | + // A different SSID from the same client is a fresh observation. | ||
| 1110 | + sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), None), now, &tx); | ||
| 1111 | + match rx.try_recv() { | ||
| 1112 | + Ok(Event::ProbeObserved(p)) => assert_eq!(p.ssid, None), | ||
| 1113 | + other => panic!("expected ProbeObserved(wildcard), got {other:?}"), | ||
| 1114 | + } | ||
| 502 | sc.ingest(&meta(-55, 0), &data_frame_tods(&ap(), &sta()), now, &tx); | 1115 | sc.ingest(&meta(-55, 0), &data_frame_tods(&ap(), &sta()), now, &tx); |
| 503 | match rx.try_recv() { | 1116 | match rx.try_recv() { |
| 504 | Ok(Event::ClientUpdated(c)) => assert_eq!(c.ap, Some(ap())), | 1117 | Ok(Event::ClientUpdated(c)) => assert_eq!(c.ap, Some(ap())), |
| 505 | other => panic!("expected ClientUpdated with ap, got {other:?}"), | 1118 | other => panic!("expected ClientUpdated with ap, got {other:?}"), |
| 506 | } | 1119 | } |
| 507 | - assert_eq!(sc.clients[&sta()].frames, 2); | 1120 | + assert_eq!(sc.clients[&sta()].frames, 4); |
| 1121 | + } | ||
| 1122 | + | ||
| 1123 | + #[test] | ||
| 1124 | + fn deauth_flags_client_disconnected_exactly_once() { | ||
| 1125 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1126 | + let mut sc = test_scanner(); | ||
| 1127 | + let now: u64 = 0; | ||
| 1128 | + sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), Some("parafin")), now, &tx); | ||
| 1129 | + let _ = rx.try_recv(); // ProbeObserved | ||
| 1130 | + let _ = rx.try_recv(); // ClientIdent (pairing decision) | ||
| 1131 | + let _ = rx.try_recv(); // creation event | ||
| 1132 | + assert!(sc.clients[&sta()].connected); | ||
| 1133 | + | ||
| 1134 | + // AP → client deauth: state flips, one update event. | ||
| 1135 | + let f = dot11::build_deauth(&ap(), &sta(), 7); | ||
| 1136 | + sc.ingest(&meta(-55, 0), &f, now, &tx); | ||
| 1137 | + match rx.try_recv() { | ||
| 1138 | + Ok(Event::ClientUpdated(c)) => { | ||
| 1139 | + assert_eq!(c.mac, sta()); | ||
| 1140 | + assert!(!c.connected); | ||
| 1141 | + } | ||
| 1142 | + other => panic!("expected ClientUpdated(disconnected), got {other:?}"), | ||
| 1143 | + } | ||
| 1144 | + assert!(!sc.clients[&sta()].connected); | ||
| 1145 | + | ||
| 1146 | + // Repeated deauths against an already-flagged station: silent. | ||
| 1147 | + sc.ingest(&meta(-55, 0), &f, now, &tx); | ||
| 1148 | + sc.ingest(&meta(-55, 0), &f, now, &tx); | ||
| 1149 | + assert!(rx.try_recv().is_err()); | ||
| 1150 | + assert!(!sc.clients[&sta()].connected); | ||
| 1151 | + } | ||
| 1152 | + | ||
| 1153 | + #[test] | ||
| 1154 | + fn client_frame_after_deauth_reconnects_it() { | ||
| 1155 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1156 | + let mut sc = test_scanner(); | ||
| 1157 | + let now: u64 = 0; | ||
| 1158 | + sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), Some("parafin")), now, &tx); | ||
| 1159 | + let _ = rx.try_recv(); // ProbeObserved | ||
| 1160 | + let _ = rx.try_recv(); // ClientIdent (pairing decision) | ||
| 1161 | + let _ = rx.try_recv(); // creation | ||
| 1162 | + sc.ingest(&meta(-50, 0), &dot11::build_deauth(&ap(), &sta(), 7), now, &tx); | ||
| 1163 | + let _ = rx.try_recv(); // disconnect flip | ||
| 1164 | + assert!(!sc.clients[&sta()].connected); | ||
| 1165 | + | ||
| 1166 | + // Station talks again: connected flips back true and the update | ||
| 1167 | + // event fires. | ||
| 1168 | + sc.ingest(&meta(-55, 0), &data_frame_tods(&ap(), &sta()), now, &tx); | ||
| 1169 | + match rx.try_recv() { | ||
| 1170 | + Ok(Event::ClientUpdated(c)) => { | ||
| 1171 | + assert_eq!(c.mac, sta()); | ||
| 1172 | + assert!(c.connected); | ||
| 1173 | + } | ||
| 1174 | + other => panic!("expected ClientUpdated(reconnected), got {other:?}"), | ||
| 1175 | + } | ||
| 1176 | + assert!(sc.clients[&sta()].connected); | ||
| 1177 | + } | ||
| 1178 | + | ||
| 1179 | + #[test] | ||
| 1180 | + fn client_initiated_disassoc_flags_disconnect() { | ||
| 1181 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1182 | + let mut sc = test_scanner(); | ||
| 1183 | + let now: u64 = 0; | ||
| 1184 | + sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), None), now, &tx); | ||
| 1185 | + let _ = rx.try_recv(); // ProbeObserved | ||
| 1186 | + let _ = rx.try_recv(); // ClientIdent (pairing decision) | ||
| 1187 | + let _ = rx.try_recv(); // creation | ||
| 1188 | + | ||
| 1189 | + // Disassoc (FC 0x00a0) sent BY the station: addr2 = transmitter. | ||
| 1190 | + let mut f = Vec::new(); | ||
| 1191 | + f.extend_from_slice(&0x00a0u16.to_le_bytes()); | ||
| 1192 | + f.extend_from_slice(&0u16.to_le_bytes()); | ||
| 1193 | + f.extend_from_slice(&ap().0); // addr1 = ap | ||
| 1194 | + f.extend_from_slice(&sta().0); // addr2 = client transmitter | ||
| 1195 | + f.extend_from_slice(&ap().0); // addr3 = bssid | ||
| 1196 | + f.extend_from_slice(&0u16.to_le_bytes()); // seq | ||
| 1197 | + f.extend_from_slice(&8u16.to_le_bytes()); // reason: leaving | ||
| 1198 | + sc.ingest(&meta(-55, 0), &f, now, &tx); | ||
| 1199 | + match rx.try_recv() { | ||
| 1200 | + Ok(Event::ClientUpdated(c)) => assert!(!c.connected), | ||
| 1201 | + other => panic!("expected ClientUpdated(disconnected), got {other:?}"), | ||
| 1202 | + } | ||
| 1203 | + assert!(!sc.clients[&sta()].connected); | ||
| 1204 | + } | ||
| 1205 | + | ||
| 1206 | + #[test] | ||
| 1207 | + fn deauth_not_touching_a_known_client_is_ignored() { | ||
| 1208 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1209 | + let mut sc = test_scanner(); | ||
| 1210 | + let now: u64 = 0; | ||
| 1211 | + sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), None), now, &tx); | ||
| 1212 | + let _ = rx.try_recv(); // ProbeObserved | ||
| 1213 | + let _ = rx.try_recv(); // ClientIdent (pairing decision) | ||
| 1214 | + let _ = rx.try_recv(); // creation | ||
| 1215 | + | ||
| 1216 | + // Unknown target: neither side tracked. | ||
| 1217 | + let other: MacAddr = "de:ad:be:ef:00:01".parse().unwrap(); | ||
| 1218 | + sc.ingest(&meta(-50, 0), &dot11::build_deauth(&ap(), &other, 7), now, &tx); | ||
| 1219 | + assert!(rx.try_recv().is_err()); | ||
| 1220 | + assert!(sc.clients[&sta()].connected); | ||
| 1221 | + | ||
| 1222 | + // Broadcast deauth from a tracked AP: broadcast is not a client | ||
| 1223 | + // row, and (unless the AP is a client) nothing flips. | ||
| 1224 | + sc.ingest( | ||
| 1225 | + &meta(-50, 0), | ||
| 1226 | + &dot11::build_deauth(&ap(), &MacAddr::BROADCAST, 7), | ||
| 1227 | + now, | ||
| 1228 | + &tx, | ||
| 1229 | + ); | ||
| 1230 | + assert!(rx.try_recv().is_err()); | ||
| 1231 | + assert!(sc.clients[&sta()].connected); | ||
| 508 | } | 1232 | } |
| 509 | 1233 | ||
| 510 | #[test] | 1234 | #[test] |
| 511 | fn multicast_ta_is_ignored() { | 1235 | fn multicast_ta_is_ignored() { |
| 512 | let (tx, rx) = crossbeam_channel::unbounded(); | 1236 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 513 | - let mut sc = Scanner::new(-85); | 1237 | + let mut sc = test_scanner(); |
| 514 | let now: u64 = 0; | 1238 | let now: u64 = 0; |
| 515 | let mcast = MacAddr([0x33, 0x33, 0, 0, 0, 1]); | 1239 | let mcast = MacAddr([0x33, 0x33, 0, 0, 0, 1]); |
| 516 | sc.ingest(&meta(-40, 0), &probe_req_frame(&mcast, None), now, &tx); | 1240 | sc.ingest(&meta(-40, 0), &probe_req_frame(&mcast, None), now, &tx); |
| @@ -521,12 +1245,14 @@ mod tests { | |||
| 521 | #[test] | 1245 | #[test] |
| 522 | fn aging_emits_ap_lost_and_drops_clients() { | 1246 | fn aging_emits_ap_lost_and_drops_clients() { |
| 523 | let (tx, rx) = crossbeam_channel::unbounded(); | 1247 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 524 | - let mut sc = Scanner::new(-85); | 1248 | + let mut sc = test_scanner(); |
| 525 | let t0: u64 = 1_000; | 1249 | let t0: u64 = 1_000; |
| 526 | sc.ingest(&meta(-40, 0), &beacon_frame(&ap(), "parafin", 6), t0, &tx); | 1250 | sc.ingest(&meta(-40, 0), &beacon_frame(&ap(), "parafin", 6), t0, &tx); |
| 527 | sc.ingest(&meta(-40, 0), &probe_req_frame(&sta(), None), t0, &tx); | 1251 | sc.ingest(&meta(-40, 0), &probe_req_frame(&sta(), None), t0, &tx); |
| 528 | - let _ = rx.try_recv(); | 1252 | + let _ = rx.try_recv(); // ApUpdated |
| 529 | - let _ = rx.try_recv(); | 1253 | + let _ = rx.try_recv(); // ProbeObserved |
| 1254 | + let _ = rx.try_recv(); // ClientIdent (pairing decision) | ||
| 1255 | + let _ = rx.try_recv(); // ClientUpdated | ||
| 530 | 1256 | ||
| 531 | // 31 s later: AP expired, client still alive. | 1257 | // 31 s later: AP expired, client still alive. |
| 532 | let t1 = t0 + 31_000; | 1258 | let t1 = t0 + 31_000; |
| @@ -537,9 +1263,284 @@ mod tests { | |||
| 537 | } | 1263 | } |
| 538 | assert!(sc.clients.contains_key(&sta())); | 1264 | assert!(sc.clients.contains_key(&sta())); |
| 539 | 1265 | ||
| 540 | - // 61 s: client gone too. | 1266 | + // 61 s: client gone too, with a ClientLost for the UI. |
| 541 | sc.expire(t0 + 61_000, &tx); | 1267 | sc.expire(t0 + 61_000, &tx); |
| 542 | assert!(sc.clients.is_empty()); | 1268 | assert!(sc.clients.is_empty()); |
| 1269 | + match rx.try_recv() { | ||
| 1270 | + Ok(Event::ClientLost(m)) => assert_eq!(m, sta()), | ||
| 1271 | + other => panic!("expected ClientLost, got {other:?}"), | ||
| 1272 | + } | ||
| 1273 | + } | ||
| 1274 | + | ||
| 1275 | + #[test] | ||
| 1276 | + fn deauth_alert_window_threshold() { | ||
| 1277 | + let mut counts = VecDeque::new(); | ||
| 1278 | + // 9 stamps inside the window → no alert. | ||
| 1279 | + for i in 0..9 { | ||
| 1280 | + assert_eq!(deauth_alert(&mut counts, 1_000 + i * 100), None); | ||
| 1281 | + } | ||
| 1282 | + // The 10th inside 10 s trips it. | ||
| 1283 | + assert_eq!(deauth_alert(&mut counts, 2_000), Some(10)); | ||
| 1284 | + // Stamps older than 10 s are pruned: now = 20_000 drops them all. | ||
| 1285 | + assert_eq!(deauth_alert(&mut counts, 20_000), None); | ||
| 1286 | + assert_eq!(counts.len(), 1); | ||
| 1287 | + } | ||
| 1288 | + | ||
| 1289 | + #[test] | ||
| 1290 | + fn deauth_storm_emits_alert_once_per_cooldown() { | ||
| 1291 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1292 | + let mut sc = test_scanner(); | ||
| 1293 | + let now: u64 = 100_000; | ||
| 1294 | + let evil: MacAddr = "66:77:88:99:aa:bb".parse().unwrap(); | ||
| 1295 | + // 9 deauths → silent; 10th → one alert. | ||
| 1296 | + for i in 0..9u64 { | ||
| 1297 | + sc.ingest( | ||
| 1298 | + &meta(-40, 0), | ||
| 1299 | + &dot11::build_deauth(&evil, &sta(), 7), | ||
| 1300 | + now + i, | ||
| 1301 | + &tx, | ||
| 1302 | + ); | ||
| 1303 | + } | ||
| 1304 | + assert!(rx.try_recv().is_err()); | ||
| 1305 | + sc.ingest(&meta(-40, 0), &dot11::build_deauth(&evil, &sta(), 7), now + 9, &tx); | ||
| 1306 | + match rx.try_recv() { | ||
| 1307 | + Ok(Event::DeauthAlert { | ||
| 1308 | + source, | ||
| 1309 | + target, | ||
| 1310 | + count, | ||
| 1311 | + }) => { | ||
| 1312 | + assert_eq!(source, evil); | ||
| 1313 | + assert_eq!(target, sta()); | ||
| 1314 | + assert_eq!(count, 10); | ||
| 1315 | + } | ||
| 1316 | + other => panic!("expected DeauthAlert, got {other:?}"), | ||
| 1317 | + } | ||
| 1318 | + // Cooldown: further deauths inside 30 s stay silent. | ||
| 1319 | + for i in 0..15u64 { | ||
| 1320 | + sc.ingest( | ||
| 1321 | + &meta(-40, 0), | ||
| 1322 | + &dot11::build_deauth(&evil, &sta(), 7), | ||
| 1323 | + now + 100 + i, | ||
| 1324 | + &tx, | ||
| 1325 | + ); | ||
| 1326 | + } | ||
| 1327 | + assert!(rx.try_recv().is_err()); | ||
| 1328 | + } | ||
| 1329 | + | ||
| 1330 | + #[test] | ||
| 1331 | + fn own_deauth_sources_are_suppressed() { | ||
| 1332 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1333 | + let own: MacAddr = "02:11:22:33:44:55".parse().unwrap(); | ||
| 1334 | + let suppress: Arc<Mutex<HashSet<MacAddr>>> = Arc::new(Mutex::new(HashSet::new())); | ||
| 1335 | + suppress.lock().unwrap().insert(ap()); | ||
| 1336 | + let mut sc = Scanner::new(-85, own, suppress); | ||
| 1337 | + let now: u64 = 100_000; | ||
| 1338 | + // Blasts from our monitor MAC and from the user-deauthed AP both | ||
| 1339 | + // stay silent even past the threshold. | ||
| 1340 | + for i in 0..20u64 { | ||
| 1341 | + sc.ingest(&meta(-40, 0), &dot11::build_deauth(&own, &sta(), 7), now + i, &tx); | ||
| 1342 | + sc.ingest(&meta(-40, 0), &dot11::build_deauth(&ap(), &sta(), 7), now + i, &tx); | ||
| 1343 | + } | ||
| 1344 | + assert!(rx.try_recv().is_err()); | ||
| 1345 | + } | ||
| 1346 | + | ||
| 1347 | + /// Hidden-SSID beacon (zero-len SSID IE) followed by an assoc request | ||
| 1348 | + /// naming the real SSID: the AP row gains the name. | ||
| 1349 | + #[test] | ||
| 1350 | + fn assoc_req_reveals_hidden_ssid() { | ||
| 1351 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1352 | + let mut sc = test_scanner(); | ||
| 1353 | + let now: u64 = 0; | ||
| 1354 | + // Beacon with empty SSID. | ||
| 1355 | + sc.ingest(&meta(-45, 0), &beacon_frame(&ap(), "", 6), now, &tx); | ||
| 1356 | + match rx.try_recv() { | ||
| 1357 | + Ok(Event::ApUpdated(a)) => assert_eq!(a.ssid, ""), | ||
| 1358 | + other => panic!("expected ApUpdated(hidden), got {other:?}"), | ||
| 1359 | + } | ||
| 1360 | + // Assoc request: FC 0x0000, addr1=bssid, addr2=sta, fixed params, | ||
| 1361 | + // SSID IE with the real name. | ||
| 1362 | + let mut f = Vec::new(); | ||
| 1363 | + f.extend_from_slice(&0x0000u16.to_le_bytes()); | ||
| 1364 | + f.extend_from_slice(&0u16.to_le_bytes()); | ||
| 1365 | + f.extend_from_slice(&ap().0); // addr1 = bssid | ||
| 1366 | + f.extend_from_slice(&sta().0); // addr2 = station | ||
| 1367 | + f.extend_from_slice(&ap().0); // addr3 = bssid | ||
| 1368 | + f.extend_from_slice(&0u16.to_le_bytes()); // seq | ||
| 1369 | + f.extend_from_slice(&0u16.to_le_bytes()); // capability | ||
| 1370 | + f.extend_from_slice(&10u16.to_le_bytes()); // listen interval | ||
| 1371 | + f.push(0); // SSID IE | ||
| 1372 | + f.push(7); | ||
| 1373 | + f.extend_from_slice(b"parafin"); | ||
| 1374 | + sc.ingest(&meta(-50, 0), &f, now, &tx); | ||
| 1375 | + // Pairing decision first, then client creation, then the ApUpdated | ||
| 1376 | + // revealing the ssid. | ||
| 1377 | + match rx.try_recv() { | ||
| 1378 | + Ok(Event::ClientIdent { mac, .. }) => assert_eq!(mac, sta()), | ||
| 1379 | + other => panic!("expected ClientIdent, got {other:?}"), | ||
| 1380 | + } | ||
| 1381 | + match rx.try_recv() { | ||
| 1382 | + Ok(Event::ClientUpdated(c)) => assert_eq!(c.ap, Some(ap())), | ||
| 1383 | + other => panic!("expected ClientUpdated, got {other:?}"), | ||
| 1384 | + } | ||
| 1385 | + match rx.try_recv() { | ||
| 1386 | + Ok(Event::ApUpdated(a)) => { | ||
| 1387 | + assert_eq!(a.bssid, ap()); | ||
| 1388 | + assert_eq!(a.ssid, "parafin"); | ||
| 1389 | + } | ||
| 1390 | + other => panic!("expected ApUpdated(revealed), got {other:?}"), | ||
| 1391 | + } | ||
| 1392 | + assert_eq!(sc.aps[&ap()].ssid, "parafin"); | ||
| 1393 | + } | ||
| 1394 | + | ||
| 1395 | + // -- MAC-randomization pairing --------------------------------------- | ||
| 1396 | + | ||
| 1397 | + /// Pop events up to and including the next ClientIdent (probe-panel | ||
| 1398 | + /// and client-row events are ingestion noise for pairing tests). | ||
| 1399 | + fn expect_ident( | ||
| 1400 | + rx: &crossbeam_channel::Receiver<Event>, | ||
| 1401 | + ) -> (MacAddr, u64, IdentConfidence) { | ||
| 1402 | + loop { | ||
| 1403 | + match rx.try_recv() { | ||
| 1404 | + Ok(Event::ClientIdent { mac, group, confidence }) => { | ||
| 1405 | + return (mac, group, confidence); | ||
| 1406 | + } | ||
| 1407 | + Ok(_) => continue, | ||
| 1408 | + Err(e) => panic!("expected ClientIdent, got {e:?}"), | ||
| 1409 | + } | ||
| 1410 | + } | ||
| 1411 | + } | ||
| 1412 | + | ||
| 1413 | + fn drain(rx: &crossbeam_channel::Receiver<Event>) { | ||
| 1414 | + while rx.try_recv().is_ok() {} | ||
| 1415 | + } | ||
| 1416 | + | ||
| 1417 | + #[test] | ||
| 1418 | + fn pairing_shared_ssid_pairs_rotated_macs() { | ||
| 1419 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1420 | + let mut sc = test_scanner(); | ||
| 1421 | + let now: u64 = 0; | ||
| 1422 | + let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap(); | ||
| 1423 | + let m2: MacAddr = "06:bb:bb:bb:bb:02".parse().unwrap(); | ||
| 1424 | + | ||
| 1425 | + sc.ingest(&meta(-50, 0), &probe_seq(&m1, Some("parafin"), 7), now, &tx); | ||
| 1426 | + let (mac, g1, conf) = expect_ident(&rx); | ||
| 1427 | + assert_eq!(mac, m1); | ||
| 1428 | + assert_eq!(conf, IdentConfidence::Probable); | ||
| 1429 | + sc.ingest(&meta(-48, 0), &probe_seq(&m2, Some("parafin"), 8), now + 1, &tx); | ||
| 1430 | + let (mac, g2, conf) = expect_ident(&rx); | ||
| 1431 | + // Same IE chain + same probed SSID = same radio, strong witness. | ||
| 1432 | + assert_eq!(mac, m2); | ||
| 1433 | + assert_eq!(g2, g1, "rotated MAC lands in the same group"); | ||
| 1434 | + assert_eq!(conf, IdentConfidence::Strong); | ||
| 1435 | + // Second frame from m1: no new pairing events. | ||
| 1436 | + sc.ingest(&meta(-49, 0), &probe_seq(&m1, None, 9), now + 2, &tx); | ||
| 1437 | + drain(&rx); | ||
| 1438 | + assert!(rx.try_recv().is_err()); | ||
| 1439 | + assert!(sc.groups.id_of(&m1).is_some() && sc.groups.id_of(&m2).is_some()); | ||
| 1440 | + } | ||
| 1441 | + | ||
| 1442 | + #[test] | ||
| 1443 | + fn pairing_seq_continuity_witness() { | ||
| 1444 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1445 | + let mut sc = test_scanner(); | ||
| 1446 | + let now: u64 = 0; | ||
| 1447 | + let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap(); | ||
| 1448 | + let m2: MacAddr = "06:cc:cc:cc:cc:03".parse().unwrap(); | ||
| 1449 | + | ||
| 1450 | + sc.ingest(&meta(-50, 0), &probe_seq(&m1, None, 100), now, &tx); | ||
| 1451 | + let _ = expect_ident(&rx); | ||
| 1452 | + // Wildcard probes (no shared SSID), but the sequence counter | ||
| 1453 | + // continues uninterrupted across the rotation. | ||
| 1454 | + sc.ingest(&meta(-50, 0), &probe_seq(&m2, None, 101), now + 1, &tx); | ||
| 1455 | + let (_, _, conf) = expect_ident(&rx); | ||
| 1456 | + assert_eq!(conf, IdentConfidence::Strong); | ||
| 1457 | + // A gap beyond the window is NOT continuity: downgrade. | ||
| 1458 | + let m3: MacAddr = "0e:dd:dd:dd:dd:04".parse().unwrap(); | ||
| 1459 | + sc.ingest(&meta(-50, 0), &probe_seq(&m3, None, 200), now + 2, &tx); | ||
| 1460 | + // m3 shares the fingerprint with the group's members, but seq 200 | ||
| 1461 | + // vs last 101 is 99 away → probable only. | ||
| 1462 | + let (_, _, conf) = expect_ident(&rx); | ||
| 1463 | + assert_eq!(conf, IdentConfidence::Probable); | ||
| 1464 | + } | ||
| 1465 | + | ||
| 1466 | + #[test] | ||
| 1467 | + fn pairing_uuid_e_is_exact() { | ||
| 1468 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1469 | + let mut sc = test_scanner(); | ||
| 1470 | + let now: u64 = 0; | ||
| 1471 | + let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap(); | ||
| 1472 | + let m2: MacAddr = "06:ee:ee:ee:ee:05".parse().unwrap(); | ||
| 1473 | + let uuid = [0xABu8; 16]; | ||
| 1474 | + | ||
| 1475 | + let f1 = probe_req_ies(&m1, Some("parafin"), &[wps_uuid_ie(&uuid)], 7); | ||
| 1476 | + sc.ingest(&meta(-50, 0), &f1, now, &tx); | ||
| 1477 | + let _ = expect_ident(&rx); | ||
| 1478 | + let f2 = probe_req_ies(&m2, None, &[wps_uuid_ie(&uuid)], 9); | ||
| 1479 | + sc.ingest(&meta(-50, 0), &f2, now + 1, &tx); | ||
| 1480 | + let (mac, g2, conf) = expect_ident(&rx); | ||
| 1481 | + assert_eq!(mac, m2); | ||
| 1482 | + assert_eq!(conf, IdentConfidence::Exact, "UUID-E is a certain witness"); | ||
| 1483 | + // Same UUID but a COMPLETELY different IE chain (firmware update | ||
| 1484 | + // between rotations, fingerprint unusable) still pairs. | ||
| 1485 | + let m3: MacAddr = "0a:dd:dd:dd:dd:07".parse().unwrap(); | ||
| 1486 | + let f3 = probe_req_ies( | ||
| 1487 | + &m3, | ||
| 1488 | + None, | ||
| 1489 | + &[ie_bytes(3, &[1u8]), wps_uuid_ie(&uuid)], | ||
| 1490 | + 40, | ||
| 1491 | + ); | ||
| 1492 | + sc.ingest(&meta(-50, 0), &f3, now + 2, &tx); | ||
| 1493 | + let (mac, g3, conf) = expect_ident(&rx); | ||
| 1494 | + assert_eq!(mac, m3); | ||
| 1495 | + assert_eq!(g3, g2, "UUID-E pairs across a fingerprint break"); | ||
| 1496 | + assert_eq!(conf, IdentConfidence::Exact); | ||
| 1497 | + } | ||
| 1498 | + | ||
| 1499 | + #[test] | ||
| 1500 | + fn pairing_different_fingerprints_stay_separate() { | ||
| 1501 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1502 | + let mut sc = test_scanner(); | ||
| 1503 | + let now: u64 = 0; | ||
| 1504 | + let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap(); | ||
| 1505 | + let m2: MacAddr = "06:bb:bb:bb:bb:02".parse().unwrap(); | ||
| 1506 | + | ||
| 1507 | + sc.ingest(&meta(-50, 0), &probe_seq(&m1, Some("parafin"), 7), now, &tx); | ||
| 1508 | + let (_, g1, _) = expect_ident(&rx); | ||
| 1509 | + // Same probed SSID, DIFFERENT IE chain → different device class. | ||
| 1510 | + let other = probe_req_ies( | ||
| 1511 | + &m2, | ||
| 1512 | + Some("parafin"), | ||
| 1513 | + &[ie_bytes(1, &[0x82, 0x84]), ie_bytes(3, &[6u8])], | ||
| 1514 | + 8, | ||
| 1515 | + ); | ||
| 1516 | + sc.ingest(&meta(-50, 0), &other, now + 1, &tx); | ||
| 1517 | + let (_, g2, _) = expect_ident(&rx); | ||
| 1518 | + assert_ne!(g1, g2, "fingerprint mismatch keeps radios separate"); | ||
| 1519 | + } | ||
| 1520 | + | ||
| 1521 | + #[test] | ||
| 1522 | + fn pairing_groups_outlive_client_rows() { | ||
| 1523 | + let (tx, rx) = crossbeam_channel::unbounded(); | ||
| 1524 | + let mut sc = test_scanner(); | ||
| 1525 | + let t0: u64 = 100_000; | ||
| 1526 | + let m1: MacAddr = "02:aa:aa:aa:aa:01".parse().unwrap(); | ||
| 1527 | + let m2: MacAddr = "06:ff:ff:ff:ff:06".parse().unwrap(); | ||
| 1528 | + | ||
| 1529 | + sc.ingest(&meta(-50, 0), &probe_seq(&m1, Some("parafin"), 7), t0, &tx); | ||
| 1530 | + let (_, g1, _) = expect_ident(&rx); | ||
| 1531 | + // Client row expires (60 s), but the group lives for minutes. | ||
| 1532 | + sc.expire(t0 + 61_000, &tx); | ||
| 1533 | + drain(&rx); | ||
| 1534 | + // The rotated MAC appears late and still pairs (shared SSID). | ||
| 1535 | + sc.ingest(&meta(-46, 0), &probe_seq(&m2, Some("parafin"), 8), t0 + 65_000, &tx); | ||
| 1536 | + let (_, g2, conf) = expect_ident(&rx); | ||
| 1537 | + assert_eq!(g1, g2, "group identity survives the client-row TTL"); | ||
| 1538 | + assert_eq!(conf, IdentConfidence::Strong); | ||
| 1539 | + // Full TTL (15 min) expiry destroys the group. | ||
| 1540 | + sc.ingest(&meta(-50, 0), &probe_seq(&m2, None, 9), t0 + 65_000, &tx); | ||
| 1541 | + sc.expire(t0 + 65_000 + GROUP_TTL_MS + 1, &tx); | ||
| 1542 | + assert!(sc.groups.id_of(&m1).is_none()); | ||
| 1543 | + assert!(sc.groups.id_of(&m2).is_none()); | ||
| 543 | } | 1544 | } |
| 544 | 1545 | ||
| 545 | #[test] | 1546 | #[test] |