forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

mock.rs507 lines, 16.2 KiBHistoryRawDownload
1//! Mock backend: fabricates the event stream the real radio/attack/cracker
2//! threads will eventually produce. Delete this module — and the env-flag
3//! branch in `run_app` — when the backend lands.
4
5use std::thread;
6use std::time::{Duration, Instant};
7
8use crossbeam_channel::Sender;
9
10use crate::common::{
11 AccessPoint, Akm, ChannelStat, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture,
12 ProbeInfo, Security, now_ms,
13};
14
15/// Salted deterministic PRNG (xorshift64) — no rand crate, values only need
16/// to *look* like radio noise.
17struct Rng(u64);
18
19impl Rng {
20 fn next(&mut self) -> u64 {
21 let mut x = self.0;
22 x ^= x << 13;
23 x ^= x >> 7;
24 x ^= x << 17;
25 self.0 = x;
26 x
27 }
28
29 /// Inclusive low, exclusive high.
30 fn below(&mut self, high: u64) -> u64 {
31 self.next() % high.max(1)
32 }
33}
34
35/// The mock interface, also what the header picker offers.
36pub const MOCK_IFACE: &str = "wlp14s0";
37
38pub const MOCK_BSSID: MacAddr = MacAddr([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]);
39
40pub const MOCK_CLIENTS: [MacAddr; 4] = [
41 MacAddr([0x11, 0x22, 0x33, 0x44, 0x55, 0x66]),
42 MacAddr([0x22, 0x33, 0x44, 0x55, 0x66, 0x77]),
43 MacAddr([0x33, 0x44, 0x55, 0x66, 0x77, 0x88]),
44 MacAddr([0x44, 0x55, 0x66, 0x77, 0x88, 0x99]),
45];
46
47/// Locally-administered MACs the mock pairs into one device group (the
48/// MAC-randomization storyline: ROT1 visible from start, ROT2 "rotates in").
49pub const MOCK_ROT1: MacAddr = MacAddr([0x02, 0xa0, 0xb1, 0xc2, 0xd3, 0xe4]);
50pub const MOCK_ROT2: MacAddr = MacAddr([0x06, 0x5f, 0x4e, 0x3d, 0x2c, 0x1b]);
51
52/// Channel sets the mock's scan reports over time. Real scans gain and lose
53/// channels as devices come and go; rotating the set exercises both the
54/// Networks page's fixed-height activity timeline (3 blocks of 8 rows for
55/// the 20-channel set) and the crowded-channel warning. Rotated every
56/// [`CHAN_SET_SNAPSHOTS`] snapshots.
57const MOCK_CHAN_SETS: &[&[u8]] = &[
58 &[1, 6, 11, 36],
59 &[
60 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 36, 40, 44, 48, 52, 56, 60, 64, 100,
61 ],
62 &[1, 6, 11, 36, 44, 100],
63 &[6, 11, 36],
64];
65
66/// Counter slots kept for the rotating channel sets — must be ≥ the widest
67/// set in [`MOCK_CHAN_SETS`] (asserted in tests).
68const MAX_MOCK_CHANS: usize = 20;
69
70/// Snapshots per channel-set rotation (2 s each).
71const CHAN_SET_SNAPSHOTS: u64 = 10;
72
73fn seed_aps() -> Vec<AccessPoint> {
74 let now = now_ms();
75 let ap = |mac: [u8; 6], ssid: &str, channel, security, rssi, akms: Vec<Akm>| AccessPoint {
76 bssid: MacAddr(mac),
77 ssid: ssid.to_string(),
78 channel,
79 security,
80 rssi_dbm: rssi,
81 beacons: 200,
82 last_seen_ms: now,
83 akms,
84 };
85 vec![
86 ap(
87 [0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff],
88 "testnet",
89 6,
90 Security::Wpa2,
91 -42,
92 vec![Akm::Psk],
93 ),
94 ap(
95 [0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e],
96 "labnet",
97 1,
98 Security::Wpa2,
99 -55,
100 vec![Akm::Psk],
101 ),
102 ap(
103 [0x02, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e],
104 "coffeeshop",
105 11,
106 Security::Wpa2,
107 -68,
108 vec![Akm::Psk],
109 ),
110 ap(
111 [0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb],
112 "corp-wpa3",
113 36,
114 Security::Wpa3,
115 -61,
116 vec![Akm::Psk, Akm::Sae],
117 ),
118 ap(
119 [0x02, 0xde, 0xad, 0xbe, 0xef, 0x00],
120 "legacy-prn",
121 3,
122 Security::Wep,
123 -80,
124 Vec::new(),
125 ),
126 ap(
127 [0x02, 0x00, 0x11, 0x22, 0x33, 0x44],
128 "open-wifi",
129 6,
130 Security::Open,
131 -72,
132 Vec::new(),
133 ),
134 // Same SSID as `testnet` but OPEN + different BSSID: trips the
135 // UI's rogue-AP detection so the warning path is visible in mock.
136 ap(
137 [0x02, 0x66, 0x66, 0x66, 0x66, 0x66],
138 "testnet",
139 11,
140 Security::Open,
141 -77,
142 Vec::new(),
143 ),
144 ]
145}
146
147fn seed_clients() -> Vec<ClientInfo> {
148 let now = now_ms();
149 let cl = |mac: MacAddr, ap: MacAddr, rssi, connected: bool| ClientInfo {
150 mac,
151 ap: Some(ap),
152 rssi_dbm: rssi,
153 frames: 40,
154 last_seen_ms: now,
155 connected,
156 ident_group: None,
157 ident_conf: None,
158 };
159 vec![
160 cl(MOCK_CLIENTS[0], MOCK_BSSID, -44, true),
161 cl(MOCK_CLIENTS[1], MOCK_BSSID, -51, true),
162 cl(
163 MOCK_CLIENTS[2],
164 MacAddr([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e]),
165 -60,
166 true,
167 ),
168 // Locally-administered (randomized) MAC — the ROT2 milestone below
169 // pairs it with ROT1 as one physical radio.
170 cl(MOCK_ROT1, MOCK_BSSID, -48, true),
171 // Deauth-flagged so the disconnected state is visible in mock mode.
172 cl(
173 MOCK_CLIENTS[3],
174 MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]),
175 -63,
176 false,
177 ),
178 ]
179}
180
181/// Deterministic filler byte for fabricated crypto material.
182fn fill(byte: u64) -> u8 {
183 (byte % 251) as u8
184}
185
186/// Fabricate a syntactically valid-looking WPA1/WPA2 capture (dummy nonces,
187/// dummy MIC, dummy M2 EAPOL frame). The cracker would reject these, but the
188/// UI only displays and exports them.
189pub fn fabricate_handshake(
190 ap: MacAddr,
191 client: MacAddr,
192 essid: &str,
193 salt: u64,
194) -> HandshakeCapture {
195 let mut anonce = [0u8; 32];
196 let mut snonce = [0u8; 32];
197 let mut mic = [0u8; 16];
198 let mut rng = Rng(salt | 1);
199 for i in 0..32 {
200 anonce[i] = fill(rng.next() + i as u64);
201 snonce[i] = fill(rng.next() + 7 * i as u64);
202 }
203 for (i, b) in mic.iter_mut().enumerate() {
204 *b = fill(rng.next() + 11 * i as u64);
205 }
206 // EAPOL v1, type Key, 95-byte key descriptor + empty key data: laid out
207 // so the exporter's MIC-field offset (81..97) lands inside real bytes.
208 let mut eapol_m2 = vec![0u8; 4 + 95];
209 eapol_m2[0] = 1; // EAPOL version
210 eapol_m2[1] = 3; // type: Key
211 eapol_m2[2] = 0;
212 eapol_m2[3] = 95; // length
213 eapol_m2[4] = 2; // descriptor: RSN
214 eapol_m2[5] = 0x01; // key info: M2, pairwise, MIC set
215 eapol_m2[6] = 0x0a;
216 let mut rng = Rng(salt ^ 0x5a5a);
217 for b in eapol_m2.iter_mut().skip(7) {
218 *b = fill(rng.next());
219 }
220 // SNonce rides at key-descriptor offset 13 (EAPOL offset 17).
221 eapol_m2[17..17 + 32].copy_from_slice(&snonce);
222 // MIC field at EAPOL offset 81..97.
223 eapol_m2[81..97].copy_from_slice(&mic);
224 HandshakeCapture::new(
225 ap,
226 client,
227 essid.to_string(),
228 anonce,
229 snonce,
230 mic,
231 eapol_m2,
232 2,
233 )
234}
235
236/// Fabricate a partial M2+M3 capture — same dummy-material convention as
237/// [`fabricate_handshake`], but `partial: true` (`eapol_m2` carries the
238/// M3 frame with its MIC not zeroed; see [`HandshakeCapture::new_partial`]).
239/// Exercises the [`Event::HandshakePartial`] path in mock mode.
240pub fn fabricate_partial(ap: MacAddr, client: MacAddr, essid: &str, salt: u64) -> HandshakeCapture {
241 let full = fabricate_handshake(ap, client, essid, salt);
242 // Read the MIC BEFORE the field moves below (the accessor borrows
243 // the whole capture).
244 let mic = *full.mic();
245 HandshakeCapture::new_partial(
246 full.ap,
247 full.client,
248 full.essid,
249 full.anonce,
250 full.snonce,
251 mic,
252 full.eapol_m2,
253 full.key_ver,
254 )
255}
256
257/// Fabricate a PMKID capture against `ap`, impersonating `client`.
258pub fn fabricate_pmkid(ap: MacAddr, client: MacAddr, essid: &str, salt: u64) -> PmkidCapture {
259 let mut pmkid = [0u8; 16];
260 let mut rng = Rng(salt ^ 0xa5a5);
261 for b in &mut pmkid {
262 *b = fill(rng.next());
263 }
264 PmkidCapture {
265 ap,
266 client,
267 essid: essid.to_string(),
268 pmkid,
269 }
270}
271
272/// Spawn the mock generator thread. Sends forever until the channel closes
273/// (app exit) — error sends are simply dropped.
274pub fn spawn_mock(tx: Sender<Event>) {
275 thread::Builder::new()
276 .name("wifi_lab-mock".into())
277 .spawn(move || run(tx))
278 .expect("mock thread");
279}
280
281fn run(tx: Sender<Event>) {
282 let _ = tx.send(Event::Log(format!(
283 "mock: scanning on {MOCK_IFACE} (7 APs, 4 clients)"
284 )));
285
286 let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
287 let mut aps = seed_aps();
288 let mut clients = seed_clients();
289 for ap in &aps {
290 let _ = tx.send(Event::ApUpdated(ap.clone()));
291 }
292 for cl in &clients {
293 let _ = tx.send(Event::ClientUpdated(cl.clone()));
294 }
295
296 let started = Instant::now();
297 let mut stage = 0usize;
298 let mut tick = 0u64;
299 // Drifting cumulative per-channel counters for the ChannelStats feed,
300 // one slot per channel of the widest rotating set (see MOCK_CHAN_SETS).
301 let mut chan_frames: [u64; MAX_MOCK_CHANS] = [
302 120, 340, 60, 85, 45, 980, 150, 70, 30, 55, 210, 500, 260, 180, 95, 140, 65, 40, 25, 15,
303 ];
304 let mut chan_beacons: [u64; MAX_MOCK_CHANS] = [
305 40, 90, 12, 20, 8, 210, 33, 15, 6, 11, 55, 120, 60, 44, 22, 31, 14, 9, 5, 3,
306 ];
307 // Probe-request feed cycles these (client, ssid) pairs.
308 const PROBE_FEED: &[(MacAddr, Option<&str>)] = &[
309 (MOCK_CLIENTS[0], Some("HOME-WIFI")),
310 (MOCK_CLIENTS[1], Some("labnet")),
311 (MOCK_CLIENTS[2], None),
312 (MOCK_CLIENTS[3], Some("coffeeshop")),
313 (MOCK_CLIENTS[1], None),
314 ];
315 let mut probe_step = 0usize;
316 let mut ident_fed = false;
317 let mut deauth_alert_sent = false;
318 const LOG_LINES: &[&str] = &[
319 "hop: ch 1 → ch 6",
320 "probe request from 11:22:33:44:55:66 (\"labnet\")",
321 "hop: ch 6 → ch 11",
322 "beacon: corp-wpa3 on ch 36 (SAE)",
323 "hop: ch 36 → ch 44",
324 "data frame burst on testnet (297 fps)",
325 "probe response coffeeshop (WPA2-PSK)",
326 ];
327
328 loop {
329 thread::sleep(Duration::from_millis(200));
330 tick += 1;
331 let t = started.elapsed().as_secs_f32();
332 let now = now_ms();
333
334 // Per-channel activity snapshot every ~2 s (10 ticks).
335 if tick.is_multiple_of(10) {
336 let snapshots = tick / 10;
337 let set =
338 MOCK_CHAN_SETS[((snapshots / CHAN_SET_SNAPSHOTS) as usize) % MOCK_CHAN_SETS.len()];
339 let mut stats = Vec::with_capacity(set.len());
340 for (i, ch) in set.iter().enumerate() {
341 chan_frames[i] += 20 + rng.below(180);
342 chan_beacons[i] += rng.below(6);
343 stats.push(ChannelStat {
344 channel: *ch,
345 frames: chan_frames[i],
346 beacons: chan_beacons[i],
347 });
348 }
349 let _ = tx.send(Event::ChannelStats(stats));
350 }
351
352 // Probe-request feed every ~3 s (15 ticks).
353 if tick.is_multiple_of(15) {
354 let (client, ssid) = PROBE_FEED[probe_step % PROBE_FEED.len()];
355 probe_step += 1;
356 let _ = tx.send(Event::ProbeObserved(ProbeInfo {
357 client,
358 ssid: ssid.map(str::to_string),
359 rssi_dbm: -(40 + rng.below(45) as i8),
360 at_ms: now,
361 }));
362 }
363
364 // MAC-rotation storyline at ~6 s: a new randomized MAC appears and
365 // the correlator pairs both into device group #1.
366 if !ident_fed && t >= 6.0 {
367 ident_fed = true;
368 let _ = tx.send(Event::ClientIdent {
369 mac: MOCK_ROT1,
370 group: 1,
371 confidence: crate::common::IdentConfidence::Strong,
372 });
373 let _ = tx.send(Event::ClientUpdated(ClientInfo {
374 mac: MOCK_ROT2,
375 ap: Some(MOCK_BSSID),
376 rssi_dbm: -46,
377 frames: 3,
378 last_seen_ms: now,
379 connected: true,
380 ident_group: None,
381 ident_conf: None,
382 }));
383 let _ = tx.send(Event::ClientIdent {
384 mac: MOCK_ROT2,
385 group: 1,
386 confidence: crate::common::IdentConfidence::Strong,
387 });
388 }
389
390 // One foreign-deauth storm milestone at ~12 s.
391 if !deauth_alert_sent && t >= 12.0 {
392 deauth_alert_sent = true;
393 let _ = tx.send(Event::DeauthAlert {
394 source: MOCK_BSSID,
395 target: MacAddr::BROADCAST,
396 count: 64,
397 });
398 }
399
400 // RSSI drift + beacon/frame counters on every tick.
401 for ap in &mut aps {
402 ap.rssi_dbm = (ap.rssi_dbm + (rng.below(5) as i8 - 2)).clamp(-90, -30);
403 ap.beacons += rng.below(3);
404 ap.last_seen_ms = now;
405 let _ = tx.send(Event::ApUpdated(ap.clone()));
406 }
407 for cl in &mut clients {
408 cl.rssi_dbm = (cl.rssi_dbm + (rng.below(3) as i8 - 1)).clamp(-90, -30);
409 cl.frames += rng.below(12);
410 cl.last_seen_ms = now;
411 let _ = tx.send(Event::ClientUpdated(cl.clone()));
412 }
413
414 // Milestones, roughly one per few seconds.
415 let milestone_at = |stage: usize| t >= [2.0, 5.0, 8.0, 9.0, 11.0, 14.0][stage];
416 while stage < 4 && milestone_at(stage) {
417 match stage {
418 0 => {
419 let _ = tx.send(Event::Log(format!(
420 "locking onto testnet ({MOCK_BSSID}, ch 6)"
421 )));
422 }
423 1 => {
424 let _ = tx.send(Event::HandshakeProgress {
425 ap: MOCK_BSSID,
426 client: MOCK_CLIENTS[0],
427 have: 0b0001,
428 });
429 }
430 2 => {
431 let _ = tx.send(Event::HandshakeProgress {
432 ap: MOCK_BSSID,
433 client: MOCK_CLIENTS[0],
434 have: 0b0011,
435 });
436 }
437 3 => {
438 let cap =
439 fabricate_handshake(MOCK_BSSID, MOCK_CLIENTS[0], "testnet", 0x1234_5678);
440 let _ = tx.send(Event::HandshakeComplete(Box::new(cap)));
441 stage += 1;
442 break;
443 }
444 _ => unreachable!(),
445 }
446 stage += 1;
447 }
448
449 if stage == 4 && t >= 14.0 {
450 let cap = fabricate_pmkid(
451 MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]),
452 MOCK_CLIENTS[3],
453 "corp-wpa3",
454 0xdead_beef,
455 );
456 let _ = tx.send(Event::PmkidCaptured(cap));
457 stage += 1;
458 }
459
460 // Partial M2+M3 milestone at ~17 s (deterministic): exercises the
461 // HandshakePartial reduction — log line, [partial] picker entry,
462 // `state.partials`.
463 if stage == 5 && t >= 17.0 {
464 let cap = fabricate_partial(
465 MacAddr([0x02, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e]),
466 MOCK_CLIENTS[2],
467 "coffeeshop",
468 0xc0ff_ee11,
469 );
470 let _ = tx.send(Event::HandshakePartial(Box::new(cap)));
471 stage += 1;
472 }
473
474 if stage >= 5 && rng.next().is_multiple_of(20) {
475 let _ = tx.send(Event::Log(
476 LOG_LINES[(rng.below(LOG_LINES.len() as u64)) as usize].to_string(),
477 ));
478 }
479
480 // Occasionally nudge deauth stats so the log feels alive.
481 if stage >= 5 && t > 20.0 && rng.next().is_multiple_of(40) {
482 let _ = tx.send(Event::DeauthSent {
483 ap: MOCK_BSSID,
484 target: MOCK_CLIENTS[1],
485 count: 8,
486 });
487 }
488 }
489}
490#[cfg(test)]
491mod tests {
492 use super::*;
493
494 /// The stats feed indexes the per-channel counter arrays by position in
495 /// the rotating set — a set wider than those arrays panics the mock
496 /// thread (mock runs are how the UI is developed and screenshotted).
497 #[test]
498 fn mock_channel_sets_fit_counter_arrays() {
499 for set in MOCK_CHAN_SETS {
500 assert!(
501 set.len() <= MAX_MOCK_CHANS,
502 "channel set {set:?} exceeds MAX_MOCK_CHANS={MAX_MOCK_CHANS}"
503 );
504 }
505 assert!(!MOCK_CHAN_SETS.is_empty());
506 }
507}