forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

state.rs713 lines, 28.0 KiBHistoryRawDownload
1//! Application state: the UI-side home for everything arriving over the
2//! service event channel (mock thread or privileged-service reader).
3
4use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
5
6use crate::common::{
7 AccessPoint, ChannelStat, ClientInfo, Event, HandshakeCapture, IdentConfidence, MacAddr,
8 PmkidCapture, ProbeInfo, Security,
9};
10use crate::crypto::CrackTarget;
11
12/// Ring capacity of the on-screen log.
13pub const LOG_CAP: usize = 500;
14
15/// Live status of the (currently simulated) handshake cracker.
16#[derive(Default)]
17pub struct CrackerState {
18 /// Selected capture, as an index into [`AppState::capture_descs`] /
19 /// the aligned target vectors. Index (not description string) keyed so
20 /// a selection never depends on regenerated display strings; the
21 /// vectors are append-only, so new captures arriving mid-run cannot
22 /// shift an existing selection.
23 pub target: Option<usize>,
24 pub wordlist: Option<String>,
25 pub running: bool,
26 /// Guesses per second.
27 pub hps: f64,
28 /// Candidates tried so far.
29 pub tried: u64,
30 /// Recovered password, once found.
31 pub found: Option<String>,
32 /// Rainbow-table build job in flight (RainbowProgress feeds the
33 /// counters, RainbowBuilt clears the flag).
34 pub rainbow_building: bool,
35 /// PMKs written by the running build job.
36 pub rainbow_done: u64,
37 /// Build job throughput.
38 pub rainbow_hps: f64,
39 /// Worst-case candidate total of the running crack (wordlist lines /
40 /// brute-force space / table entries), when countable.
41 pub total: Option<u64>,
42 /// Worst-case size of the table being built (wordlist lines).
43 pub rainbow_total: Option<u64>,
44 /// The currently running attack, tracked so the UI can persist a
45 /// resume session ([`crate::store::CrackSession`]) without the
46 /// worker's cooperation. Cleared when the run settles.
47 pub active_attack: Option<crate::attack::Attack>,
48 /// A saved, interrupted run matched against a loaded capture —
49 /// shown as a resume banner on the cracker page.
50 pub resume: Option<ResumeInfo>,
51}
52
53/// Saved-run banner payload (mirror of [`crate::store::CrackSession`]
54/// resolved to the capture's current description).
55#[derive(Clone)]
56pub struct ResumeInfo {
57 /// Capture index (the [`AppState::capture_descs`] / target-select
58 /// index) of the capture this run belongs to — the Resume action sets
59 /// `CrackerState.target` from this without any string re-matching.
60 pub target_idx: usize,
61 /// Dropdown description of the capture this run belongs to (display
62 /// text for the banner; selection logic keys on `target_idx`).
63 pub target_desc: String,
64 /// Attack definition at the saved candidate offset.
65 pub attack: crate::attack::Attack,
66 /// Candidates already tried when the run was saved.
67 pub done: u64,
68 /// Worst-case total of the saved run, when countable.
69 pub total: Option<u64>,
70}
71
72/// Everything the window renders. Updated exclusively by
73/// [`AppState::apply`] so a real service can reuse the reduction logic.
74pub struct AppState {
75 /// Whether the interface is (pretending to be) capturing in monitor mode.
76 pub iface_running: bool,
77 pub ifname: String,
78 pub aps: BTreeMap<MacAddr, AccessPoint>,
79 pub clients: BTreeMap<MacAddr, ClientInfo>,
80 /// User-assigned names by MAC (APs and clients share one namespace;
81 /// a MAC is unique). Persisted to `~/wifi_lab/labels.json`
82 /// ([`crate::store`]); UI-side only.
83 pub labels: BTreeMap<MacAddr, String>,
84 pub handshakes: Vec<HandshakeCapture>,
85 pub pmkids: Vec<PmkidCapture>,
86 /// Partial M2+M3 captures (from [`Event::HandshakePartial`]): crackable
87 /// with the identical PTK/MIC math, distinguished for provenance and
88 /// export (`partial == true`, hashcat message-pair field `02`).
89 /// Deduped on (AP, client) + MIC.
90 pub partials: Vec<HandshakeCapture>,
91 /// [`capture_descs`]-aligned crack targets, in ARRIVAL ORDER
92 /// (handshakes, PMKIDs and partials interleaved as they arrived):
93 /// `capture_targets[i]` is the [`CrackTarget`] described by
94 /// `capture_descs()[i]`, so the cracker starts a run without
95 /// re-parsing an hc22000 line. Append-only by construction — new
96 /// captures never shift existing indices.
97 capture_targets: Vec<CrackTarget>,
98 pub log: VecDeque<String>,
99 pub cracker: CrackerState,
100 /// Observed probe requests, newest last.
101 pub probes: VecDeque<ProbeInfo>,
102 /// Recent RSSI samples per MAC (APs and clients keyed by their own
103 /// MAC) — the Networks page renders these as sparklines.
104 pub rssi_hist: HashMap<MacAddr, VecDeque<i8>>,
105 /// Normalized (trim, lowercase) SSIDs observed on more than one BSSID
106 /// with differing security — possible rogue APs.
107 pub rogue_ssids: HashSet<String>,
108 /// One-shot rogue-AP alert message; taken by the app drain into a toast.
109 pub rogue_alert: Option<String>,
110 /// One-shot deauth-storm alert message; taken by the app drain into a
111 /// toast.
112 pub deauth_alert: Option<String>,
113 /// Last benchmark throughput (H/s); `None` = no GPU / not run yet.
114 pub bench_gpu: Option<f64>,
115 pub bench_cpu: Option<f64>,
116 /// MAC-randomization pairing ([`Event::ClientIdent`]): device-group id +
117 /// confidence per correlated MAC. Outlives the client row (groups keep
118 /// their members while any one of them is live).
119 pub idents: HashMap<MacAddr, (u64, IdentConfidence)>,
120 /// Reverse view per group: set of currently-known member MACs (live
121 /// rows + remembered) — the Networks page shows "N MACs" per device.
122 pub ident_groups: HashMap<u64, HashSet<MacAddr>>,
123 /// One-shot pairing alert ("device rotated MAC, paired into group #N");
124 /// taken by the app drain into a toast.
125 pub ident_alert: Option<String>,
126 /// SSID (normalized) → BSSID → security seen, backing `rogue_ssids`.
127 seen_ssids: BTreeMap<String, BTreeMap<MacAddr, Security>>,
128 /// ChannelStats time-series, one entry per snapshot, oldest first
129 /// (~3 min at the scanner's 2 s cadence) — the Networks page renders
130 /// it as a scrolling per-channel activity timeline.
131 pub chan_timeline: VecDeque<Vec<ChannelStat>>,
132 /// Crack H/s samples, one per [`Event::CrackProgress`] of the current
133 /// run (cleared at run start) — the Cracker page renders it as a
134 /// throughput curve.
135 pub hps_hist: VecDeque<f64>,
136}
137
138/// Cap on [`AppState::probes`] (oldest dropped first).
139const PROBE_CAP: usize = 2000;
140
141/// RSSI samples kept per MAC in [`AppState::rssi_hist`].
142const RSSI_CAP: usize = 60;
143
144/// ChannelStats snapshots kept in [`AppState::chan_timeline`].
145const CHAN_TL_CAP: usize = 90;
146
147/// H/s samples kept in [`AppState::hps_hist`].
148const HPS_CAP: usize = 240;
149
150impl AppState {
151 pub fn new(ifname: &str) -> Self {
152 AppState {
153 iface_running: false,
154 ifname: ifname.to_string(),
155 aps: BTreeMap::new(),
156 clients: BTreeMap::new(),
157 labels: BTreeMap::new(),
158 handshakes: Vec::new(),
159 pmkids: Vec::new(),
160 partials: Vec::new(),
161 capture_targets: Vec::new(),
162 log: VecDeque::with_capacity(LOG_CAP),
163 cracker: CrackerState::default(),
164 probes: VecDeque::with_capacity(64),
165 rssi_hist: HashMap::new(),
166 rogue_ssids: HashSet::new(),
167 rogue_alert: None,
168 deauth_alert: None,
169 bench_gpu: None,
170 bench_cpu: None,
171 idents: HashMap::new(),
172 ident_groups: HashMap::new(),
173 ident_alert: None,
174 seen_ssids: BTreeMap::new(),
175 chan_timeline: VecDeque::with_capacity(CHAN_TL_CAP + 1),
176 hps_hist: VecDeque::with_capacity(HPS_CAP + 1),
177 }
178 }
179
180 /// Append one RSSI sample for `mac` (APs and clients keyed by their
181 /// own MAC), capping the per-MAC history.
182 fn note_rssi(&mut self, mac: MacAddr, rssi_dbm: i8) {
183 let hist = self.rssi_hist.entry(mac).or_default();
184 if hist.len() == RSSI_CAP {
185 hist.pop_front();
186 }
187 hist.push_back(rssi_dbm);
188 }
189
190 /// Normalize an SSID for rogue comparison (trim + lowercase).
191 fn norm_ssid(ssid: &str) -> String {
192 ssid.trim().to_lowercase()
193 }
194
195 /// Crack target described by `capture_descs()[i]` (cloned — the cracker
196 /// worker takes ownership).
197 pub fn crack_target_at(&self, i: usize) -> Option<CrackTarget> {
198 self.capture_targets.get(i).cloned()
199 }
200
201 /// The same capture as a [`crate::store::StoredCapture`] (resume
202 /// session identity), `capture_descs()`-aligned like
203 /// [`AppState::crack_target_at`]. Sourced from the arrival-ordered
204 /// `capture_targets` so the index space never shifts under appends.
205 pub fn stored_capture_at(&self, i: usize) -> Option<crate::store::StoredCapture> {
206 match self.capture_targets.get(i)? {
207 CrackTarget::Handshake(h) => Some(crate::store::StoredCapture::Handshake(h.clone())),
208 CrackTarget::Pmkid(p) => Some(crate::store::StoredCapture::Pmkid(p.clone())),
209 }
210 }
211
212 pub fn push_log(&mut self, line: impl Into<String>) {
213 if self.log.len() == LOG_CAP {
214 self.log.pop_front();
215 }
216 self.log.push_back(line.into());
217 }
218
219 /// Reduce one service event into state. Returns `true` when the set of
220 /// crackable captures changed (callers rebuild dependent widgets).
221 ///
222 /// Does NOT sweep stale clients: at 10 Hz+ probe volumes a per-event
223 /// sweep allocates a full `clients` snapshot every call. The sweep
224 /// runs once per 100 ms drain tick instead — see
225 /// [`AppState::sweep_stale_clients`], invoked by the app drain loop
226 /// after the event batch is applied.
227 pub fn apply(&mut self, event: Event) -> bool {
228 self.reduce(event)
229 }
230
231 /// Backstop mirror of the scanner's 60 s client-expiry: rows learned
232 /// before a scanner restart (the restart wipes the scanner's internal
233 /// map, so no ClientLost can ever come for them) would linger as "up"
234 /// forever without this. Clock-offset between the service and UI
235 /// epochs (both `now_ms`, different process-local zero points) is a
236 /// few seconds at most — negligible against a 60 s threshold.
237 pub fn sweep_stale_clients(&mut self) {
238 const UI_CLIENT_EXPIRE_MS: u64 = 60_000;
239 let now = crate::common::now_ms();
240 let swept: Vec<MacAddr> = self
241 .clients
242 .iter()
243 .filter(|(_, c)| now.saturating_sub(c.last_seen_ms) > UI_CLIENT_EXPIRE_MS)
244 .map(|(m, _)| *m)
245 .collect();
246 for m in swept {
247 self.clients.remove(&m);
248 self.forget_ident(&m);
249 }
250 }
251
252 /// Drop a MAC's pairing record (client row gone).
253 fn forget_ident(&mut self, mac: &MacAddr) {
254 if let Some((gid, _)) = self.idents.remove(mac)
255 && let Some(set) = self.ident_groups.get_mut(&gid)
256 {
257 set.remove(mac);
258 if set.is_empty() {
259 self.ident_groups.remove(&gid);
260 }
261 }
262 }
263
264 fn reduce(&mut self, event: Event) -> bool {
265 match event {
266 Event::ApUpdated(ap) => {
267 self.note_rssi(ap.bssid, ap.rssi_dbm);
268 // Rogue detection: the same non-empty SSID advertised by a
269 // *different* BSSID with *different* security settings is
270 // the classic evil-twin smell (same security on multi-AP
271 // deployments is normal).
272 let norm = Self::norm_ssid(&ap.ssid);
273 if !norm.is_empty() {
274 let entry = self.seen_ssids.entry(norm.clone()).or_default();
275 if !self.rogue_ssids.contains(&norm) {
276 let conflict = entry
277 .iter()
278 .find(|(b, sec)| **b != ap.bssid && **sec != ap.security);
279 if let Some((known, sec1)) = conflict {
280 self.rogue_ssids.insert(norm.clone());
281 self.rogue_alert = Some(format!(
282 "possible rogue AP: \"{}\" on {} ({}) vs {} ({})",
283 norm,
284 known,
285 sec1.label(),
286 ap.bssid,
287 ap.security.label()
288 ));
289 }
290 }
291 entry.insert(ap.bssid, ap.security);
292 }
293 self.aps.insert(ap.bssid, ap);
294 false
295 }
296 Event::ApLost(bssid) => {
297 self.aps.remove(&bssid);
298 false
299 }
300 Event::ClientUpdated(mut client) => {
301 self.note_rssi(client.mac, client.rssi_dbm);
302 // Overlay the known pairing (the wire fields may lag or be
303 // absent for clients learned before this process knew the
304 // group).
305 if let Some(&(gid, conf)) = self.idents.get(&client.mac) {
306 client.ident_group = Some(gid);
307 client.ident_conf = Some(conf);
308 }
309 self.clients.insert(client.mac, client);
310 false
311 }
312 Event::ClientLost(mac) => {
313 self.clients.remove(&mac);
314 self.forget_ident(&mac);
315 false
316 }
317 Event::ClientIdent {
318 mac,
319 group,
320 confidence,
321 } => {
322 let rotated = self
323 .ident_groups
324 .get(&group)
325 .is_some_and(|ms| ms.iter().any(|m| *m != mac));
326 self.idents.insert(mac, (group, confidence));
327 self.ident_groups.entry(group).or_default().insert(mac);
328 // Message names the whole rotation set — the actionable fact
329 // is "these N MACs are one radio".
330 let n = self.ident_groups.get(&group).map_or(1, |ms| ms.len());
331 let msg = format!(
332 "device paired: {mac} → group #{group} ({n} MAC{}) [{}]",
333 if n == 1 { "" } else { "s" },
334 confidence.label()
335 );
336 self.push_log(msg.clone());
337 if rotated {
338 self.ident_alert = Some(msg);
339 }
340 // Live row gets the badge immediately.
341 if let Some(c) = self.clients.get_mut(&mac) {
342 c.ident_group = Some(group);
343 c.ident_conf = Some(confidence);
344 }
345 false
346 }
347 Event::HandshakeProgress { ap, client, have } => {
348 self.push_log(format!(
349 "4-way {ap} → {client}: {}/4 messages",
350 have.count_ones()
351 ));
352 false
353 }
354 Event::HandshakeComplete(cap) => {
355 self.push_log(format!(
356 "handshake captured: {} ({} ⇄ {})",
357 cap.essid, cap.ap, cap.client
358 ));
359 self.capture_targets
360 .push(CrackTarget::Handshake(cap.as_ref().clone()));
361 self.handshakes.push(*cap);
362 true
363 }
364 Event::HandshakePartial(cap) => {
365 // Same material re-delivered (e.g. tracker drain after the
366 // capture session already reported it) must not duplicate
367 // the picker entry.
368 if self
369 .partials
370 .iter()
371 .any(|p| p.ap == cap.ap && p.client == cap.client && p.mic() == cap.mic())
372 {
373 return false;
374 }
375 self.push_log(format!(
376 "partial handshake (M2+M3) for {}: hashcat-exportable",
377 cap.essid
378 ));
379 self.capture_targets
380 .push(CrackTarget::Handshake(cap.as_ref().clone()));
381 self.partials.push(*cap);
382 true
383 }
384 Event::PmkidCaptured(cap) => {
385 self.push_log(format!("PMKID captured: {} ({})", cap.essid, cap.ap));
386 self.capture_targets.push(CrackTarget::Pmkid(cap.clone()));
387 self.pmkids.push(cap);
388 true
389 }
390 Event::DeauthSent { ap, target, count } => {
391 self.push_log(format!("deauth: {count} frames → {target} (AP {ap})"));
392 false
393 }
394 Event::CrackProgress { done, hps, total } => {
395 if self.cracker.running {
396 self.cracker.tried = done;
397 self.cracker.hps = hps;
398 self.cracker.total = total;
399 if self.hps_hist.len() == HPS_CAP {
400 self.hps_hist.pop_front();
401 }
402 self.hps_hist.push_back(hps);
403 }
404 false
405 }
406 Event::CrackFound { password } => {
407 self.push_log(format!("PASSWORD FOUND: {password}"));
408 self.cracker.found = Some(password);
409 false
410 }
411 Event::CrackStopped { found } => {
412 self.push_log(format!(
413 "cracker: run ended ({})",
414 if found {
415 "password recovered"
416 } else {
417 "stopped/exhausted"
418 }
419 ));
420 self.cracker.running = false;
421 true // force dependent-widget refresh so the cracker page updates promptly
422 }
423 Event::CrackError { reason } => {
424 // Backend failure (GPU device lost, dispatch timeout,
425 // worker panic) — NOT exhaustion, NOT user stop. Log the
426 // reason (the cracker page's recent-activity block is a
427 // filtered view over this log, so the line mirrors there
428 // automatically) and reset the cracker to idle like
429 // CrackStopped, but do NOT touch the saved resume session:
430 // the failure is recoverable and the run may be resumed.
431 self.push_log(format!("crack FAILED (backend): {reason}"));
432 self.cracker.running = false;
433 true // force dependent-widget refresh so the cracker page updates promptly
434 }
435 Event::RainbowProgress { done, hps, total } => {
436 if self.cracker.rainbow_building {
437 self.cracker.rainbow_done = done;
438 self.cracker.rainbow_hps = hps;
439 self.cracker.rainbow_total = total;
440 }
441 false
442 }
443 Event::RainbowBuilt { path, entries } => {
444 self.push_log(format!("rainbow: table finished: {path} ({entries} PMKs)"));
445 self.cracker.rainbow_building = false;
446 false
447 }
448 Event::Log(line) => {
449 self.push_log(line);
450 false
451 }
452 Event::Error(line) => {
453 self.push_log(format!("ERROR: {line}"));
454 false
455 }
456 Event::ChannelStats(stats) => {
457 if self.chan_timeline.len() == CHAN_TL_CAP {
458 self.chan_timeline.pop_front();
459 }
460 self.chan_timeline.push_back(stats);
461 false
462 }
463 Event::ProbeObserved(probe) => {
464 self.note_rssi(probe.client, probe.rssi_dbm);
465 if self.probes.len() == PROBE_CAP {
466 self.probes.pop_front();
467 }
468 self.probes.push_back(probe);
469 false
470 }
471 Event::BenchmarkDone { gpu_hps, cpu_hps } => {
472 self.bench_gpu = gpu_hps;
473 self.bench_cpu = Some(cpu_hps);
474 self.push_log(format!(
475 "benchmark: gpu {} H/s, cpu {} H/s",
476 gpu_hps
477 .map(|h| h.to_string())
478 .unwrap_or_else(|| "none".to_string()),
479 cpu_hps
480 ));
481 false
482 }
483 Event::DeauthAlert {
484 source,
485 target,
486 count,
487 } => {
488 let msg = format!("DEAUTH STORM: {source} → {target} x{count}");
489 self.push_log(msg.clone());
490 self.deauth_alert = Some(msg);
491 false
492 }
493 Event::CaptureImported(cap) => {
494 match cap {
495 crate::common::ImportedCapture::Handshake(h) => {
496 self.push_log(format!(
497 "import{} handshake: {} ({} ⇄ {})",
498 if h.partial { "ed [partial]" } else { "ed" },
499 h.essid,
500 h.ap,
501 h.client
502 ));
503 self.capture_targets
504 .push(CrackTarget::Handshake(h.as_ref().clone()));
505 // Imported partials join the partial provenance
506 // list (dedup, [partial] marker, hc22000-export
507 // path) just like service-emitted partials.
508 if h.partial {
509 if !self
510 .partials
511 .iter()
512 .any(|p| p.ap == h.ap && p.client == h.client && p.mic() == h.mic())
513 {
514 self.partials.push(*h);
515 }
516 } else {
517 self.handshakes.push(*h);
518 }
519 }
520 crate::common::ImportedCapture::Pmkid(p) => {
521 self.push_log(format!("imported PMKID: {} ({})", p.essid, p.ap));
522 self.capture_targets.push(CrackTarget::Pmkid(p.clone()));
523 self.pmkids.push(p);
524 }
525 }
526 true
527 }
528 }
529 }
530
531 /// Stable, unique descriptions of every crackable capture — the
532 /// cracker's target dropdown is fed with these (index prefix keeps
533 /// duplicates apart). Arrival-ordered ([`self.capture_targets`]), so
534 /// appending new captures can never renumber an existing entry — the
535 /// selection structs key on the index, not the string. Partial M2+M3
536 /// captures carry a `[partial]` marker so their provenance is visible
537 /// at a glance.
538 pub fn capture_descs(&self) -> Vec<String> {
539 self.capture_targets
540 .iter()
541 .enumerate()
542 .map(|(i, t)| match t {
543 CrackTarget::Handshake(hs) => format!(
544 "#{:02} HS {}{} {} ⇄ {} kv{}",
545 i + 1,
546 if hs.partial { "[partial] " } else { "" },
547 hs.essid,
548 hs.ap,
549 hs.client,
550 hs.key_ver
551 ),
552 CrackTarget::Pmkid(pm) => format!("#{:02} PMKID {} {}", i + 1, pm.essid, pm.ap),
553 })
554 .collect()
555 }
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561
562 fn stat(ch: u8, frames: u64) -> ChannelStat {
563 ChannelStat {
564 channel: ch,
565 frames,
566 beacons: 0,
567 }
568 }
569
570 fn mac(byte: u8) -> MacAddr {
571 MacAddr([byte; 6])
572 }
573
574 fn partial_cap(seed: u8, essid: &str) -> HandshakeCapture {
575 HandshakeCapture::new_partial(
576 mac(0xaa),
577 mac(0xbb),
578 essid.to_string(),
579 [seed; 32],
580 [seed.wrapping_add(1); 32],
581 [seed; 16],
582 vec![1, 3, 0, 95],
583 2,
584 )
585 }
586
587 #[test]
588 fn handshake_partial_appends_marked_and_dedups() {
589 let mut s = AppState::new("wlan0");
590 let cap = partial_cap(7, "partialnet");
591 assert!(s.apply(Event::HandshakePartial(Box::new(cap.clone()))));
592 // Same (AP, client) + MIC re-delivered: no duplicate picker entry.
593 assert!(!s.apply(Event::HandshakePartial(Box::new(cap))));
594 assert_eq!(s.partials.len(), 1);
595 assert!(s.partials[0].partial);
596 let descs = s.capture_descs();
597 assert_eq!(descs.len(), 1);
598 assert!(descs[0].contains("[partial]"), "desc: {}", descs[0]);
599 // Cracker-side index space includes it (same run path as HS/PMKID).
600 assert!(matches!(
601 s.stored_capture_at(0),
602 Some(crate::store::StoredCapture::Handshake(_))
603 ));
604 assert_eq!(
605 s.log.back().map(String::as_str),
606 Some("partial handshake (M2+M3) for partialnet: hashcat-exportable")
607 );
608 }
609
610 #[test]
611 fn crack_error_resets_running_and_logs_reason() {
612 let mut s = AppState::new("wlan0");
613 s.cracker.running = true;
614 assert!(s.apply(Event::CrackError {
615 reason: "GPU device lost".to_string()
616 }));
617 assert!(!s.cracker.running);
618 assert_eq!(
619 s.log.back().map(String::as_str),
620 Some("crack FAILED (backend): GPU device lost")
621 );
622 }
623
624 #[test]
625 fn capture_index_space_is_append_stable() {
626 let mut s = AppState::new("wlan0");
627 let h1 = HandshakeCapture::new(
628 mac(1),
629 mac(2),
630 "alpha".to_string(),
631 [0; 32],
632 [1; 32],
633 [2; 16],
634 vec![0],
635 2,
636 );
637 s.apply(Event::HandshakeComplete(Box::new(h1)));
638 s.apply(Event::PmkidCaptured(PmkidCapture {
639 ap: mac(3),
640 client: mac(4),
641 essid: "beta".to_string(),
642 pmkid: [5; 16],
643 }));
644 let before = s.capture_descs();
645 assert_eq!(before.len(), 2);
646 assert!(before[1].contains("PMKID"));
647 // A later handshake must NOT renumber the PMKID entry: with an
648 // index-keyed target selection, a shift would silently crack the
649 // wrong capture.
650 let h2 = HandshakeCapture::new(
651 mac(5),
652 mac(6),
653 "gamma".to_string(),
654 [1; 32],
655 [2; 32],
656 [3; 16],
657 vec![0],
658 2,
659 );
660 s.apply(Event::HandshakeComplete(Box::new(h2)));
661 let after = s.capture_descs();
662 assert_eq!(after.len(), 3);
663 assert_eq!(&after[..before.len()], &before[..]);
664 assert!(matches!(
665 s.stored_capture_at(1),
666 Some(crate::store::StoredCapture::Pmkid(_))
667 ));
668 }
669
670 #[test]
671 fn channel_timeline_keeps_snapshots_and_caps() {
672 let mut s = AppState::new("wlan0");
673 for i in 0..(CHAN_TL_CAP + 5) {
674 s.apply(Event::ChannelStats(vec![stat(1, i as u64 + 1)]));
675 }
676 assert_eq!(s.chan_timeline.len(), CHAN_TL_CAP);
677 // Oldest dropped: the first surviving snapshot is frames=6.
678 assert_eq!(s.chan_timeline.front().unwrap()[0].frames, 6);
679 // Newest snapshot is the tail of the timeline.
680 assert_eq!(
681 s.chan_timeline.back().unwrap()[0].frames,
682 (CHAN_TL_CAP + 5) as u64
683 );
684 }
685
686 #[test]
687 fn hps_history_advances_only_while_running() {
688 let mut s = AppState::new("wlan0");
689 s.apply(Event::CrackProgress {
690 done: 10,
691 hps: 100.0,
692 total: None,
693 });
694 assert!(s.hps_hist.is_empty(), "stopped run must not feed the curve");
695 s.cracker.running = true;
696 s.apply(Event::CrackProgress {
697 done: 20,
698 hps: 200.0,
699 total: Some(50),
700 });
701 s.apply(Event::CrackProgress {
702 done: 30,
703 hps: 300.0,
704 total: Some(50),
705 });
706 assert_eq!(
707 s.hps_hist.iter().copied().collect::<Vec<_>>(),
708 vec![200.0, 300.0]
709 );
710 assert_eq!(s.cracker.tried, 30);
711 assert_eq!(s.cracker.total, Some(50));
712 }
713}