forge
Explore
Log in

Don't you dare go Hollow

Device columns + labels, persistent capture store, mode-rich cracker, desktop notify

Browse files at this commit

1e4e538cbc9275ba46f00d505af76316e69f9444Ahmet Kaan GümüşParent: d8f9a5d
  • feat
    • device columns + labels, persistent capture store, mode-rich cracker, desktop notify
Show full message
✨ feat(ui): device columns + labels, persistent capture store, mode-rich cracker, desktop notify
src/store.rsadded+456 -0
@@ -0,0 +1,456 @@
1+//! Persistent UI-side data under `~/wifilab`:
2+//! - `labels.json` — user-assigned names by MAC (APs and clients share one
3+//! namespace; a MAC is unique).
4+//! - `captures.jsonl` — every complete handshake / PMKID capture, one JSON
5+//! line each, appended as they arrive and reloaded at startup (the
6+//! cracker keeps working across restarts without re-attacking).
7+//!
8+//! UI-only data — the privileged service never touches it.
9+
10+use std::collections::BTreeMap;
11+use std::path::{Path, PathBuf};
12+
13+use anyhow::{Context, Result};
14+use serde::{Deserialize, Serialize};
15+
16+use crate::common::{HandshakeCapture, MacAddr, PmkidCapture};
17+
18+/// `~/wifilab` — falls back to `./wifilab` when HOME is unset.
19+pub fn data_dir() -> PathBuf {
20+ std::env::var_os("HOME")
21+ .map(PathBuf::from)
22+ .unwrap_or_else(|| PathBuf::from("."))
23+ .join("wifilab")
24+}
25+
26+fn labels_path() -> PathBuf {
27+ data_dir().join("labels.json")
28+}
29+
30+fn captures_path() -> PathBuf {
31+ data_dir().join("captures.jsonl")
32+}
33+
34+fn session_path() -> PathBuf {
35+ data_dir().join("crack-session.json")
36+}
37+
38+/// One persisted capture (tagged JSON line in `captures.jsonl`).
39+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
40+#[serde(tag = "kind", rename_all = "lowercase")]
41+pub enum StoredCapture {
42+ Handshake(HandshakeCapture),
43+ Pmkid(PmkidCapture),
44+}
45+
46+impl StoredCapture {
47+ /// Display identity used for dedup on load.
48+ fn id(&self) -> String {
49+ match self {
50+ StoredCapture::Handshake(h) => format!("hs:{}:{}", h.ap, h.client),
51+ StoredCapture::Pmkid(p) => format!("pmkid:{}", p.ap),
52+ }
53+ }
54+}
55+
56+fn load_labels_from(path: &Path) -> Result<BTreeMap<MacAddr, String>> {
57+ let raw = match std::fs::read_to_string(path) {
58+ Ok(s) => s,
59+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
60+ return Ok(BTreeMap::new());
61+ }
62+ Err(e) => return Err(e).context("reading labels.json"),
63+ };
64+ let by_str: BTreeMap<String, String> =
65+ serde_json::from_str(&raw).context("parsing labels.json")?;
66+ let mut out = BTreeMap::new();
67+ for (mac, label) in by_str {
68+ let mac: MacAddr = mac.parse().with_context(|| format!("bad MAC key {mac:?}"))?;
69+ if !label.is_empty() {
70+ out.insert(mac, label);
71+ }
72+ }
73+ Ok(out)
74+}
75+
76+/// Load all labels; a missing file is an empty store, a corrupt one is an
77+/// error (callers log it and start empty rather than clobbering).
78+pub fn load() -> Result<BTreeMap<MacAddr, String>> {
79+ load_labels_from(&labels_path())
80+}
81+
82+fn save_labels_to(path: &Path, labels: &BTreeMap<MacAddr, String>) -> Result<()> {
83+ let dir = path.parent().expect("labels path has a parent");
84+ std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
85+ let by_str: BTreeMap<String, &String> =
86+ labels.iter().map(|(mac, l)| (mac.to_string(), l)).collect();
87+ let body = serde_json::to_string_pretty(&by_str).expect("string map serialization");
88+ let tmp = path.with_extension("json.tmp");
89+ std::fs::write(&tmp, body).with_context(|| format!("writing {}", tmp.display()))?;
90+ std::fs::rename(&tmp, path)
91+ .with_context(|| format!("renaming {} → {}", tmp.display(), path.display()))
92+}
93+
94+/// Persist the whole label map (labels are few; rewriting is cheap and
95+/// atomic enough via write-to-tmp + rename).
96+pub fn save(labels: &BTreeMap<MacAddr, String>) -> Result<()> {
97+ save_labels_to(&labels_path(), labels)
98+}
99+
100+fn append_capture_to(path: &Path, cap: &StoredCapture) -> Result<()> {
101+ let dir = path.parent().expect("captures path has a parent");
102+ std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
103+ use std::io::Write as _;
104+ let mut f = std::fs::OpenOptions::new()
105+ .create(true)
106+ .append(true)
107+ .open(path)
108+ .with_context(|| format!("opening {}", path.display()))?;
109+ let line = serde_json::to_string(cap).context("serializing capture")?;
110+ writeln!(f, "{line}").with_context(|| format!("appending to {}", path.display()))
111+}
112+
113+/// Append one capture to `captures.jsonl`. Called the moment a capture
114+/// arrives — the file survives a crash right after.
115+pub fn append_capture(cap: &StoredCapture) -> Result<()> {
116+ append_capture_to(&captures_path(), cap)
117+}
118+
119+fn load_captures_from(path: &Path) -> Result<Vec<StoredCapture>> {
120+ let raw = match std::fs::read_to_string(path) {
121+ Ok(s) => s,
122+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
123+ Err(e) => return Err(e).context("reading captures.jsonl"),
124+ };
125+ let mut seen = std::collections::BTreeSet::new();
126+ let mut out = Vec::new();
127+ for (n, line) in raw.lines().enumerate() {
128+ let line = line.trim();
129+ if line.is_empty() {
130+ continue;
131+ }
132+ match serde_json::from_str::<StoredCapture>(line) {
133+ Ok(cap) => {
134+ if seen.insert(cap.id()) {
135+ out.push(cap);
136+ }
137+ }
138+ // One corrupt line must not kill the whole archive.
139+ Err(e) => eprintln!("wifilab: skipping corrupt captures.jsonl line {}: {e}", n + 1),
140+ }
141+ }
142+ Ok(out)
143+}
144+
145+/// Load every stored capture (deduped by AP/client identity). A corrupt
146+/// FILE is an error; individual corrupt lines are skipped.
147+pub fn load_captures() -> Result<Vec<StoredCapture>> {
148+ load_captures_from(&captures_path())
149+}
150+
151+// ---------------------------------------------------------------------------
152+// Crack session (resume): the interrupted run's position, so a later start
153+// — in this or a future session — continues instead of restarting.
154+// ---------------------------------------------------------------------------
155+
156+/// A stopped (not finished) crack run: which capture, which attack, how
157+/// far it had gotten. Written throttle-throttled on progress and once on
158+/// stop; deleted when the run finds the password or exhausts the space.
159+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
160+pub struct CrackSession {
161+ pub capture: StoredCapture,
162+ pub attack: crate::attack::Attack,
163+ /// Candidates checked so far (resume skips/seeks past these).
164+ pub done: u64,
165+ /// Worst-case total of the run (see the ETA plumbing), when countable.
166+ pub total: Option<u64>,
167+}
168+
169+fn save_session_to(path: &Path, session: &CrackSession) -> Result<()> {
170+ if let Some(dir) = path.parent() {
171+ std::fs::create_dir_all(dir).context("creating ~/wifilab")?;
172+ }
173+ let json = serde_json::to_string_pretty(session).context("serializing crack session")?;
174+ let tmp = path.with_extension("json.tmp");
175+ std::fs::write(&tmp, json).with_context(|| format!("writing {}", tmp.display()))?;
176+ std::fs::rename(&tmp, path).with_context(|| format!("renaming {}", path.display()))?;
177+ Ok(())
178+}
179+
180+/// Persist the session (atomic-ish: write tmp + rename, like labels).
181+pub fn save_session(session: &CrackSession) -> Result<()> {
182+ save_session_to(&session_path(), session)
183+}
184+
185+fn load_session_from(path: &Path) -> Result<Option<CrackSession>> {
186+ match std::fs::read_to_string(path) {
187+ Ok(s) => Ok(Some(
188+ serde_json::from_str(&s).context("parsing crack-session.json")?,
189+ )),
190+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
191+ Err(e) => Err(e).context("reading crack-session.json"),
192+ }
193+}
194+
195+/// Load the saved session; `None` when no run was interrupted. A corrupt
196+/// file is an error (callers log it and start fresh rather than resuming
197+/// garbage).
198+pub fn load_session() -> Result<Option<CrackSession>> {
199+ load_session_from(&session_path())
200+}
201+
202+/// Drop the saved session (run found/exhausted, or user discarded).
203+/// Missing file is fine.
204+pub fn clear_session() -> Result<()> {
205+ match std::fs::remove_file(session_path()) {
206+ Ok(()) => Ok(()),
207+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
208+ Err(e) => Err(e).context("removing crack-session.json"),
209+ }
210+}
211+
212+// ---------------------------------------------------------------------------
213+// Per-SSID PMK cache: `~/wifilab/cache/<ssid-hex>.pmk` in rainbow text
214+// format — PMKs computed on earlier CPU runs are reusable for ANY capture
215+// of the same SSID without re-running PBKDF2.
216+// ---------------------------------------------------------------------------
217+
218+/// `~/wifilab/cache` — created on use by the cache readers/writers.
219+pub fn cache_dir() -> PathBuf {
220+ data_dir().join("cache")
221+}
222+
223+/// Cache table path for one SSID: lowercase hex of the raw SSID bytes +
224+/// `.pmk` (filesystem-safe for arbitrary SSID encodings).
225+pub fn cache_file(ssid: &str) -> PathBuf {
226+ let hex: String = ssid.bytes().map(|b| format!("{b:02x}")).collect();
227+ cache_dir().join(format!("{hex}.pmk"))
228+}
229+
230+// ---------------------------------------------------------------------------
231+// Crack profiles + recent wordlists (`~/wifilab/profiles.json`): user-saved
232+// attack setups for one-click reuse on the cracker page.
233+// ---------------------------------------------------------------------------
234+
235+/// One saved attack setup (mode/wl/rules as the cracker page fields).
236+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
237+pub struct CrackProfile {
238+ pub name: String,
239+ pub mode: String,
240+ pub wordlist: String,
241+ pub rules: Option<String>,
242+}
243+
244+/// The whole profiles file: saved presets + MRU wordlist list (cap 5).
245+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
246+pub struct Profiles {
247+ pub profiles: Vec<CrackProfile>,
248+ pub recent_wordlists: Vec<String>,
249+}
250+
251+fn profiles_path() -> PathBuf {
252+ data_dir().join("profiles.json")
253+}
254+
255+fn load_profiles_from(path: &Path) -> Result<Profiles> {
256+ match std::fs::read_to_string(path) {
257+ Ok(s) => match serde_json::from_str::<Profiles>(&s) {
258+ Ok(p) => Ok(p),
259+ Err(e) => {
260+ eprintln!("wifilab: profiles.json unreadable ({e}), starting fresh");
261+ Ok(Profiles::default())
262+ }
263+ },
264+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Profiles::default()),
265+ Err(e) => Err(e).context("reading profiles.json"),
266+ }
267+}
268+
269+/// Load profiles; missing or unparseable file starts empty (never clobbers).
270+pub fn load_profiles() -> Result<Profiles> {
271+ load_profiles_from(&profiles_path())
272+}
273+
274+fn save_profiles_to(path: &Path, p: &Profiles) -> Result<()> {
275+ let dir = path.parent().expect("profiles path has a parent");
276+ std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
277+ let body = serde_json::to_string_pretty(p).context("serializing profiles")?;
278+ let tmp = path.with_extension("json.tmp");
279+ std::fs::write(&tmp, body).with_context(|| format!("writing {}", tmp.display()))?;
280+ std::fs::rename(&tmp, path)
281+ .with_context(|| format!("renaming {} → {}", tmp.display(), path.display()))
282+}
283+
284+/// Persist profiles (atomic-ish: write tmp + rename, like labels).
285+pub fn save_profiles(p: &Profiles) -> Result<()> {
286+ save_profiles_to(&profiles_path(), p)
287+}
288+
289+/// MRU-insert a wordlist path at the front of `recent_wordlists`, deduped,
290+/// capped at 5.
291+pub fn remember_wordlist(p: &mut Profiles, path: &str) {
292+ p.recent_wordlists.retain(|w| w != path);
293+ p.recent_wordlists.insert(0, path.to_string());
294+ p.recent_wordlists.truncate(5);
295+}
296+
297+#[cfg(test)]
298+mod tests {
299+ use super::*;
300+
301+ fn tmp(name: &str) -> PathBuf {
302+ std::env::temp_dir().join(format!("wifilab-store-test-{}-{name}", std::process::id()))
303+ }
304+
305+ #[test]
306+ fn labels_roundtrip() {
307+ let dir = tmp("labels");
308+ let path = dir.join("labels.json");
309+ let mac: MacAddr = "aa:bb:cc:dd:ee:ff".parse().unwrap();
310+ let mut labels = BTreeMap::new();
311+ labels.insert(mac, "living room".to_string());
312+ save_labels_to(&path, &labels).unwrap();
313+ let back = load_labels_from(&path).unwrap();
314+ assert_eq!(back.get(&mac).map(String::as_str), Some("living room"));
315+ let _ = std::fs::remove_dir_all(&dir);
316+ }
317+
318+ #[test]
319+ fn labels_missing_file_is_empty() {
320+ let back = load_labels_from(&tmp("nope").join("labels.json")).unwrap();
321+ assert!(back.is_empty());
322+ }
323+
324+ #[test]
325+ fn session_roundtrip_and_missing() {
326+ let dir = tmp("session");
327+ let path = dir.join("crack-session.json");
328+ assert!(load_session_from(&path).unwrap().is_none());
329+ let session = CrackSession {
330+ capture: StoredCapture::Pmkid(PmkidCapture {
331+ ap: "aa:bb:cc:dd:ee:ff".parse().unwrap(),
332+ client: "11:22:33:44:55:66".parse().unwrap(),
333+ essid: "parafin".into(),
334+ pmkid: [7u8; 16],
335+ }),
336+ attack: crate::attack::Attack::Bruteforce {
337+ charset: b"01".to_vec(),
338+ min: 8,
339+ max: 10,
340+ freq_order: true,
341+ },
342+ done: 12_345,
343+ total: Some(1_114_100),
344+ };
345+ save_session_to(&path, &session).unwrap();
346+ let back = load_session_from(&path).unwrap().expect("saved");
347+ assert_eq!(back, session);
348+ let _ = std::fs::remove_dir_all(&dir);
349+ }
350+
351+ #[test]
352+ fn captures_append_and_load_dedups() {
353+ let dir = tmp("caps");
354+ let path = dir.join("captures.jsonl");
355+ let pm = PmkidCapture {
356+ ap: "aa:bb:cc:dd:ee:ff".parse().unwrap(),
357+ client: "11:22:33:44:55:66".parse().unwrap(),
358+ essid: "parafin".into(),
359+ pmkid: [7u8; 16],
360+ };
361+ let hs = HandshakeCapture::new(
362+ "aa:bb:cc:dd:ee:ff".parse().unwrap(),
363+ "11:22:33:44:55:66".parse().unwrap(),
364+ "parafin".into(),
365+ [1u8; 32],
366+ [2u8; 32],
367+ [3u8; 16],
368+ vec![9u8; 8],
369+ 2,
370+ );
371+ let cap_pm = StoredCapture::Pmkid(pm.clone());
372+ let cap_hs = StoredCapture::Handshake(hs.clone());
373+ append_capture_to(&path, &cap_pm).unwrap();
374+ append_capture_to(&path, &cap_pm).unwrap(); // duplicate line on disk
375+ append_capture_to(&path, &cap_hs).unwrap();
376+ // One corrupt line must not kill the rest.
377+ std::fs::write(
378+ &path,
379+ format!("{}{{not json}}\n", std::fs::read_to_string(&path).unwrap()),
380+ )
381+ .unwrap();
382+ let back = load_captures_from(&path).unwrap();
383+ assert_eq!(back, vec![cap_pm, cap_hs]);
384+ let _ = std::fs::remove_dir_all(&dir);
385+ }
386+
387+ #[test]
388+ fn captures_missing_file_is_empty() {
389+ let back = load_captures_from(&tmp("nope").join("captures.jsonl")).unwrap();
390+ assert!(back.is_empty());
391+ }
392+
393+ #[test]
394+ fn profiles_roundtrip_and_missing() {
395+ let dir = tmp("profiles");
396+ let path = dir.join("profiles.json");
397+ // Missing file = empty store.
398+ assert_eq!(load_profiles_from(&path).unwrap().profiles.len(), 0);
399+ let mut p = Profiles {
400+ profiles: vec![
401+ CrackProfile {
402+ name: "wl:rockyou".into(),
403+ mode: "wordlist".into(),
404+ wordlist: "/usr/share/wordlists/rockyou.txt".into(),
405+ rules: None,
406+ },
407+ CrackProfile {
408+ name: "rules:corp".into(),
409+ mode: "rules".into(),
410+ wordlist: "/home/x/wl.txt".into(),
411+ rules: Some("/home/x/best64.rule".into()),
412+ },
413+ ],
414+ recent_wordlists: vec!["/a.txt".into(), "/b.txt".into()],
415+ };
416+ p.recent_wordlists.insert(0, "/c.txt".into());
417+ save_profiles_to(&path, &p).unwrap();
418+ let back = load_profiles_from(&path).unwrap();
419+ assert_eq!(back.profiles.len(), 2);
420+ assert_eq!(back.profiles[0].name, "wl:rockyou");
421+ assert_eq!(back.profiles[1].rules.as_deref(), Some("/home/x/best64.rule"));
422+ assert_eq!(back.recent_wordlists, p.recent_wordlists);
423+ // Unparseable file = empty store, no error (never clobbered).
424+ std::fs::write(&path, "{{not json").unwrap();
425+ let back = load_profiles_from(&path).unwrap();
426+ assert!(back.profiles.is_empty() && back.recent_wordlists.is_empty());
427+ let _ = std::fs::remove_dir_all(&dir);
428+ }
429+
430+ #[test]
431+ fn remember_wordlist_front_insert_dedup_cap5() {
432+ let mut p = Profiles::default();
433+ for w in ["/a", "/b", "/c", "/d", "/e", "/a"] {
434+ remember_wordlist(&mut p, w);
435+ }
436+ // "/a" re-remembered: moves to front, no duplicate.
437+ assert_eq!(p.recent_wordlists, vec!["/a", "/e", "/d", "/c", "/b"]);
438+ // Sixth distinct path evicts the oldest.
439+ remember_wordlist(&mut p, "/f");
440+ assert_eq!(p.recent_wordlists, vec!["/f", "/a", "/e", "/d", "/c"]);
441+ }
442+
443+ #[test]
444+ fn cache_file_hex_naming() {
445+ let p = cache_file("parafin");
446+ assert_eq!(
447+ p.file_name().unwrap().to_str().unwrap(),
448+ "7061726166696e.pmk"
449+ );
450+ // Hex is lowercase and 2 chars per byte; non-ASCII bytes safe.
451+ let p2 = cache_file("aé");
452+ assert_eq!(p2.file_name().unwrap().to_str().unwrap(), "61c3a9.pmk");
453+ assert_eq!(p.parent().unwrap(), cache_dir());
454+ }
455+}
456+
src/ui/app.rsmodified+436 -37
@@ -3,7 +3,9 @@
3 //! task that polls the service event channel.3 //! task that polls the service event channel.
4 4
5 use std::collections::BTreeMap;5 use std::collections::BTreeMap;
6-use std::time::Duration;6+use std::sync::Arc;
7+use std::sync::atomic::{AtomicBool, Ordering};
8+use std::time::{Duration, Instant};
7 9
8 use crossbeam_channel::{Receiver, Sender};10 use crossbeam_channel::{Receiver, Sender};
9 use gpui::{11 use gpui::{
@@ -19,8 +21,9 @@ use gpuikit::elements::toast::ToastExt;
19 use gpuikit::input::InputState;21 use gpuikit::input::InputState;
20 use gpuikit::layout::{h_stack, v_stack};22 use gpuikit::layout::{h_stack, v_stack};
21 use gpuikit::theme::{ActiveTheme, Themeable};23 use gpuikit::theme::{ActiveTheme, Themeable};
24+use gpuikit::traits::disableable::Disableable;
22 25
23-use crate::common::{Cmd, Event, MacAddr};26+use crate::common::{AccessPoint, Cmd, Event, MacAddr};
24 use crate::service::ServiceClient;27 use crate::service::ServiceClient;
25 use crate::ui::{attacks, cracker, log as log_view, networks, state::AppState};28 use crate::ui::{attacks, cracker, log as log_view, networks, state::AppState};
26 29
@@ -47,6 +50,15 @@ impl Page {
47 Page::Log => "Log",50 Page::Log => "Log",
48 }51 }
49 }52 }
53+
54+ /// Startup page override (`WIFILAB_PAGE=attacks`) — dev/visual-verification
55+ /// hook; unknown values fall through to Networks.
56+ fn from_name(name: &str) -> Option<Page> {
57+ Page::ALL
58+ .iter()
59+ .copied()
60+ .find(|p| p.label().eq_ignore_ascii_case(name))
61+ }
50 }62 }
51 63
52 pub struct AppRoot {64 pub struct AppRoot {
@@ -56,18 +68,26 @@ pub struct AppRoot {
56 /// UI-triggered actions are injected into the same pipeline.68 /// UI-triggered actions are injected into the same pipeline.
57 pub tx: Sender<Event>,69 pub tx: Sender<Event>,
58 pub page: Page,70 pub page: Page,
59- /// Privilege indicator; real value from [`crate::iface::is_root`].71+ /// UI-process privilege ([`crate::iface::is_root`]); the header badge
60- /// Informational only — the UI never needs root itself; the service72+ /// combines this with `service` presence to show the SERVICE's
61- /// elevates via polkit when it spawns.73+ /// privilege state — any running service is root (direct spawn or
74+ /// pkexec).
62 pub is_root: bool,75 pub is_root: bool,
63- /// Privileged radio service client (owns the child process + the76+ /// Privileged radio service client (owns the child process). `None`
64- /// UI-side cracker stop flag). `None` in mock mode or before the77+ /// in mock mode or before the first "Start capture". Kept across
65- /// first "Start capture". Kept across stop/start cycles.78+ /// stop/start cycles. NOT involved in cracking — crack jobs are
79+ /// UI-process threads tracked via [`AppRoot::crack_stop`].
66 pub service: Option<ServiceClient>,80 pub service: Option<ServiceClient>,
67 /// Mock data mode (`--mock` / `WIFILAB_MOCK=1`): never touches devices.81 /// Mock data mode (`--mock` / `WIFILAB_MOCK=1`): never touches devices.
68 pub is_mock: bool,82 pub is_mock: bool,
69 /// Target BSSID picked on the Networks page (AP row or client row).83 /// Target BSSID picked on the Networks page (AP row or client row).
70 pub selected: Option<MacAddr>,84 pub selected: Option<MacAddr>,
85+ /// Last-known AP row for [`AppRoot::selected`], snapshotted at click
86+ /// time and refreshed whenever the live record updates. The Attacks
87+ /// page builds its target card from this even when the live row is
88+ /// momentarily absent (host-capture mode never re-scans: a target
89+ /// picked before the lock may have no AP row at all).
90+ pub selected_ap: Option<AccessPoint>,
71 /// Client station picked on the Networks page; deauth targets it91 /// Client station picked on the Networks page; deauth targets it
72 /// instead of the broadcast address when set (AP stays `selected`).92 /// instead of the broadcast address when set (AP stays `selected`).
73 pub selected_client: Option<MacAddr>,93 pub selected_client: Option<MacAddr>,
@@ -77,11 +97,24 @@ pub struct AppRoot {
77 /// "Spinner shown" flags for attack buttons awaiting results.97 /// "Spinner shown" flags for attack buttons awaiting results.
78 pub attacking_handshake: bool,98 pub attacking_handshake: bool,
79 pub attacking_pmkid: bool,99 pub attacking_pmkid: bool,
100+ /// Channels the scanner is parked on for attacks (restricted StartScan
101+ /// plan; several entries cover dual-band targets). `None` = full hop
102+ /// list. Blanket spectrum-wide hopping makes capture/PMKID/deauth
103+ /// mostly deaf and blind to one band.
104+ pub parked_channels: Option<Vec<u8>>,
80 /// Crack run in flight; cleared when CrackStopped arrives.105 /// Crack run in flight; cleared when CrackStopped arrives.
81 pub crack_inflight: bool,106 pub crack_inflight: bool,
82- /// Toast queued by the event loop (no Window there) — shown on the107+ /// Stop flag of the running crack job (UI-process thread, see
83- /// next render pass.108+ /// [`crate::attack`]); flipped by Stop and on window close.
84- pub pending_toast: Option<SharedString>,109+ pub crack_stop: Option<Arc<AtomicBool>>,
110+ /// Stop flag of the running rainbow-table build job.
111+ pub rainbow_stop: Option<Arc<AtomicBool>>,
112+ /// Throttle for resume-session writes (see [`AppRoot::maybe_save_crack_session`]).
113+ pub last_session_save: Instant,
114+ /// Toasts queued by the event loop (no Window there) — shown on the
115+ /// next render pass. Capped (oldest dropped) so a burst of alerts
116+ /// can't bury the window.
117+ pub pending_toast: std::collections::VecDeque<SharedString>,
85 /// NetworkManager seen active when capture started (fights channels).118 /// NetworkManager seen active when capture started (fights channels).
86 pub nm_active: bool,119 pub nm_active: bool,
87 /// Used to invalidate stale cracker simulation ticks after Stop/re-Start.120 /// Used to invalidate stale cracker simulation ticks after Stop/re-Start.
@@ -92,7 +125,49 @@ pub struct AppRoot {
92 pub iface_select: Entity<SelectState<String>>,125 pub iface_select: Entity<SelectState<String>>,
93 pub target_select: Entity<SelectState<String>>,126 pub target_select: Entity<SelectState<String>>,
94 pub wordlist_input: Entity<InputState>,127 pub wordlist_input: Entity<InputState>,
128+ /// Cracker attack-mode picker ([`crate::attack::Attack`]: wordlist /
129+ /// bruteforce / rainbow).
130+ pub attack_select: Entity<SelectState<String>>,
131+ /// Selected attack mode value ("wordlist" | "bruteforce" | "rainbow").
132+ pub attack_mode: String,
133+ /// Bruteforce preset chips ([`crate::attack::charset`]): unioned with
134+ /// the custom field into the effective charset.
135+ pub cs_lower: bool,
136+ pub cs_upper: bool,
137+ pub cs_digits: bool,
138+ pub cs_special: bool,
139+ /// Bruteforce mode inputs: charset and min/max word length.
140+ pub charset_input: Entity<InputState>,
141+ pub len_min_input: Entity<InputState>,
142+ pub len_max_input: Entity<InputState>,
143+ /// Rainbow mode: PMK table path; the build job writes it, the run
144+ /// reads it.
145+ pub rainbow_input: Entity<InputState>,
95 pub deauth_input: Entity<InputState>,146 pub deauth_input: Entity<InputState>,
147+ /// Networks-page label editor; the labels themselves live in
148+ /// `state.labels` ([`crate::store`]).
149+ pub label_input: Entity<InputState>,
150+ /// Log page body: read-only multiline input so log text is
151+ /// mouse-selectable / Ctrl-C-copyable (plain text widgets aren't).
152+ pub log_input: Entity<InputState>,
153+ /// Rules-attack mode: hashcat-style rule file path.
154+ pub rules_input: Entity<InputState>,
155+ /// Crack-time estimator candidate (how strong might the password be).
156+ pub strength_input: Entity<InputState>,
157+ /// Hybrid mode: appended-suffix length bounds.
158+ pub hyb_min_input: Entity<InputState>,
159+ pub hyb_max_input: Entity<InputState>,
160+ /// Bruteforce charset ordering: most-common characters first.
161+ pub freq_order: bool,
162+ /// A throughput benchmark run is in flight.
163+ pub bench_running: bool,
164+ /// A capture-file import is in flight.
165+ pub import_busy: bool,
166+ /// Target count behind the "Deauth all clients (N)" button label
167+ /// (0 = hidden); computed during attack-page render prep.
168+ pub deauth_all_targets: usize,
169+ /// Saved cracking presets + recent wordlists (~/wifilab/profiles.json).
170+ pub profiles: crate::store::Profiles,
96 }171 }
97 172
98 impl AppRoot {173 impl AppRoot {
@@ -141,21 +216,73 @@ impl AppRoot {
141 input.set_content("16", cx);216 input.set_content("16", cx);
142 });217 });
143 218
219+ let label_input = cx.new(InputState::new_singleline);
220+ let log_input = cx.new(|cx| InputState::new_multiline(cx).read_only(true));
221+
222+ let attack_select = cx.new(|_cx| {
223+ SelectState::new(
224+ select(
225+ "cracker-attack",
226+ "Attack",
227+ vec![
228+ ("wordlist".to_string(), "wordlist".to_string()),
229+ ("rules".to_string(), "rules".to_string()),
230+ ("hybrid".to_string(), "hybrid".to_string()),
231+ ("bruteforce".to_string(), "bruteforce".to_string()),
232+ ("rainbow".to_string(), "rainbow".to_string()),
233+ ],
234+ )
235+ .selected("wordlist".to_string())
236+ .on_change({
237+ let view = view.clone();
238+ move |mode, _window, cx| {
239+ view.update(cx, |app, cx| {
240+ app.attack_mode = mode;
241+ cx.notify();
242+ });
243+ }
244+ }),
245+ )
246+ });
247+ let charset_input = cx.new(InputState::new_singleline);
248+ let len_min_input = cx.new(InputState::new_singleline);
249+ len_min_input.update(cx, |input, cx| input.set_content("8", cx));
250+ let len_max_input = cx.new(InputState::new_singleline);
251+ len_max_input.update(cx, |input, cx| input.set_content("10", cx));
252+ let rainbow_input = cx.new(InputState::new_singleline);
253+ let rules_input = cx.new(InputState::new_singleline);
254+ rules_input.update(cx, |input, cx| {
255+ input.set_content("/path/to/rules (e.g. best64.rule)", cx);
256+ });
257+ let strength_input = cx.new(InputState::new_singleline);
258+ let hyb_min_input = cx.new(InputState::new_singleline);
259+ hyb_min_input.update(cx, |input, cx| input.set_content("1", cx));
260+ let hyb_max_input = cx.new(InputState::new_singleline);
261+ hyb_max_input.update(cx, |input, cx| input.set_content("2", cx));
262+
144 let mut this = AppRoot {263 let mut this = AppRoot {
145 state: AppState::new(&selected_iface),264 state: AppState::new(&selected_iface),
146 rx,265 rx,
147 tx,266 tx,
148- page: Page::Networks,267+ page: std::env::var("WIFILAB_PAGE")
268+ .ok()
269+ .and_then(|p| Page::from_name(&p))
270+ .unwrap_or(Page::Networks),
149 is_root: crate::iface::is_root(),271 is_root: crate::iface::is_root(),
150 service: None,272 service: None,
151 is_mock,273 is_mock,
152 selected: None,274 selected: None,
275+ selected_ap: None,
153 selected_client: None,276 selected_client: None,
154 hs_progress: BTreeMap::new(),277 hs_progress: BTreeMap::new(),
155 attacking_handshake: false,278 attacking_handshake: false,
156 attacking_pmkid: false,279 attacking_pmkid: false,
280+ parked_channels: None,
157 crack_inflight: false,281 crack_inflight: false,
158- pending_toast: None,282+ crack_stop: None,
283+ rainbow_stop: None,
284+ last_session_save: Instant::now(),
285+ pending_toast: std::collections::VecDeque::new(),
159 nm_active: false,286 nm_active: false,
160 crack_epoch: 0,287 crack_epoch: 0,
161 ap_sort: None,288 ap_sort: None,
@@ -167,9 +294,74 @@ impl AppRoot {
167 SelectState::new(select("cracker-target", "Crack target", empty))294 SelectState::new(select("cracker-target", "Crack target", empty))
168 }),295 }),
169 wordlist_input,296 wordlist_input,
297+ attack_select,
298+ attack_mode: "wordlist".to_string(),
299+ cs_lower: false,
300+ cs_upper: false,
301+ cs_digits: true,
302+ cs_special: false,
303+ charset_input,
304+ len_min_input,
305+ len_max_input,
306+ rainbow_input,
170 deauth_input,307 deauth_input,
308+ label_input,
309+ log_input,
310+ rules_input,
311+ strength_input,
312+ hyb_min_input,
313+ hyb_max_input,
314+ freq_order: true,
315+ bench_running: false,
316+ import_busy: false,
317+ deauth_all_targets: 0,
318+ profiles: match crate::store::load_profiles() {
319+ Ok(p) => p,
320+ Err(e) => {
321+ eprintln!("profiles: load failed, starting empty: {e:#}");
322+ crate::store::Profiles::default()
323+ }
324+ },
171 };325 };
326+ match crate::store::load() {
327+ Ok(labels) => {
328+ let n = labels.len();
329+ this.state.labels = labels;
330+ this.state
331+ .push_log(format!("labels: {n} loaded from ~/wifilab/labels.json"));
332+ }
333+ Err(e) => this
334+ .state
335+ .push_log(format!("labels: load failed, starting empty: {e:#}")),
336+ }
337+ // Restore previous captures so the cracker can keep working across
338+ // restarts without re-running attacks.
339+ match crate::store::load_captures() {
340+ Ok(caps) => {
341+ let n = caps.len();
342+ for cap in caps {
343+ match cap {
344+ crate::store::StoredCapture::Handshake(h) => {
345+ this.state.apply(Event::HandshakeComplete(Box::new(h)));
346+ }
347+ crate::store::StoredCapture::Pmkid(p) => {
348+ this.state.apply(Event::PmkidCaptured(p));
349+ }
350+ }
351+ }
352+ if n > 0 {
353+ this.state
354+ .push_log(format!("captures: {n} restored from ~/wifilab/captures.jsonl"));
355+ }
356+ }
357+ Err(e) => this
358+ .state
359+ .push_log(format!("captures: restore failed: {e:#}")),
360+ }
172 this.rebuild_target_select(cx);361 this.rebuild_target_select(cx);
362+ if !is_mock {
363+ this.restore_crack_session();
364+ }
173 this.state.push_log(if is_mock {365 this.state.push_log(if is_mock {
174 "wifilab UI started (mock backend)".to_string()366 "wifilab UI started (mock backend)".to_string()
175 } else {367 } else {
@@ -179,9 +371,15 @@ impl AppRoot {
179 });371 });
180 372
181 cx.on_release(|this, _cx| {373 cx.on_release(|this, _cx| {
182- // Window closed → root view released → shut the service down374+ // Window closed → root view released → stop UI-process jobs
183- // (it stops workers, restores managed mode, exits) and stop375+ // (crack + rainbow build) and shut the service down (it stops
184- // any UI-side crack job.376+ // workers, restores managed mode, exits).
377+ for flag in [this.crack_stop.take(), this.rainbow_stop.take()]
378+ .into_iter()
379+ .flatten()
380+ {
381+ flag.store(true, Ordering::Relaxed);
382+ }
185 if let Some(svc) = this.service.take() {383 if let Some(svc) = this.service.take() {
186 svc.shutdown();384 svc.shutdown();
187 }385 }
@@ -239,7 +437,11 @@ impl AppRoot {
239 .push_log("ui: stopping capture, service restores managed mode…");437 .push_log("ui: stopping capture, service restores managed mode…");
240 svc.stop_scan();438 svc.stop_scan();
241 }439 }
440+ // Stopping also kills every attack worker — un-spin buttons.
242 self.state.iface_running = false;441 self.state.iface_running = false;
442+ self.parked_channels = None;
443+ self.attacking_handshake = false;
444+ self.attacking_pmkid = false;
243 cx.notify();445 cx.notify();
244 } else {446 } else {
245 // NetworkManager fight: pin-to-connected-channel makes ONLY the447 // NetworkManager fight: pin-to-connected-channel makes ONLY the
@@ -251,8 +453,8 @@ impl AppRoot {
251 network's channel; you will likely see ONLY that SSID. Use \"Stop NM\" in the header."453 network's channel; you will likely see ONLY that SSID. Use \"Stop NM\" in the header."
252 .to_string(),454 .to_string(),
253 );455 );
254- self.pending_toast = Some(456+ self.queue_toast(
255- "NetworkManager is active — only your connected network may be visible; stop it from the header".into(),457+ "NetworkManager is active — only your connected network may be visible; stop it from the header",
256 );458 );
257 }459 }
258 let ifname = self.state.ifname.clone();460 let ifname = self.state.ifname.clone();
@@ -262,8 +464,11 @@ impl AppRoot {
262 svc.cmd(&Cmd::StartScan {464 svc.cmd(&Cmd::StartScan {
263 ifname: ifname.clone(),465 ifname: ifname.clone(),
264 channels: None,466 channels: None,
467+ spool: Some(crate::store::data_dir().join("spool.pcap")),
468+ fresh_spool: true,
265 });469 });
266 self.state.iface_running = true;470 self.state.iface_running = true;
471+ self.parked_channels = None;
267 self.state472 self.state
268 .push_log(format!("ui: capture started on {ifname}"));473 .push_log(format!("ui: capture started on {ifname}"));
269 cx.notify();474 cx.notify();
@@ -279,8 +484,7 @@ impl AppRoot {
279 Err(e) => {484 Err(e) => {
280 self.state485 self.state
281 .push_log(format!("ERROR: start capture on {ifname}: {e:#}"));486 .push_log(format!("ERROR: start capture on {ifname}: {e:#}"));
282- self.pending_toast =487+ self.queue_toast(format!("start capture failed: {e:#}"));
283- Some(format!("start capture failed: {e:#}").into());
284 }488 }
285 }489 }
286 cx.notify();490 cx.notify();
@@ -305,6 +509,15 @@ impl AppRoot {
305 cx.notify();509 cx.notify();
306 }510 }
307 511
512+ /// Queue a toast for the next render pass (the event loop has no
513+ /// Window). Capped at 3 — oldest dropped first.
514+ pub fn queue_toast(&mut self, msg: impl Into<SharedString>) {
515+ if self.pending_toast.len() == 3 {
516+ self.pending_toast.pop_front();
517+ }
518+ self.pending_toast.push_back(msg.into());
519+ }
520+
308 /// Drain every queued event, track handshake progress, refresh widgets521 /// Drain every queued event, track handshake progress, refresh widgets
309 /// derived from the capture set.522 /// derived from the capture set.
310 fn drain_events(&mut self, cx: &mut Context<Self>) {523 fn drain_events(&mut self, cx: &mut Context<Self>) {
@@ -319,9 +532,19 @@ impl AppRoot {
319 Event::HandshakeComplete(cap) => {532 Event::HandshakeComplete(cap) => {
320 self.hs_progress.remove(&(cap.ap, cap.client));533 self.hs_progress.remove(&(cap.ap, cap.client));
321 self.attacking_handshake = false;534 self.attacking_handshake = false;
535+ if let Err(e) = crate::store::append_capture(
536+ &crate::store::StoredCapture::Handshake(cap.as_ref().clone()),
537+ ) {
538+ self.state.push_log(format!("capture save FAILED: {e:#}"));
539+ }
322 }540 }
323- Event::PmkidCaptured(_) => {541+ Event::PmkidCaptured(cap) => {
324 self.attacking_pmkid = false;542 self.attacking_pmkid = false;
543+ if let Err(e) = crate::store::append_capture(
544+ &crate::store::StoredCapture::Pmkid(cap.clone()),
545+ ) {
546+ self.state.push_log(format!("capture save FAILED: {e:#}"));
547+ }
325 }548 }
326 // Service child died (EOF seen by the reader thread):549 // Service child died (EOF seen by the reader thread):
327 // un-flip every running flag and drop the client so the550 // un-flip every running flag and drop the client so the
@@ -343,10 +566,13 @@ impl AppRoot {
343 self.attacking_handshake = false;566 self.attacking_handshake = false;
344 self.attacking_pmkid = false;567 self.attacking_pmkid = false;
345 }568 }
569+ // Terminal attack-worker log lines un-spin the buttons.
570+ // NOT a generic prefix match: "handshake: listening for
571+ // 4-way…" fires right at worker start and would instantly
572+ // kill the spinner while the worker runs.
346 Event::Log(line)573 Event::Log(line)
347- if ["handshake:", "pmkid:"]574+ if line.starts_with("handshake: capture ended")
348- .iter()575+ || line.starts_with("pmkid: no PMKID") =>
349- .any(|p| line.starts_with(p)) =>
350 {576 {
351 self.attacking_handshake = false;577 self.attacking_handshake = false;
352 self.attacking_pmkid = false;578 self.attacking_pmkid = false;
@@ -355,22 +581,79 @@ impl AppRoot {
355 Event::Log(line) if line.starts_with("nm:") => {581 Event::Log(line) if line.starts_with("nm:") => {
356 if line == "nm: stopped" {582 if line == "nm: stopped" {
357 self.nm_active = false;583 self.nm_active = false;
358- self.pending_toast = Some(584+ self.queue_toast(
359- "NetworkManager stopped — all networks become visible as the hopper cycles"585+ "NetworkManager stopped — all networks become visible as the hopper cycles",
360- .into(),
361 );586 );
362 }587 }
363 }588 }
364- Event::CrackStopped { .. } => {589+ Event::CrackProgress { .. } => {
590+ self.maybe_save_crack_session();
591+ }
592+ Event::CrackStopped { found } => {
365 self.crack_inflight = false;593 self.crack_inflight = false;
594+ self.crack_stop = None;
595+ self.finalize_crack_session(*found);
596+ }
597+ Event::RainbowBuilt { .. } => {
598+ self.rainbow_stop = None;
366 }599 }
367 Event::CrackFound { password } => {600 Event::CrackFound { password } => {
368- self.pending_toast =601+ self.queue_toast(format!("password recovered: {password}"));
369- Some(format!("password recovered: {password}").into());602+ // Best-effort desktop notification; headless/no-D-Bus
603+ // just drops the error.
604+ let _ = notify_rust::Notification::new()
605+ .summary("wifilab: password found")
606+ .body(&format!("password recovered: {password}"))
607+ .show();
608+ }
609+ Event::CaptureImported(cap) => {
610+ let stored = match cap {
611+ crate::common::ImportedCapture::Handshake(h) => {
612+ crate::store::StoredCapture::Handshake(h.as_ref().clone())
613+ }
614+ crate::common::ImportedCapture::Pmkid(p) => {
615+ crate::store::StoredCapture::Pmkid(p.clone())
616+ }
617+ };
618+ if let Err(e) = crate::store::append_capture(&stored) {
619+ self.state
620+ .push_log(format!("import: capture save FAILED: {e:#}"));
621+ }
622+ }
623+ Event::BenchmarkDone { .. } => {
624+ self.bench_running = false;
370 }625 }
371 _ => {}626 _ => {}
372 }627 }
373 captures_changed |= self.state.apply(event);628 captures_changed |= self.state.apply(event);
629+ if let Some(m) = self.state.deauth_alert.take() {
630+ self.queue_toast(m);
631+ }
632+ if let Some(m) = self.state.rogue_alert.take() {
633+ self.queue_toast(m);
634+ }
635+ if let Some(m) = self.state.ident_alert.take() {
636+ self.queue_toast(m);
637+ }
638+ }
639+ // Keep the target snapshot in lockstep with the live AP row (a
640+ // click-time-only snapshot goes stale: channel jumps, beacon
641+ // counts, security updates). Also self-heals after service
642+ // restarts, when only the live row exists.
643+ if let Some(live) = self
644+ .selected
645+ .and_then(|b| self.state.aps.get(&b).cloned())
646+ {
647+ self.selected_ap = Some(live);
648+ }
649+ // Mock-only convenience: pre-select the first heard AP so the
650+ // Attacks page shows its target card without a manual click —
651+ // invaluable for headless UI verification. Never in real mode.
652+ if self.is_mock && self.selected.is_none() {
653+ if let Some((&b, _)) = self.state.aps.first_key_value() {
654+ self.selected = Some(b);
655+ self.selected_ap = self.state.aps.get(&b).cloned();
656+ }
374 }657 }
375 if captures_changed {658 if captures_changed {
376 self.rebuild_target_select(cx);659 self.rebuild_target_select(cx);
@@ -380,9 +663,115 @@ impl AppRoot {
380 }663 }
381 }664 }
382 665
666+ /// Persist the interrupted crack run (resume file), throttled to one
667+ /// write per 2 s of progress events. UI-thread only (called from the
668+ /// event drain).
669+ fn maybe_save_crack_session(&mut self) {
670+ if self.last_session_save.elapsed() < Duration::from_secs(2) {
671+ return;
672+ }
673+ self.last_session_save = Instant::now();
674+ self.save_crack_session();
675+ }
676+
677+ /// Write the current run to ~/wifilab/crack-session.json. No-op when
678+ /// nothing resumable is in flight (mock runs never persist).
679+ fn save_crack_session(&mut self) {
680+ let (Some(attack), Some(desc)) = (
681+ self.state.cracker.active_attack.clone(),
682+ self.state.cracker.target.clone(),
683+ ) else {
684+ return;
685+ };
686+ let done = self.state.cracker.tried;
687+ if done == 0 {
688+ return;
689+ }
690+ let Some(idx) = self
691+ .state
692+ .capture_descs()
693+ .iter()
694+ .position(|d| *d == desc)
695+ else {
696+ return;
697+ };
698+ let Some(capture) = self.state.stored_capture_at(idx) else {
699+ return;
700+ };
701+ let total = self.state.cracker.total;
702+ let session = crate::store::CrackSession { capture, attack, done, total };
703+ if let Err(e) = crate::store::save_session(&session) {
704+ self.state.push_log(format!("cracker: session save failed: {e:#}"));
705+ return;
706+ }
707+ // The just-saved run is resumable right now (same session or the
708+ // next start): keep the banner in sync.
709+ self.state.cracker.resume = Some(crate::ui::state::ResumeInfo {
710+ target_desc: desc,
711+ attack: session.attack,
712+ done,
713+ total,
714+ });
715+ }
716+
717+ /// Settle the session file when a run ends: found/exhausted → delete
718+ /// (nothing left to resume); stopped mid-way → final save + banner.
719+ fn finalize_crack_session(&mut self, found: bool) {
720+ let done = self.state.cracker.tried;
721+ let total = self.state.cracker.total;
722+ let exhausted = !found && total.is_some_and(|t| done >= t);
723+ if found || exhausted {
724+ if let Err(e) = crate::store::clear_session() {
725+ self.state.push_log(format!("cracker: session clear failed: {e:#}"));
726+ }
727+ self.state.cracker.resume = None;
728+ } else if self.state.cracker.active_attack.is_some() {
729+ // User-stopped (or worker-ended) with room left: persist the
730+ // position — this is the whole point of the feature.
731+ self.last_session_save = Instant::now();
732+ self.save_crack_session();
733+ }
734+ self.state.cracker.active_attack = None;
735+ }
736+
737+ /// Match a saved session against the loaded captures on startup:
738+ /// a match arms the resume banner on the cracker page.
739+ fn restore_crack_session(&mut self) {
740+ let session = match crate::store::load_session() {
741+ Ok(Some(s)) => s,
742+ Ok(None) => return,
743+ Err(e) => {
744+ self.state
745+ .push_log(format!("cracker: saved session unreadable: {e:#}"));
746+ return;
747+ }
748+ };
749+ let descs = self.state.capture_descs();
750+ let hit = descs.iter().enumerate().find(|(i, _)| {
751+ self.state.stored_capture_at(*i).as_ref() == Some(&session.capture)
752+ });
753+ match hit.map(|(_, d)| d) {
754+ Some(d) => {
755+ let done = session.done;
756+ self.state.cracker.resume = Some(crate::ui::state::ResumeInfo {
757+ target_desc: d.clone(),
758+ attack: session.attack,
759+ done,
760+ total: session.total,
761+ });
762+ self.state
763+ .push_log(format!("cracker: resumable saved run restored ({d}, {done} tried)"));
764+ }
765+ None => self
766+ .state
767+ .push_log("cracker: saved session ignored — its capture is gone".to_string()),
768+ }
769+ }
770+
383 /// The cracker target dropdown mirrors `state.capture_descs()`; rebuild771 /// The cracker target dropdown mirrors `state.capture_descs()`; rebuild
384 /// it whenever a handshake/PMKID arrives, keeping the current choice if772 /// it whenever a handshake/PMKID arrives, keeping the current choice if
385- /// it still exists.773+ /// it still exists. With no captures the select is disabled so its
774+ /// (empty) popup cannot open.
386 pub fn rebuild_target_select(&mut self, cx: &mut Context<Self>) {775 pub fn rebuild_target_select(&mut self, cx: &mut Context<Self>) {
387 let descs = self.state.capture_descs();776 let descs = self.state.capture_descs();
388 let keep = self777 let keep = self
@@ -397,7 +786,12 @@ impl AppRoot {
397 "Crack target",786 "Crack target",
398 descs.iter().map(|d| (d.clone(), d.clone())).collect::<Vec<_>>(),787 descs.iter().map(|d| (d.clone(), d.clone())).collect::<Vec<_>>(),
399 )788 )
400- .placeholder("Select a capture…")789+ .placeholder(if descs.is_empty() {
790+ "no captures yet — capture a handshake or PMKID first"
791+ } else {
792+ "Select a capture…"
793+ })
794+ .disabled(descs.is_empty())
401 .on_change(move |value, _window, cx| {795 .on_change(move |value, _window, cx| {
402 view.update(cx, |app, cx| {796 view.update(cx, |app, cx| {
403 app.state.cracker.target = Some(value);797 app.state.cracker.target = Some(value);
@@ -445,12 +839,17 @@ impl AppRoot {
445 let theme = cx.theme().clone();839 let theme = cx.theme().clone();
446 let running = self.state.iface_running;840 let running = self.state.iface_running;
447 841
448- let privilege = if self.is_root {842+ // Status of the SERVICE process (the thing that actually touches
449- badge("root").secondary()843+ // the radio): any running service is root — spawned directly when
450- } else if self.is_mock {844+ // the UI is root, via pkexec (root by definition) otherwise.
845+ let privilege = if self.is_mock {
451 badge("not root (mock)").secondary()846 badge("not root (mock)").secondary()
847+ } else if self.service.is_some() {
848+ badge("service: root").secondary()
849+ } else if self.is_root {
850+ badge("ui: root · service not started").secondary()
452 } else {851 } else {
453- badge("user (service will elevate)").secondary()852+ badge("ui: user · service not started").secondary()
454 };853 };
455 854
456 let toggle = button(855 let toggle = button(
@@ -558,7 +957,7 @@ impl Render for AppRoot {
558 let view = cx.entity();957 let view = cx.entity();
559 958
560 // Flush toasts queued by the event-drain loop (which has no Window).959 // Flush toasts queued by the event-drain loop (which has no Window).
561- if let Some(msg) = self.pending_toast.take() {960+ while let Some(msg) = self.pending_toast.pop_front() {
562 cx.toast(msg).show(_window, cx);961 cx.toast(msg).show(_window, cx);
563 }962 }
564 963
src/ui/attacks.rsmodified+783 -63
@@ -16,7 +16,7 @@ use gpuikit::elements::typography::{h3, small, text};
16 use gpuikit::layout::{h_stack, v_stack};16 use gpuikit::layout::{h_stack, v_stack};
17 use gpuikit::theme::{ActiveTheme, Themeable};17 use gpuikit::theme::{ActiveTheme, Themeable};
18 18
19-use crate::common::{Cmd, Event, HandshakeCapture, MacAddr, PmkidCapture};19+use crate::common::{Akm, ClientInfo, Cmd, Event, HandshakeCapture, MacAddr, PmkidCapture};
20 use crate::ui::app::AppRoot;20 use crate::ui::app::AppRoot;
21 use crate::ui::mock;21 use crate::ui::mock;
22 22
@@ -94,6 +94,53 @@ fn export_hc22000(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::A
94 .detach();94 .detach();
95 }95 }
96 96
97+/// Export the raw pcap spool (every frame the scanner saw since the
98+/// capture started) via the platform save dialog; falls back to a fixed
99+/// path under ./captures when the dialog is refused.
100+fn export_pcap(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
101+ let spool = crate::store::data_dir().join("spool.pcap");
102+ if !spool.is_file() {
103+ view.update(cx, |app, cx| {
104+ app.state
105+ .push_log("pcap export: no spool yet — start a capture first");
106+ cx.notify();
107+ });
108+ return;
109+ }
110+
111+ let suggested = format!("wifilab-{}.pcap", unix_secs());
112+ let prompt = cx.prompt_for_new_path(Path::new("./captures"), Some(&suggested));
113+ let weak = view.downgrade();
114+ cx.spawn(async move |cx| {
115+ // Dialog refused/cancelled → fixed fallback; explicit cancel aborts.
116+ let path: Option<PathBuf> = match prompt.await {
117+ Ok(Ok(Some(p))) => Some(p),
118+ Ok(Ok(None)) => None,
119+ _ => Some(PathBuf::from("./captures").join(&suggested)),
120+ };
121+ let _ = weak.update(cx, |app, cx| {
122+ match path {
123+ None => app.state.push_log("pcap export: cancelled"),
124+ Some(path) => {
125+ if let Some(parent) = path.parent() {
126+ let _ = std::fs::create_dir_all(parent);
127+ }
128+ match std::fs::copy(&spool, &path) {
129+ Ok(n) => app
130+ .state
131+ .push_log(format!("pcap export: {n} bytes → {}", path.display())),
132+ Err(e) => app
133+ .state
134+ .push_log(format!("pcap export FAILED: {e} ({})", path.display())),
135+ }
136+ }
137+ }
138+ cx.notify();
139+ });
140+ })
141+ .detach();
142+}
143+
97 /// Selected target with its current AP row (channel + essid).144 /// Selected target with its current AP row (channel + essid).
98 fn target_info(app: &AppRoot) -> Option<(MacAddr, u8, String)> {145 fn target_info(app: &AppRoot) -> Option<(MacAddr, u8, String)> {
99 let ap = app.selected?;146 let ap = app.selected?;
@@ -101,6 +148,115 @@ fn target_info(app: &AppRoot) -> Option<(MacAddr, u8, String)> {
101 Some((ap, row.channel, row.ssid.clone()))148 Some((ap, row.channel, row.ssid.clone()))
102 }149 }
103 150
151+/// The selected target's AP row for rendering: the live record wins;
152+/// otherwise the snapshot taken at click time (host-capture mode never
153+/// re-scans, so a valid target may have no live row at all). Second tuple
154+/// element is true when falling back to the (possibly stale) snapshot.
155+fn target_row(app: &AppRoot) -> Option<(&crate::common::AccessPoint, bool)> {
156+ let sel = app.selected?;
157+ if let Some(row) = app.state.aps.get(&sel) {
158+ return Some((row, false));
159+ }
160+ app.selected_ap.as_ref().map(|row| (row, true))
161+}
162+
163+/// Material already captured for this AP (dual-band siblings count as
164+/// their own BSSIDs — a handshake grabbed on the 5 GHz twin crackable
165+/// for the same password, so count the whole ESSID family).
166+fn material_for(app: &AppRoot, ap: &crate::common::AccessPoint) -> (usize, usize) {
167+ let essids = sibling_targets(app, &ap.ssid)
168+ .into_iter()
169+ .map(|(b, _)| b)
170+ .collect::<Vec<_>>();
171+ let hs = app
172+ .state
173+ .handshakes
174+ .iter()
175+ .filter(|h| essids.contains(&h.ap))
176+ .count();
177+ let pm = app
178+ .state
179+ .pmkids
180+ .iter()
181+ .filter(|p| essids.contains(&p.ap))
182+ .count();
183+ (hs, pm)
184+}
185+
186+/// One-line "best next move" for the selected target, computed from what
187+/// the scanner already knows — the answer to "which button do I press".
188+/// Second tuple element: true = actionable path, false = dead end (the
189+/// card colors accordingly).
190+fn advisor(app: &AppRoot, ap: &crate::common::AccessPoint) -> (&'static str, bool) {
191+ use crate::common::Security;
192+ let akms = &ap.akms;
193+ let sae = !akms.is_empty()
194+ && akms.contains(&Akm::Sae)
195+ && !akms.contains(&Akm::Psk)
196+ && !akms.contains(&Akm::PskSha256);
197+ if sae {
198+ return (
199+ "advice: SAE-only — no offline-crackable material exists (dead end for today)",
200+ false,
201+ );
202+ }
203+ match ap.security {
204+ Security::Open => return ("advice: open network — nothing to crack", false),
205+ Security::Wep => {
206+ return (
207+ "advice: WEP — ancient; out of scope here (use dedicated tools)",
208+ false,
209+ );
210+ }
211+ _ => {}
212+ }
213+ if !akms.is_empty() && akms.contains(&Akm::Owe) && !akms.contains(&Akm::Psk) {
214+ return ("advice: OWE (enhanced open) — no password to recover", false);
215+ }
216+ let (hs, pm) = material_for(app, ap);
217+ if hs + pm > 0 {
218+ return (
219+ "advice: capture material in hand — crack it on the Cracker page",
220+ true,
221+ );
222+ }
223+ if sae_transition(akms) {
224+ return (
225+ "advice: WPA3 transition (PSK still offered) — handshake capture or PMKID works",
226+ true,
227+ );
228+ }
229+ if connected_clients(app, ap.bssid).is_empty() {
230+ (
231+ "advice: no clients mapped — run PMKID first (clientless), then park a handshake capture",
232+ true,
233+ )
234+ } else {
235+ (
236+ "advice: deauth a client while handshake capture runs — it re-auths with a fresh 4-way",
237+ true,
238+ )
239+ }
240+}
241+
242+fn sae_transition(akms: &[Akm]) -> bool {
243+ akms.contains(&Akm::Sae) && (akms.contains(&Akm::Psk) || akms.contains(&Akm::PskSha256))
244+}
245+
246+/// WPA3 SAE-only targets yield no offline-crackable material: the
247+/// dragonfly handshake can't be brute-forced offline and SAE APs never
248+/// hand out a PMKID. Transition-mode APs (PSK alongside SAE) still work.
249+fn sae_only(app: &AppRoot) -> bool {
250+ let Some((row, _stale)) = target_row(app) else {
251+ return false;
252+ };
253+ let akms = &row.akms;
254+ !akms.is_empty()
255+ && akms.contains(&Akm::Sae)
256+ && !akms.contains(&Akm::Psk)
257+ && !akms.contains(&Akm::PskSha256)
258+}
259+
104 /// Capture Handshake.260 /// Capture Handshake.
105 /// Mock mode: drive a fresh fabricated 4-way through the event pipeline.261 /// Mock mode: drive a fresh fabricated 4-way through the event pipeline.
106 /// Real mode: spawn the backend capture worker (channel probed first via262 /// Real mode: spawn the backend capture worker (channel probed first via
@@ -125,18 +281,25 @@ fn capture_handshake(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui
125 cx.notify();281 cx.notify();
126 282
127 if !app.is_mock {283 if !app.is_mock {
128- let Some((ap, channel, essid)) = target_info(app) else {284+ let Some((_sel_bssid, _sel_ch, essid)) = target_info(app) else {
129 app.state285 app.state
130 .push_log("handshake: target AP not in scan table yet");286 .push_log("handshake: target AP not in scan table yet");
131 app.attacking_handshake = false;287 app.attacking_handshake = false;
132 cx.notify();288 cx.notify();
133 return;289 return;
134 };290 };
291+ // Dual-band: watch EVERY BSSID of this ESSID (the scanner
292+ // parks on the union of channels, so all bands are covered).
293+ let targets = sibling_targets(app, &essid);
294+ let channels = channels_of(&targets);
135 app.state.push_log(format!(295 app.state.push_log(format!(
136- "handshake capture on {essid} ({ap}, ch {channel})…"296+ "handshake capture on {essid} — {} bssid(s), ch [{}]… deauth a client to force re-auth",
297+ targets.len(),
298+ channels.iter().map(u8::to_string).collect::<Vec<_>>().join(", ")
137 ));299 ));
300+ park_channels(app, &channels);
138 if let Some(svc) = &app.service {301 if let Some(svc) = &app.service {
139- svc.cmd(&Cmd::CaptureHs { ap, channel, essid });302+ svc.cmd(&Cmd::CaptureHs { targets, essid });
140 }303 }
141 cx.notify();304 cx.notify();
142 return;305 return;
@@ -222,6 +385,7 @@ fn pmkid_attack(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App
222 };385 };
223 app.state386 app.state
224 .push_log(format!("pmkid attack on {essid} ({ap}, ch {channel})…"));387 .push_log(format!("pmkid attack on {essid} ({ap}, ch {channel})…"));
388+ park_channels(app, &[channel]);
225 if let Some(svc) = &app.service {389 if let Some(svc) = &app.service {
226 svc.cmd(&Cmd::Pmkid { ap, channel, essid });390 svc.cmd(&Cmd::Pmkid { ap, channel, essid });
227 }391 }
@@ -257,74 +421,324 @@ fn pmkid_attack(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App
257 });421 });
258 }422 }
259 423
260-/// Deauth: broadcast by default, or target the selected client's station.424+/// Every BSSID sharing the target's ESSID, with the selected target
261-/// Real mode blasts from the backend's own socket; mock mode fabricates425+/// first — dual-band routers broadcast one SSID on several bands and the
426+/// client picks one; attacks must cover all of them. Falls back to just
427+/// the selected target when nothing else is known.
428+fn sibling_targets(app: &AppRoot, essid: &str) -> Vec<(MacAddr, u8)> {
429+ let mut targets: Vec<(MacAddr, u8)> = Vec::new();
430+ let mut others: Vec<(MacAddr, u8)> = Vec::new();
431+ for a in app.state.aps.values() {
432+ if a.ssid == essid && a.channel != 0 {
433+ if Some(a.bssid) == app.selected {
434+ targets.push((a.bssid, a.channel));
435+ } else {
436+ others.push((a.bssid, a.channel));
437+ }
438+ }
439+ }
440+ targets.extend(others);
441+ targets
442+}
443+
444+/// Union of channels of a target list (sorted, deduped, zeros dropped).
445+fn channels_of(targets: &[(MacAddr, u8)]) -> Vec<u8> {
446+ let mut ch: Vec<u8> = targets.iter().map(|(_, c)| *c).collect();
447+ ch.sort_unstable();
448+ ch.dedup();
449+ ch
450+}
451+
452+/// Restrict the scanner to the target channels so attack workers aren't
453+/// fighting the 100 ms spectrum-wide hopper (capture/PMKID listen, deauth
454+/// injects — a far-away radio is mostly deaf/blind). Restarts the scanner
455+/// with the restricted plan when not already parked on it; a no-op
456+/// otherwise and in mock mode.
457+fn park_channels(app: &mut AppRoot, channels: &[u8]) {
458+ let mut want = channels.to_vec();
459+ want.sort_unstable();
460+ want.dedup();
461+ if app.is_mock || want.is_empty() || app.parked_channels.as_deref() == Some(&want) {
462+ return;
463+ }
464+ // A channel-plan restart also stops any running attack worker — the
465+ // new plan invalidates them; the caller (re)spawns its own worker
466+ // right after.
467+ if let Some(svc) = &app.service {
468+ svc.cmd(&Cmd::StartScan {
469+ ifname: app.state.ifname.clone(),
470+ channels: Some(want.clone()),
471+ // Keep appending to the same spool across attack-mode restarts
472+ // — only the toggle-monitor start truncates.
473+ spool: Some(crate::store::data_dir().join("spool.pcap")),
474+ fresh_spool: false,
475+ });
476+ app.parked_channels = Some(want.clone());
477+ app.state
478+ .push_log(format!("scanner parked on ch [{}] (attack mode)", want.iter().map(u8::to_string).collect::<Vec<_>>().join(", ")));
479+ }
480+}
481+
482+/// Deauth `target` (a station, or [`MacAddr::BROADCAST`] for the whole
483+/// net) against the selected AP, `count` rounds from the count field.
484+/// Real mode blasts from the service's own socket; mock mode fabricates
262 /// the same DeauthSent event the real worker emits.485 /// the same DeauthSent event the real worker emits.
486+fn do_deauth(app: &mut AppRoot, cx: &mut Context<AppRoot>, target: MacAddr) {
487+ let Some(ap) = app.selected else {
488+ app.state.push_log("deauth: no target selected");
489+ cx.notify();
490+ return;
491+ };
492+ let count64: u64 = app
493+ .deauth_input
494+ .read(cx)
495+ .content()
496+ .trim()
497+ .parse()
498+ // 64 rounds ≈ 2 s of airtime per direction — short bursts
499+ // (16 × 15 ms ≈ 0.25 s) slip entirely under a power-save client's
500+ // doze window and land nothing (verified on lab mt7922).
501+ .unwrap_or(64);
502+
503+ if !app.is_mock {
504+ if !app.state.iface_running {
505+ app.state
506+ .push_log("deauth: start capture first (injection needs monitor mode)");
507+ cx.notify();
508+ return;
509+ }
510+ if app.service.is_none() {
511+ app.state
512+ .push_log("deauth: start capture first (the service owns the radio)");
513+ cx.notify();
514+ return;
515+ }
516+ let Some((_sel_bssid, _sel_ch, essid)) = target_info(app) else {
517+ app.state
518+ .push_log("deauth: target AP not in scan table yet");
519+ cx.notify();
520+ return;
521+ };
522+ // Dual-band: blast every BSSID of this ESSID — the client picks
523+ // the band, we don't get to. The service worker walks the list
524+ // sequentially.
525+ let aps = sibling_targets(app, &essid);
526+ let channels = channels_of(&aps);
527+ // Park ONCE on the final plan before sending ANY attack command:
528+ // a channel-plan restart stop-joins all workers, so parking later
529+ // would kill the capture worker armed just below.
530+ park_channels(app, &channels);
531+ // A deauth without a listener yields nothing: arm a handshake
532+ // capture first when none is running (the flag is app-global —
533+ // one target at a time, matching the attacks page). CaptureHs is
534+ // handled before Deauth (single command pipe), and the service
535+ // holds the channel synchronously there, so the blast can't shake
536+ // a client loose onto an unwatched band.
537+ if !app.attacking_handshake {
538+ app.attacking_handshake = true;
539+ app.state.push_log(format!(
540+ "deauth: no capture running — auto-armed handshake capture on {essid}"
541+ ));
542+ app.service
543+ .as_ref()
544+ .expect("service presence checked above")
545+ .cmd(&Cmd::CaptureHs {
546+ targets: aps.clone(),
547+ essid: essid.clone(),
548+ });
549+ }
550+ let count = count64.min(u32::MAX as u64) as u32;
551+ let kind = if target.is_broadcast() {
552+ "broadcast".to_string()
553+ } else {
554+ format!("client {target}")
555+ };
556+ app.state.push_log(format!(
557+ "deauth: {count} rounds → {kind} ({} bssid(s), ch [{}])",
558+ aps.len(),
559+ channels.iter().map(u8::to_string).collect::<Vec<_>>().join(", ")
560+ ));
561+ app.service
562+ .as_ref()
563+ .expect("service presence checked above")
564+ .cmd(&Cmd::Deauth { aps: aps.clone(), target, count });
565+ // Optimistic DOWN marking: monitor-mode TX never loops back to
566+ // the scanner socket (verified: PACKET_OUTGOING never surfaces on
567+ // mt7921e injection), so the scanner can't observe our own blast
568+ // and the row would stay "up" until the client talks again
569+ // (ClientUpdated flips it back) or ages out. Broadcast → every
570+ // station mapped to a sibling BSSID of this ESSID.
571+ for cl in app.state.clients.values_mut() {
572+ let blasted = if target.is_broadcast() {
573+ cl.ap.is_some_and(|cap| aps.iter().any(|(b, _)| *b == cap))
574+ } else {
575+ cl.mac == target
576+ };
577+ if blasted {
578+ cl.connected = false;
579+ }
580+ }
581+ cx.notify();
582+ return;
583+ }
584+
585+ let _ = app.tx.send(Event::DeauthSent {
586+ ap,
587+ target,
588+ count: count64,
589+ });
590+ // Same optimistic DOWN marking as the real branch (see there).
591+ for cl in app.state.clients.values_mut() {
592+ let blasted = if target.is_broadcast() {
593+ cl.ap.is_none_or(|cap| cap == ap)
594+ } else {
595+ cl.mac == target
596+ };
597+ if blasted {
598+ cl.connected = false;
599+ }
600+ }
601+ cx.notify();
602+}
603+
604+/// A client row counts as belonging to the selected target when the
605+/// scanner mapped it there — OR when its AP is unknown (the scanner often
606+/// never resolves the association; trust the user's pick).
607+fn client_on_target(app: &AppRoot, mac: &MacAddr, ap: MacAddr) -> bool {
608+ app.state
609+ .clients
610+ .get(mac)
611+ .is_some_and(|c| c.ap.is_none_or(|cap| cap == ap))
612+}
613+
614+/// Deauth button: a selected client row (see [`client_on_target`]) wins;
615+/// otherwise deauth the whole net broadcast-style.
263 fn deauth(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {616 fn deauth(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
617+ view.update(cx, |app, cx| {
618+ let target = app
619+ .selected
620+ .and_then(|ap| {
621+ app.selected_client
622+ .filter(|mac| client_on_target(app, mac, ap))
623+ })
624+ .unwrap_or(MacAddr::BROADCAST);
625+ do_deauth(app, cx, target);
626+ });
627+}
628+
629+/// Per-station Deauth button in the stations table: fires immediately at
630+/// that station, no handshake capture required.
631+fn deauth_station(view: &Entity<AppRoot>, station: MacAddr, cx: &mut gpui::App) {
632+ view.update(cx, |app, cx| do_deauth(app, cx, station));
633+}
634+
635+/// Connected clients mapped to the selected AP (strict association —
636+/// `client_on_target`'s "unknown AP" leniency would sweep strangers into
637+/// a bulk blast).
638+fn connected_clients(app: &AppRoot, ap: MacAddr) -> Vec<MacAddr> {
639+ let mut macs: Vec<MacAddr> = app
640+ .state
641+ .clients
642+ .values()
643+ .filter(|c| c.ap == Some(ap) && c.connected && !c.mac.is_broadcast())
644+ .map(|c| c.mac)
645+ .collect();
646+ macs.sort();
647+ macs
648+}
649+
650+/// Bulk deauth: every connected client of the selected AP in one service
651+/// job (single channel pin, per-client rounds, then one broadcast blast).
652+/// Mock mode fabricates the same DeauthSent stream per client.
653+fn deauth_all(view: &Entity<AppRoot>, cx: &mut gpui::App) {
264 view.update(cx, |app, cx| {654 view.update(cx, |app, cx| {
265 let Some(ap) = app.selected else {655 let Some(ap) = app.selected else {
266- app.state.push_log("deauth: no target selected");656+ app.state.push_log("deauth-all: no target selected");
267 cx.notify();657 cx.notify();
268 return;658 return;
269 };659 };
660+ let targets = connected_clients(app, ap);
661+ if targets.len() < 2 {
662+ app.state
663+ .push_log("deauth-all: fewer than 2 connected clients — deauth them one by one");
664+ cx.notify();
665+ return;
666+ }
270 let count64: u64 = app667 let count64: u64 = app
271 .deauth_input668 .deauth_input
272 .read(cx)669 .read(cx)
273 .content()670 .content()
274 .trim()671 .trim()
275 .parse()672 .parse()
276- .unwrap_or(16);673+ .unwrap_or(64);
277 674
278 if !app.is_mock {675 if !app.is_mock {
279- if !app.state.iface_running {676+ if !app.state.iface_running || app.service.is_none() {
280 app.state677 app.state
281- .push_log("deauth: start capture first (injection needs monitor mode)");678+ .push_log("deauth-all: start capture first (injection needs monitor mode)");
282 cx.notify();679 cx.notify();
283 return;680 return;
284 }681 }
285- let Some(svc) = &app.service else {682+ let Some((_sel_bssid, channel, essid)) = target_info(app) else {
286 app.state683 app.state
287- .push_log("deauth: start capture first (the service owns the radio)");684+ .push_log("deauth-all: target AP not in scan table yet");
288 cx.notify();685 cx.notify();
289 return;686 return;
290 };687 };
291- let Some((ap, channel, _essid)) = target_info(app) else {688+ // Park before ANY attack command (see do_deauth) and arm a
292- app.state689+ // capture so the forced re-auths land in a listener.
293- .push_log("deauth: target AP not in scan table yet");690+ park_channels(app, &[channel]);
294- cx.notify();691+ if !app.attacking_handshake {
295- return;692+ app.attacking_handshake = true;
296- };693+ app.state.push_log(format!(
297- // A selected client row wins; otherwise deauth the whole net694+ "deauth-all: no capture running — auto-armed handshake capture on {essid}"
298- // broadcast-style. (Guard: the pair must still be consistent695+ ));
299- // with the live client table.)696+ let aps = sibling_targets(app, &essid);
300- let target = app697+ app.service
301- .selected_client698+ .as_ref()
302- .filter(|mac| {699+ .expect("service presence checked above")
303- app.state700+ .cmd(&Cmd::CaptureHs {
304- .clients701+ targets: aps,
305- .get(mac)702+ essid,
306- .is_some_and(|c| c.ap == Some(ap))703+ });
307- })704+ }
308- .unwrap_or(MacAddr::BROADCAST);
309 let count = count64.min(u32::MAX as u64) as u32;705 let count = count64.min(u32::MAX as u64) as u32;
310 app.state.push_log(format!(706 app.state.push_log(format!(
311- "deauth: {count} rounds → {target} (AP {ap}, ch {channel})"707+ "deauth-all: {count} rounds → {} clients of {ap} (ch {channel})",
708+ targets.len()
312 ));709 ));
313- svc.cmd(&Cmd::Deauth {710+ app.service
314- ap,711+ .as_ref()
315- target,712+ .expect("service presence checked above")
316- channel,713+ .cmd(&Cmd::DeauthAll {
317- count,714+ ap,
318- });715+ channel,
716+ targets: targets.clone(),
717+ count,
718+ });
719+ // Optimistic DOWN marking (see do_deauth).
720+ for cl in app.state.clients.values_mut() {
721+ if targets.contains(&cl.mac) {
722+ cl.connected = false;
723+ }
724+ }
319 cx.notify();725 cx.notify();
320 return;726 return;
321 }727 }
322 728
323- let _ = app.tx.send(Event::DeauthSent {729+ // ---- mock path ----
324- ap,730+ for target in &targets {
325- target: MacAddr::BROADCAST,731+ let _ = app.tx.send(Event::DeauthSent {
326- count: count64,732+ ap,
327- });733+ target: *target,
734+ count: count64,
735+ });
736+ }
737+ for cl in app.state.clients.values_mut() {
738+ if targets.contains(&cl.mac) {
739+ cl.connected = false;
740+ }
741+ }
328 cx.notify();742 cx.notify();
329 });743 });
330 }744 }
@@ -378,18 +792,107 @@ pub fn render(
378 ) -> gpui::Div {792 ) -> gpui::Div {
379 let theme = cx.theme().clone();793 let theme = cx.theme().clone();
380 794
381- let target_block = match app.selected.and_then(|b| {795+ // Client chip for the banner: the selected client counts when it's
382- app.state796+ // mapped to the target AP or its association is unknown (scanner often
383- .aps797+ // never resolves it).
384- .get(&b)798+ let banner_client: Option<MacAddr> = app.selected.and_then(|ap| {
385- .map(|ap| (ap.ssid.clone(), b, ap.channel))799+ app.selected_client
386- }) {800+ .filter(|mac| client_on_target(app, mac, ap))
387- Some((ssid, bssid, ch)) => h_stack()801+ });
388- .gap_3()802+
389- .items_center()803+ // Target context card: everything Networks knows about the target,
390- .child(h3(format!("target: {ssid}")))804+ // one glance, plus a computed "best next move". Falls back to the
391- .child(text(format!("{bssid} · ch {ch}")).code().small().into_any_element())805+ // click-time snapshot when the AP has no live row (host-capture
392- .into_any_element(),806+ // lock never re-scans) so the card can't silently go blank.
807+ let target_block: gpui::AnyElement = match target_row(app) {
808+ Some((ap, stale)) => {
809+ let bssid = ap.bssid;
810+ let (hs_n, pm_n) = material_for(app, ap);
811+ let siblings = sibling_targets(app, &ap.ssid).len();
812+ let akm_join = ap
813+ .akms
814+ .iter()
815+ .map(|a| a.label())
816+ .collect::<Vec<_>>()
817+ .join("+");
818+ let spark = app.state.rssi_hist.get(&bssid).cloned();
819+ let label = app.state.labels.get(&bssid).cloned();
820+ let (advice, actionable) = advisor(app, ap);
821+ let client_line = banner_client.map(|c| {
822+ let lbl = app
823+ .state
824+ .labels
825+ .get(&c)
826+ .map(|l| format!(" “{l}”"))
827+ .unwrap_or_default();
828+ text(format!("client: {c}{lbl}")).code().small().into_any_element()
829+ });
830+ v_stack()
831+ .gap_2()
832+ .p_3()
833+ .rounded_md()
834+ .border_1()
835+ .border_color(theme.border())
836+ .bg(theme.surface())
837+ .child(h3(format!(
838+ "target: {}{}",
839+ ap.ssid,
840+ label.map(|l| format!(" “{l}”")).unwrap_or_default()
841+ )))
842+ .child(small(format!(
843+ "{bssid} · ch {} ({} GHz) · vendor {}{}",
844+ ap.channel,
845+ crate::ui::networks::band(ap.channel),
846+ crate::ui::networks::vendor_of(&bssid),
847+ if stale { " · last scan snapshot" } else { "" }
848+ )))
849+ .child(
850+ v_stack()
851+ .gap_2()
852+ .child(
853+ h_stack()
854+ .gap_2()
855+ .items_center()
856+ .child(crate::ui::networks::sec_badge_label(
857+ &crate::ui::networks::sec_label(ap),
858+ ap.security,
859+ ))
860+ .children((!akm_join.is_empty()).then(|| small(akm_join)))
861+ .children((siblings > 1)
862+ .then(|| badge(format!("dual-band x{siblings}")).secondary())),
863+ )
864+ .child(
865+ h_stack()
866+ .gap_3()
867+ .items_center()
868+ .child(crate::ui::networks::sparkline(
869+ spark.as_ref(),
870+ theme.accent(),
871+ ))
872+ .child(small(format!(
873+ "{} dBm · {} beacons · seen {} ago",
874+ ap.rssi_dbm,
875+ ap.beacons,
876+ crate::ui::networks::age(ap.last_seen_ms)
877+ ))),
878+ )
879+ .child(small(format!(
880+ "material for this AP family: {hs_n} handshake(s) · {pm_n} PMKID(s)"
881+ )))
882+ .children(client_line)
883+ .child(
884+ div()
885+ .text_xs()
886+ .text_color(if actionable {
887+ theme.accent()
888+ } else {
889+ theme.warning()
890+ })
891+ .child(advice),
892+ ),
893+ )
894+ .into_any_element()
895+ }
393 None => h_stack()896 None => h_stack()
394 .gap_3()897 .gap_3()
395 .items_center()898 .items_center()
@@ -403,15 +906,25 @@ pub fn render(
403 // (a matching hint sits next to them).906 // (a matching hint sits next to them).
404 let not_running = !app.is_mock && !app.state.iface_running;907 let not_running = !app.is_mock && !app.state.iface_running;
405 let blocked = no_target || not_running;908 let blocked = no_target || not_running;
909+ // SAE-only: no offline attack applies (see sae_only).
910+ let sae = sae_only(app);
406 let hs_running = app.attacking_handshake;911 let hs_running = app.attacking_handshake;
407 let pm_running = app.attacking_pmkid;912 let pm_running = app.attacking_pmkid;
408 913
914+ // Bulk-deauth candidates: strictly-mapped connected clients of the
915+ // selected AP. Click-time count for the button label.
916+ let deauth_targets: usize = app
917+ .selected
918+ .map(|ap| connected_clients(app, ap).len())
919+ .unwrap_or(0);
920+ app.deauth_all_targets = deauth_targets;
921+
409 let actions = h_stack()922 let actions = h_stack()
410 .gap_3()923 .gap_3()
411 .items_center()924 .items_center()
412 .child(925 .child(
413 button("btn-handshake", "Capture Handshake")926 button("btn-handshake", "Capture Handshake")
414- .disabled(blocked || hs_running)927+ .disabled(blocked || hs_running || sae)
415 .on_click({928 .on_click({
416 let view = view.clone();929 let view = view.clone();
417 move |_, window, cx| capture_handshake(&view, window, cx)930 move |_, window, cx| capture_handshake(&view, window, cx)
@@ -419,21 +932,40 @@ pub fn render(
419 )932 )
420 .child(933 .child(
421 button("btn-pmkid", "PMKID Attack")934 button("btn-pmkid", "PMKID Attack")
422- .disabled(blocked || pm_running)935+ .disabled(blocked || pm_running || sae)
423 .on_click({936 .on_click({
424 let view = view.clone();937 let view = view.clone();
425 move |_, window, cx| pmkid_attack(&view, window, cx)938 move |_, window, cx| pmkid_attack(&view, window, cx)
426 }),939 }),
427 )940 )
428 .child(941 .child(
429- button("btn-deauth", "Deauth")942+ button(
430- .destructive()943+ "btn-deauth",
431- .disabled(blocked)944+ if banner_client.is_some() {
432- .on_click({945+ "Deauth client"
433- let view = view.clone();946+ } else {
434- move |_, window, cx| deauth(&view, window, cx)947+ "Deauth all"
435- }),948+ },
949+ )
950+ .destructive()
951+ .disabled(blocked || sae)
952+ .on_click({
953+ let view = view.clone();
954+ move |_, window, cx| deauth(&view, window, cx)
955+ }),
436 )956 )
957+ .children((deauth_targets >= 2).then(|| {
958+ button(
959+ "btn-deauth-all",
960+ format!("Deauth all clients ({deauth_targets})"),
961+ )
962+ .destructive()
963+ .disabled(blocked || sae)
964+ .on_click({
965+ let view = view.clone();
966+ move |_, _window, cx| deauth_all(&view, cx)
967+ })
968+ }))
437 .child(969 .child(
438 div()970 div()
439 .w(px(90.))971 .w(px(90.))
@@ -464,13 +996,174 @@ pub fn render(
464 })996 })
465 .collect();997 .collect();
466 998
999+ // Stations of the target: deauth a client directly (forces its
1000+ // re-auth → its 4-way handshake) without touching anything else.
1001+ let stations: Vec<&ClientInfo> = app
1002+ .selected
1003+ .map(|sel| {
1004+ app.state
1005+ .clients
1006+ .values()
1007+ .filter(|c| client_on_target(app, &c.mac, sel) && !c.mac.is_broadcast())
1008+ .collect()
1009+ })
1010+ .unwrap_or_default();
1011+
1012+ let stations_block = app.selected.map(|_sel| {
1013+ let rows: Vec<gpui::AnyElement> = stations
1014+ .iter()
1015+ .map(|cl| {
1016+ let mac = cl.mac;
1017+ let ap_of = cl.ap;
1018+ let view = view.clone();
1019+ // MAC-randomization pairing chip: live row's own fields,
1020+ // overlaid by the pairing record (wire fields can lag).
1021+ let ident = app
1022+ .state
1023+ .idents
1024+ .get(&mac)
1025+ .copied()
1026+ .or(cl.ident_group.zip(cl.ident_conf));
1027+ h_stack()
1028+ .w_full()
1029+ .gap_3()
1030+ .items_center()
1031+ .px_2()
1032+ .py_1()
1033+ .child(
1034+ v_stack()
1035+ .w(px(170.))
1036+ .child(text(mac.to_string()).code().small().into_any_element())
1037+ .child(
1038+ div()
1039+ .text_xs()
1040+ .text_color(theme.fg_muted())
1041+ .child(crate::ui::networks::vendor_of(&mac)),
1042+ ),
1043+ )
1044+ .children(
1045+ app.state
1046+ .labels
1047+ .get(&mac)
1048+ .map(|l| small(format!("“{l}”"))),
1049+ )
1050+ .children(ident.and_then(|(gid, conf)| {
1051+ let n = app
1052+ .state
1053+ .ident_groups
1054+ .get(&gid)
1055+ .map_or(1, |ms| ms.len());
1056+ let mut el = div()
1057+ .w(px(90.))
1058+ .text_xs()
1059+ .child(format!("#{gid}{} ({n})", conf.label()));
1060+ if n > 1 {
1061+ el = el.text_color(theme.accent());
1062+ } else {
1063+ el = el.text_color(theme.fg_muted());
1064+ }
1065+ Some(el)
1066+ }))
1067+ .child(
1068+ div()
1069+ .w(px(70.))
1070+ .text_xs()
1071+ .child(format!("{} dBm", cl.rssi_dbm)),
1072+ )
1073+ .child(div().w(px(60.)).text_xs().child(format!(
1074+ "{} fr",
1075+ cl.frames
1076+ )))
1077+ .child(
1078+ div()
1079+ .w(px(50.))
1080+ .text_xs()
1081+ .child(crate::ui::networks::age(cl.last_seen_ms)),
1082+ )
1083+ .children((ap_of.is_none())
1084+ .then(|| small("AP unmapped — treating as target's station")))
1085+ .child(div().flex_1())
1086+ .child(
1087+ button(
1088+ gpui::SharedString::from(format!("deauth-sta-{mac}")),
1089+ "Deauth client",
1090+ )
1091+ .destructive()
1092+ .disabled(!app.is_mock && !app.state.iface_running)
1093+ .on_click(move |_, _window, cx| deauth_station(&view, mac, cx)),
1094+ )
1095+ .into_any_element()
1096+ })
1097+ .collect();
1098+
1099+ let body = if rows.is_empty() {
1100+ div().child(small(
1101+ "no stations seen on this AP yet — click any client row on the Networks page \
1102+ to target it here anyway",
1103+ ))
1104+ .into_any_element()
1105+ } else {
1106+ v_stack().gap_1().children(rows).into_any_element()
1107+ };
1108+
1109+ v_stack()
1110+ .gap_2()
1111+ .child(
1112+ h_stack()
1113+ .items_center()
1114+ .gap_3()
1115+ .child(h3("Stations"))
1116+ .child(small(format!(
1117+ "{} — deauth one to force its handshake while capture runs",
1118+ stations.len()
1119+ ))),
1120+ )
1121+ .child(body)
1122+ .into_any_element()
1123+ });
1124+
1125+ // Recent attack-relevant activity, so every button press leaves a
1126+ // visible trace on THIS page (the full history lives on the Log page).
1127+ const ACTIVITY_LINES: usize = 8;
1128+ let activity: Vec<String> = app
1129+ .state
1130+ .log
1131+ .iter()
1132+ .filter(|line| {
1133+ [
1134+ "deauth", "handshake", "pmkid", "4-way", "scanner parked", "ERROR", "PASSWORD",
1135+ "target selected", "client selected",
1136+ ]
1137+ .iter()
1138+ .any(|p| line.starts_with(p))
1139+ })
1140+ .rev()
1141+ .take(ACTIVITY_LINES)
1142+ .cloned()
1143+ .collect::<Vec<_>>()
1144+ .into_iter()
1145+ .rev()
1146+ .collect();
1147+
467 let mut page = v_stack()1148 let mut page = v_stack()
468 .size_full()1149 .size_full()
469 .gap_3()1150 .gap_3()
470 .p_4()1151 .p_4()
471 .child(target_block)1152 .child(target_block)
1153+ .when(sae, |el| {
1154+ el.child(
1155+ div()
1156+ .text_xs()
1157+ .text_color(theme.warning())
1158+ .child(
1159+ "SAE-only AP — no offline-crackable handshake or PMKID \
1160+ (WPA3 transition APs with PSK AKM are fine)",
1161+ ),
1162+ )
1163+ })
472 .child(actions)1164 .child(actions)
473 .children(progress_cards)1165 .children(progress_cards)
1166+ .children(stations_block)
474 .child(gpuikit::elements::separator::separator())1167 .child(gpuikit::elements::separator::separator())
475 .child(1168 .child(
476 h_stack()1169 h_stack()
@@ -483,6 +1176,12 @@ pub fn render(
483 app.state.pmkids.len()1176 app.state.pmkids.len()
484 )))1177 )))
485 .child(div().flex_1())1178 .child(div().flex_1())
1179+ .child(
1180+ button("btn-export-pcap", "Export .pcap").on_click({
1181+ let view = view.clone();
1182+ move |_, window, cx| export_pcap(&view, window, cx)
1183+ }),
1184+ )
486 .child(1185 .child(
487 button("btn-export", "Export .hc22000").on_click({1186 button("btn-export", "Export .hc22000").on_click({
488 let view = view.clone();1187 let view = view.clone();
@@ -504,5 +1203,26 @@ pub fn render(
504 page = page.child(v_stack().gap_2().children(cards));1203 page = page.child(v_stack().gap_2().children(cards));
505 }1204 }
506 1205
1206+ page = page
1207+ .child(gpuikit::elements::separator::separator())
1208+ .child(h3("Activity")).child(if activity.is_empty() {
1209+ small("nothing yet — attack output appears here (full history on the Log page)")
1210+ .into_any_element()
1211+ } else {
1212+ v_stack()
1213+ .gap_1()
1214+ .p_2()
1215+ .rounded_md()
1216+ .bg(theme.surface())
1217+ .children(activity.iter().map(|line| {
1218+ div()
1219+ .text_xs()
1220+ .text_color(theme.fg_muted())
1221+ .child(line.clone())
1222+ .into_any_element()
1223+ }))
1224+ .into_any_element()
1225+ });
1226+
507 page.text_color(theme.fg())1227 page.text_color(theme.fg())
508 }1228 }
src/ui/cracker.rsmodified+1291 -84
@@ -1,13 +1,22 @@
1-//! Cracker page: target dropdown (fed by captures), wordlist field, backend1+//! Cracker page: target dropdown (fed by captures), attack-mode select
2-//! label, Start/Stop, live throughput/progress, found-password banner.2+//! (wordlist / bruteforce / rainbow PMK table) with per-mode inputs,
3+//! backend label, Start/Stop, live throughput/progress, rainbow-table
4+//! build controls, recent-activity log, found-password banner.
3 //!5 //!
4-//! Until the real wgpu cracker lands, Start runs a deterministic simulation6+//! Cracking is a plain UI-process job ([`crate::attack`]): it does NOT
5-//! on a gpui background task so every control here is live.7+//! need the privileged radio service and is completely independent of
8+//! capture state — a run may be started while a capture is live.
9+//! In mock mode Start runs a deterministic simulation on a gpui
10+//! background task instead (same event sequence; the attack mode is
11+//! ignored there).
6 12
13+use std::path::PathBuf;
14+use std::sync::atomic::Ordering;
7 use std::time::Duration;15 use std::time::Duration;
8 16
9 use gpui::{17 use gpui::{
10- Context, Entity, IntoElement, ParentElement, Styled, Window, div, prelude::FluentBuilder, px,18+ Context, Entity, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement,
19+ Styled, Window, div, prelude::FluentBuilder, px,
11 };20 };
12 use gpuikit::elements::button::button;21 use gpuikit::elements::button::button;
13 use gpuikit::elements::loading_indicator::loading_indicator;22 use gpuikit::elements::loading_indicator::loading_indicator;
@@ -17,6 +26,7 @@ use gpuikit::elements::typography::{h3, small, text};
17 use gpuikit::layout::{h_stack, v_stack};26 use gpuikit::layout::{h_stack, v_stack};
18 use gpuikit::theme::{ActiveTheme, Themeable};27 use gpuikit::theme::{ActiveTheme, Themeable};
19 28
29+use crate::attack::Attack;
20 use crate::common::Event;30 use crate::common::Event;
21 use crate::ui::app::AppRoot;31 use crate::ui::app::AppRoot;
22 32
@@ -31,7 +41,7 @@ const fn backend_label(is_mock: bool) -> &'static str {
31 if is_mock {41 if is_mock {
32 "GPU (wgpu) · mock"42 "GPU (wgpu) · mock"
33 } else {43 } else {
34- "auto: GPU (wgpu) → CPU"44+ "GPU (wgpu) → CPU"
35 }45 }
36 }46 }
37 47
@@ -45,16 +55,180 @@ fn fmt_hps(hps: f64) -> String {
45 }55 }
46 }56 }
47 57
58+/// Human duration for worst-case ETAs ("3d 4h", "2h 05m", "3m 12s", "12s").
59+fn fmt_dur(secs: f64) -> String {
60+ if !secs.is_finite() || secs < 1.0 {
61+ return "<1s".to_string();
62+ }
63+ let s = secs.round() as u64;
64+ let (d, h, m, sec) = (s / 86400, s / 3600 % 24, s / 60 % 60, s % 60);
65+ if d > 0 {
66+ format!("{d}d {h}h")
67+ } else if h > 0 {
68+ format!("{h}h {m:02}m")
69+ } else if m > 0 {
70+ format!("{m}m {sec:02}s")
71+ } else {
72+ format!("{sec}s")
73+ }
74+}
75+
76+/// Worst-case remaining time: every not-yet-tried candidate at the
77+/// current rate. Empty when the total or the rate is unknown.
78+fn fmt_worst_case(done: u64, hps: f64, total: Option<u64>) -> Option<String> {
79+ let t = total?;
80+ if hps <= 0.0 || done >= t {
81+ return None;
82+ }
83+ Some(format!("worst case left: ~{}", fmt_dur((t - done) as f64 / hps)))
84+}
85+
86+/// Build the [`Attack`] selected by `app.attack_mode` from the page's
87+/// input fields. Returns `None` (after logging the reason) when an input
88+/// is empty or fails to parse.
89+fn selected_attack(app: &mut AppRoot, cx: &mut gpui::App) -> Option<Attack> {
90+ match app.attack_mode.as_str() {
91+ "bruteforce" => {
92+ let custom = app
93+ .charset_input
94+ .read(cx)
95+ .content()
96+ .trim_end_matches(['\r', '\n'])
97+ .as_bytes()
98+ .to_vec();
99+ // Union of the checked preset chips + the custom field.
100+ let charset = crate::attack::charset::compose(
101+ app.cs_lower,
102+ app.cs_upper,
103+ app.cs_digits,
104+ app.cs_special,
105+ &custom,
106+ );
107+ if charset.is_empty() {
108+ app.state.push_log(
109+ "cracker: empty charset — pick a preset chip or type custom chars",
110+ );
111+ return None;
112+ }
113+ let min_s = app.len_min_input.read(cx).content().trim().to_string();
114+ let max_s = app.len_max_input.read(cx).content().trim().to_string();
115+ let min = match min_s.parse::<usize>() {
116+ Ok(v) => v,
117+ Err(_) => {
118+ app.state.push_log(format!("cracker: bad min length '{min_s}'"));
119+ return None;
120+ }
121+ };
122+ let max = match max_s.parse::<usize>() {
123+ Ok(v) => v,
124+ Err(_) => {
125+ app.state.push_log(format!("cracker: bad max length '{max_s}'"));
126+ return None;
127+ }
128+ };
129+ Some(Attack::Bruteforce { charset, min, max, freq_order: app.freq_order })
130+ }
131+ "rules" => {
132+ let wl = app.wordlist_input.read(cx).content().trim().to_string();
133+ if wl.is_empty() {
134+ app.state.push_log("cracker: wordlist path is empty");
135+ return None;
136+ }
137+ let rules = app.rules_input.read(cx).content().trim().to_string();
138+ if rules.is_empty() {
139+ app.state.push_log("cracker: rules path is empty");
140+ return None;
141+ }
142+ Some(Attack::Rules {
143+ wordlist: PathBuf::from(wl),
144+ rules: PathBuf::from(rules),
145+ })
146+ }
147+ "hybrid" => {
148+ let wl = app.wordlist_input.read(cx).content().trim().to_string();
149+ if wl.is_empty() {
150+ app.state.push_log("cracker: wordlist path is empty");
151+ return None;
152+ }
153+ let custom = app
154+ .charset_input
155+ .read(cx)
156+ .content()
157+ .trim_end_matches(['\r', '\n'])
158+ .as_bytes()
159+ .to_vec();
160+ let charset = crate::attack::charset::compose(
161+ app.cs_lower,
162+ app.cs_upper,
163+ app.cs_digits,
164+ app.cs_special,
165+ &custom,
166+ );
167+ if charset.is_empty() {
168+ app.state.push_log(
169+ "cracker: empty charset — pick a preset chip or type custom chars",
170+ );
171+ return None;
172+ }
173+ let min_s = app.hyb_min_input.read(cx).content().trim().to_string();
174+ let max_s = app.hyb_max_input.read(cx).content().trim().to_string();
175+ let min = match min_s.parse::<usize>() {
176+ Ok(v) => v.clamp(1, 4),
177+ Err(_) => {
178+ app.state.push_log(format!("cracker: bad hybrid min '{min_s}'"));
179+ return None;
180+ }
181+ };
182+ let max = match max_s.parse::<usize>() {
183+ Ok(v) => v.clamp(1, 4),
184+ Err(_) => {
185+ app.state.push_log(format!("cracker: bad hybrid max '{max_s}'"));
186+ return None;
187+ }
188+ };
189+ if min > max {
190+ app.state
191+ .push_log(format!("cracker: hybrid min {min} > max {max}"));
192+ return None;
193+ }
194+ Some(Attack::Hybrid {
195+ wordlist: PathBuf::from(wl),
196+ charset,
197+ min,
198+ max,
199+ })
200+ }
201+ "rainbow" => {
202+ let path = app.rainbow_input.read(cx).content().trim().to_string();
203+ if path.is_empty() {
204+ app.state.push_log("cracker: PMK table path is empty");
205+ return None;
206+ }
207+ Some(Attack::Rainbow(PathBuf::from(path)))
208+ }
209+ _ => {
210+ let path = app.wordlist_input.read(cx).content().trim().to_string();
211+ if path.is_empty() {
212+ app.state.push_log("cracker: wordlist path is empty");
213+ return None;
214+ }
215+ Some(Attack::Wordlist(PathBuf::from(path)))
216+ }
217+ }
218+}
219+
48 /// Start a crack run on the selected capture.220 /// Start a crack run on the selected capture.
49 ///221 ///
50-/// Real mode: hands the stored [`crate::crypto::CrackTarget`] (no hc22000222+/// Real mode: builds the selected [`Attack`], validates it (files
51-/// re-parse) to the backend worker; progress and termination arrive as223+/// opened, charset/lengths checked) BEFORE any flag is set, then hands
224+/// the stored [`crate::crypto::CrackTarget`] (no hc22000 re-parse) to
225+/// `crate::attack::spawn_crack`; progress and termination arrive as
52 /// CrackProgress/CrackFound/CrackStopped events and land in state via226 /// CrackProgress/CrackFound/CrackStopped events and land in state via
53-/// `AppState::apply`. Requires capture stopped (radio exclusive).227+/// `AppState::apply`. No radio or service involvement.
54 /// Mock mode: a deterministic generator drives the SAME event sequence.228 /// Mock mode: a deterministic generator drives the SAME event sequence.
55 fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {229 fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
56 view.update(cx, |app, cx| {230 view.update(cx, |app, cx| {
57- if app.crack_inflight || app.state.cracker.running {231+ if app.crack_inflight || app.state.cracker.running || app.bench_running {
58 return;232 return;
59 }233 }
60 let Some(desc) = app.state.cracker.target.clone() else {234 let Some(desc) = app.state.cracker.target.clone() else {
@@ -62,19 +236,16 @@ fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
62 cx.notify();236 cx.notify();
63 return;237 return;
64 };238 };
65- let wordlist = app.wordlist_input.read(cx).content().trim().to_string();
66- if wordlist.is_empty() {
67- app.state.push_log("cracker: wordlist path is empty");
68- cx.notify();
69- return;
70- }
71 239
72 // Validate everything that can fail BEFORE marking the run active,240 // Validate everything that can fail BEFORE marking the run active,
73 // so a refused start never leaves stale flags behind.241 // so a refused start never leaves stale flags behind.
74- let real_target = if !app.is_mock {242+ let real = if !app.is_mock {
75- if app.state.iface_running {243+ let Some(attack) = selected_attack(app, cx) else {
76- app.state244+ cx.notify();
77- .push_log("cracker: needs the radio free — stop capture first");245+ return;
246+ };
247+ if let Err(e) = attack.validate() {
248+ app.state.push_log(format!("ERROR: cracker: {e:#}"));
78 cx.notify();249 cx.notify();
79 return;250 return;
80 }251 }
@@ -84,7 +255,7 @@ fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
84 return;255 return;
85 };256 };
86 match app.state.crack_target_at(idx) {257 match app.state.crack_target_at(idx) {
87- Some(t) => Some(t),258+ Some(t) => Some((t, attack)),
88 None => {259 None => {
89 app.state.push_log("ERROR: cracker: capture no longer exists");260 app.state.push_log("ERROR: cracker: capture no longer exists");
90 cx.notify();261 cx.notify();
@@ -96,36 +267,54 @@ fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
96 };267 };
97 268
98 app.crack_epoch += 1; // invalidate any stale mock generator ticks269 app.crack_epoch += 1; // invalidate any stale mock generator ticks
270+ let wordlist = app.wordlist_input.read(cx).content().trim().to_string();
99 let cr = &mut app.state.cracker;271 let cr = &mut app.state.cracker;
100 cr.wordlist = Some(wordlist.clone());272 cr.wordlist = Some(wordlist.clone());
101 cr.found = None;273 cr.found = None;
102 cr.tried = 0;274 cr.tried = 0;
103 cr.hps = 0.0;275 cr.hps = 0.0;
276+ cr.total = None;
277+ // A fresh foreground start supersedes any saved resume position.
278+ cr.resume = None;
104 cr.running = true;279 cr.running = true;
105 app.crack_inflight = true;280 app.crack_inflight = true;
281+ // Fresh run: the throughput curve belongs to it, not the last run.
282+ app.state.hps_hist.clear();
106 cx.notify();283 cx.notify();
107 284
108 if !app.is_mock {285 if !app.is_mock {
109- let Some(target) = real_target else { return };286+ let Some((target, attack)) = real else { return };
110 app.state.push_log(format!(287 app.state.push_log(format!(
111- "cracker: starting on {desc} via {wordlist} [auto backend]"288+ "cracker: starting on {desc} — {}",
289+ attack.describe()
112 ));290 ));
113- cx.notify();291+ // Remember the wordlist path in the MRU list (wordlist-family
114- match &app.service {292+ // attacks only) so it shows up as a one-click chip later.
115- Some(svc) => svc.spawn_crack(293+ let wl_path: Option<String> = match &attack {
116- target.describe(),294+ Attack::Wordlist(p) => Some(p.display().to_string()),
117- target,295+ Attack::Rules { wordlist, .. } | Attack::Hybrid { wordlist, .. } => {
118- std::path::PathBuf::from(&wordlist),296+ Some(wordlist.display().to_string())
119- app.tx.clone(),297+ }
120- ),298+ _ => None,
121- None => {299+ };
122- app.state.cracker.running = false;300+ if let Some(wl_path) = wl_path {
123- app.crack_inflight = false;301+ crate::store::remember_wordlist(&mut app.profiles, &wl_path);
124- app.state302+ if let Err(e) = crate::store::save_profiles(&app.profiles) {
125- .push_log("ERROR: cracker: no service (start capture first, then stop it)");303+ app.state.push_log(format!("profiles: save FAILED: {e:#}"));
126- cx.notify();
127 }304 }
128 }305 }
306+ // Track the live attack for the resume session file
307+ // (throttle-saved on progress, finalized on stop).
308+ app.state.cracker.active_attack = Some(attack.clone());
309+ cx.notify();
310+ app.crack_stop = Some(crate::attack::spawn_crack(
311+ target.describe(),
312+ target,
313+ attack,
314+ 0,
315+ app.tx.clone(),
316+ false,
317+ ));
129 return;318 return;
130 }319 }
131 320
@@ -152,7 +341,11 @@ fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
152 }341 }
153 done += (MOCK_HPS / 10.0) as u64 + done / 977 % 8_000;342 done += (MOCK_HPS / 10.0) as u64 + done / 977 % 8_000;
154 let hps = MOCK_HPS * (0.92 + (done / 331 % 15) as f64 / 100.0);343 let hps = MOCK_HPS * (0.92 + (done / 331 % 15) as f64 / 100.0);
155- let _ = tx.send(Event::CrackProgress { done, hps });344+ let _ = tx.send(Event::CrackProgress {
345+ done,
346+ hps,
347+ total: Some(WORDLIST_TOTAL),
348+ });
156 if done >= WORDLIST_TOTAL {349 if done >= WORDLIST_TOTAL {
157 let _ = tx.send(Event::CrackFound {350 let _ = tx.send(Event::CrackFound {
158 password: MOCK_PASSWORD.to_string(),351 password: MOCK_PASSWORD.to_string(),
@@ -168,10 +361,11 @@ fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
168 361
169 /// Stop the active run.362 /// Stop the active run.
170 ///363 ///
171-/// Real mode flips the crack job's stop flag (the wordlist streamer breaks364+/// Real mode flips the crack job's stop flag (the worker breaks at the
172-/// at the next batch and emits CrackStopped{found:false}, which settles365+/// next batch and emits CrackStopped{found:false}, which settles the UI
173-/// the UI). Mock mode just invalidates the generator epoch — no terminator366+/// and clears `app.crack_stop`). Mock mode just invalidates the
174-/// event will arrive, so the running flags are cleared here.367+/// generator epoch — no terminator event will arrive, so the running
368+/// flags are cleared here.
175 fn stop(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {369 fn stop(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
176 view.update(cx, |app, cx| {370 view.update(cx, |app, cx| {
177 let active = app.crack_inflight || app.state.cracker.running;371 let active = app.crack_inflight || app.state.cracker.running;
@@ -187,18 +381,615 @@ fn stop(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
187 cx.notify();381 cx.notify();
188 return;382 return;
189 }383 }
190- if let Some(svc) = &app.service {384+ if let Some(flag) = &app.crack_stop {
191- svc.request_crack_stop();385+ flag.store(true, Ordering::Relaxed);
192 app.state.push_log("cracker: stop requested");386 app.state.push_log("cracker: stop requested");
387+ }
388+ cx.notify();
389+ });
390+}
391+
392+/// Start a rainbow PMK-table build for the selected capture's SSID.
393+///
394+/// Validates both paths (wordlist must open, table path must be given)
395+/// BEFORE marking the build active; progress arrives as
396+/// RainbowProgress, termination as RainbowBuilt — the latter settles
397+/// `rainbow_building` and `app.rainbow_stop`.
398+fn build(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
399+ view.update(cx, |app, cx| {
400+ if app.state.cracker.rainbow_building
401+ || app.crack_inflight
402+ || app.state.cracker.running
403+ || app.bench_running
404+ {
405+ return;
406+ }
407+ let Some(desc) = app.state.cracker.target.clone() else {
408+ app.state.push_log("rainbow: no target selected");
409+ cx.notify();
410+ return;
411+ };
412+ let Some(idx) = app.state.capture_descs().iter().position(|d| *d == desc) else {
413+ app.state.push_log("ERROR: rainbow: capture no longer exists");
414+ cx.notify();
415+ return;
416+ };
417+ let Some(target) = app.state.crack_target_at(idx) else {
418+ app.state.push_log("ERROR: rainbow: capture no longer exists");
419+ cx.notify();
420+ return;
421+ };
422+ let ssid = target.essid().to_string();
423+
424+ let wl = app.wordlist_input.read(cx).content().trim().to_string();
425+ if wl.is_empty() {
426+ app.state.push_log("rainbow: wordlist path is empty");
427+ cx.notify();
428+ return;
429+ }
430+ if let Err(e) = std::fs::File::open(&wl) {
431+ app.state
432+ .push_log(format!("ERROR: rainbow: cannot open wordlist {wl}: {e}"));
433+ cx.notify();
434+ return;
435+ }
436+ let out = app.rainbow_input.read(cx).content().trim().to_string();
437+ if out.is_empty() {
438+ app.state.push_log("rainbow: PMK table path is empty");
439+ cx.notify();
440+ return;
441+ }
442+
443+ app.state.cracker.rainbow_building = true;
444+ app.state.cracker.rainbow_done = 0;
445+ app.state.cracker.rainbow_hps = 0.0;
446+ app.state.cracker.rainbow_total = None;
447+ app.state.push_log(format!(
448+ "rainbow: building table {out} for ssid \"{ssid}\" from {wl}"
449+ ));
450+ cx.notify();
451+ app.rainbow_stop = Some(crate::attack::spawn_rainbow_build(
452+ ssid,
453+ PathBuf::from(wl),
454+ PathBuf::from(out),
455+ app.tx.clone(),
456+ ));
457+ });
458+}
459+
460+/// Stop the running rainbow-table build: flip the job's stop flag; the
461+/// terminating RainbowBuilt event settles the UI.
462+fn build_stop(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
463+ view.update(cx, |app, cx| {
464+ if let Some(flag) = &app.rainbow_stop {
465+ flag.store(true, Ordering::Relaxed);
466+ app.state.push_log("rainbow: stop requested");
467+ cx.notify();
468+ }
469+ });
470+}
471+
472+/// Resume the saved run shown in the banner: same capture, same attack,
473+/// continuing at the saved candidate offset.
474+fn resume_saved(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
475+ view.update(cx, |app, cx| {
476+ if app.crack_inflight
477+ || app.state.cracker.running
478+ || app.state.cracker.rainbow_building
479+ || app.bench_running
480+ {
481+ return;
482+ }
483+ let Some(r) = app.state.cracker.resume.clone() else {
484+ return;
485+ };
486+ // Files may have vanished since the run was saved — refuse with a
487+ // visible reason, keep the session file + banner untouched.
488+ if let Err(e) = r.attack.validate() {
489+ app.state
490+ .push_log(format!("ERROR: cracker: saved run no longer valid: {e:#}"));
491+ cx.notify();
492+ return;
493+ }
494+ let Some(idx) = app
495+ .state
496+ .capture_descs()
497+ .iter()
498+ .position(|d| *d == r.target_desc)
499+ else {
500+ app.state
501+ .push_log("ERROR: cracker: saved run's capture no longer exists");
502+ cx.notify();
503+ return;
504+ };
505+ let Some(target) = app.state.crack_target_at(idx) else {
506+ app.state
507+ .push_log("ERROR: cracker: saved run's capture no longer exists");
508+ cx.notify();
509+ return;
510+ };
511+
512+ app.crack_epoch += 1;
513+ let cr = &mut app.state.cracker;
514+ cr.found = None;
515+ cr.tried = r.done;
516+ cr.hps = 0.0;
517+ cr.total = r.total;
518+ cr.active_attack = Some(r.attack.clone());
519+ cr.resume = None;
520+ cr.running = true;
521+ app.crack_inflight = true;
522+ app.state.hps_hist.clear();
523+ // The new run's throttle-saves supersede the old session file;
524+ // clear eagerly so a crash cannot doubly arm the banner.
525+ if let Err(e) = crate::store::clear_session() {
526+ app.state
527+ .push_log(format!("cracker: session clear failed: {e:#}"));
528+ }
529+ app.state.push_log(format!(
530+ "cracker: resuming saved run — {} at {}{}",
531+ r.attack.describe(),
532+ r.done,
533+ r.total.map(|t| format!("/{t}")).unwrap_or_default()
534+ ));
535+ cx.notify();
536+ app.crack_stop = Some(crate::attack::spawn_crack(
537+ target.describe(),
538+ target,
539+ r.attack,
540+ r.done,
541+ app.tx.clone(),
542+ false,
543+ ));
544+ });
545+}
546+
547+/// Delete the saved session file and dismiss the banner.
548+fn discard_saved(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
549+ view.update(cx, |app, cx| {
550+ if let Err(e) = crate::store::clear_session() {
551+ app.state
552+ .push_log(format!("cracker: session clear failed: {e:#}"));
553+ }
554+ app.state.cracker.resume = None;
555+ app.state.push_log("cracker: saved run discarded");
556+ cx.notify();
557+ });
558+}
559+
560+/// Save the current mode + paths as a named preset in `app.profiles`
561+/// (name auto-derived as `{mode}:{basename(wordlist)}`; a same-name
562+/// preset is replaced). Persisted via [`crate::store::save_profiles`].
563+fn save_preset(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
564+ view.update(cx, |app, cx| {
565+ let mode = app.attack_mode.clone();
566+ if mode == "rainbow" {
567+ app.state.push_log("profiles: rainbow presets are not saved");
568+ cx.notify();
569+ return;
570+ }
571+ let wordlist = app.wordlist_input.read(cx).content().trim().to_string();
572+ if wordlist.is_empty() {
573+ app.state.push_log("profiles: wordlist path is empty — nothing to save");
574+ cx.notify();
575+ return;
576+ }
577+ let rules = match mode.as_str() {
578+ "rules" => {
579+ let r = app.rules_input.read(cx).content().trim().to_string();
580+ if r.is_empty() {
581+ app.state.push_log("profiles: rules path is empty — nothing to save");
582+ cx.notify();
583+ return;
584+ }
585+ Some(r)
586+ }
587+ _ => None,
588+ };
589+ let base = std::path::Path::new(&wordlist)
590+ .file_name()
591+ .map(|n| n.to_string_lossy().into_owned())
592+ .unwrap_or_else(|| wordlist.clone());
593+ let name = format!("{mode}:{base}");
594+ let profile = crate::store::CrackProfile {
595+ name: name.clone(),
596+ mode,
597+ wordlist,
598+ rules,
599+ };
600+ app.profiles.profiles.retain(|p| p.name != name);
601+ app.profiles.profiles.push(profile);
602+ match crate::store::save_profiles(&app.profiles) {
603+ Ok(()) => app.state.push_log(format!("profiles: saved preset {name}")),
604+ Err(e) => app.state.push_log(format!("profiles: save FAILED: {e:#}")),
605+ }
606+ cx.notify();
607+ });
608+}
609+
610+/// Apply a saved preset: switch the attack mode and prefill the
611+/// wordlist/rules input fields.
612+fn apply_preset(profile: crate::store::CrackProfile, view: &Entity<AppRoot>, cx: &mut gpui::App) {
613+ view.update(cx, |app, cx| {
614+ app.attack_mode = profile.mode.clone();
615+ app.attack_select.update(cx, |sel, cx| {
616+ sel.set_selected(Some(profile.mode.clone()), cx);
617+ });
618+ let wl = profile.wordlist.clone();
619+ app.wordlist_input.update(cx, |input, cx| {
620+ input.set_content(wl, cx);
621+ });
622+ if let Some(rules) = &profile.rules {
623+ let r = rules.clone();
624+ app.rules_input.update(cx, |input, cx| {
625+ input.set_content(r, cx);
626+ });
627+ }
628+ app.state
629+ .push_log(format!("profiles: applied preset {}", profile.name));
630+ cx.notify();
631+ });
632+}
633+
634+/// Import captures from .cap/.pcap files (via [`crate::pcapin::extract`])
635+/// or .hc22000 text files (via [`crate::crypto::parse_hc22000`]). Each
636+/// extracted capture arrives as a CaptureImported event; the heavy parse
637+/// runs on a worker thread streaming events like the crack threads do.
638+/// `import_busy` is cleared at the very end, after all chosen files.
639+fn import_captures(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
640+ let prompt = cx.prompt_for_paths(gpui::PathPromptOptions {
641+ files: true,
642+ directories: false,
643+ multiple: true,
644+ prompt: None,
645+ });
646+ view.update(cx, |app, cx| {
647+ app.import_busy = true;
648+ cx.notify();
649+ });
650+ let weak = view.downgrade();
651+ cx.spawn(async move |cx| {
652+ // oneshot recv err OR platform dialog err OR explicit cancel all
653+ // land here as "no file chosen".
654+ let picked: Option<Vec<PathBuf>> = match prompt.await {
655+ Ok(Ok(paths)) => paths,
656+ _ => None,
657+ };
658+ let Some(paths) = picked else {
659+ let _ = weak.update(cx, |app, cx| {
660+ app.import_busy = false;
661+ app.state.push_log("import: no file chosen");
662+ cx.notify();
663+ });
664+ return;
665+ };
666+ // Heavy parsing (multi-GB pcaps) must not block the UI executor:
667+ // stream results from a plain thread like the crack workers do.
668+ let tx = match weak.update(cx, |app, _cx| app.tx.clone()) {
669+ Ok(tx) => tx,
670+ Err(_) => return, // view gone — nothing to report to
671+ };
672+ // At the very end (after all files) the worker signals completion
673+ // on this channel; the gpui continuation below clears import_busy
674+ // (a bare std thread cannot touch gpui state).
675+ let (done_tx, done_rx) = crossbeam_channel::bounded::<()>(1);
676+ std::thread::Builder::new()
677+ .name("wifilab-import".into())
678+ .spawn(move || {
679+ for path in paths {
680+ let disp = path.display().to_string();
681+ let is_hc22000 = disp.contains("22000")
682+ || std::fs::read_to_string(&path)
683+ .map(|s| {
684+ s.lines()
685+ .take(8)
686+ .any(|l| l.starts_with("WPA*01") || l.starts_with("WPA*02"))
687+ })
688+ .unwrap_or(false);
689+ if is_hc22000 {
690+ match std::fs::read_to_string(&path) {
691+ Ok(text) => {
692+ let mut n = 0usize;
693+ let mut m = 0usize;
694+ for line in text.lines() {
695+ let line = line.trim();
696+ if line.is_empty() {
697+ continue;
698+ }
699+ let bare = line.strip_prefix("WPA*").unwrap_or(line);
700+ match crate::crypto::parse_hc22000(bare) {
701+ Ok(crate::crypto::CrackTarget::Handshake(h)) => {
702+ let _ = tx.send(Event::CaptureImported(
703+ crate::common::ImportedCapture::Handshake(
704+ Box::new(h),
705+ ),
706+ ));
707+ n += 1;
708+ }
709+ Ok(crate::crypto::CrackTarget::Pmkid(p)) => {
710+ let _ = tx.send(Event::CaptureImported(
711+ crate::common::ImportedCapture::Pmkid(p),
712+ ));
713+ n += 1;
714+ }
715+ Err(_) => m += 1,
716+ }
717+ }
718+ let _ = tx.send(Event::Log(format!(
719+ "import: {disp}: {n} captures ({m} skipped)"
720+ )));
721+ }
722+ Err(e) => {
723+ let _ = tx.send(Event::Error(format!("import: {disp}: {e}")));
724+ }
725+ }
726+ } else {
727+ match crate::pcapin::extract(&path) {
728+ Ok(caps) => {
729+ let n = caps.len();
730+ for cap in caps {
731+ let _ = tx.send(Event::CaptureImported(cap));
732+ }
733+ let _ = tx.send(Event::Log(format!(
734+ "import: {disp}: {n} captures (0 skipped)"
735+ )));
736+ }
737+ Err(e) => {
738+ let _ = tx.send(Event::Error(format!("import: {disp}: {e:#}")));
739+ }
740+ }
741+ }
742+ }
743+ let _ = done_tx.send(());
744+ })
745+ .expect("spawn import thread");
746+ // Wait for completion on the background executor, then clear the
747+ // busy flag on the gpui side.
748+ let bg = cx.background_executor().clone();
749+ bg.spawn(async move {
750+ let _ = done_rx.recv();
751+ })
752+ .await;
753+ let _ = weak.update(cx, |app, cx| {
754+ app.import_busy = false;
755+ cx.notify();
756+ });
757+ })
758+ .detach();
759+}
760+
761+/// Run a 3 s H/s benchmark (GPU if available, CPU always). Results
762+/// arrive as one BenchmarkDone event; `bench_running` is cleared on the
763+/// app drain side. Mock mode fabricates a fixed result after ~1.5 s.
764+fn benchmark(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
765+ view.update(cx, |app, cx| {
766+ if app.bench_running
767+ || app.crack_inflight
768+ || app.state.cracker.running
769+ || app.state.cracker.rainbow_building
770+ {
771+ return;
772+ }
773+ app.bench_running = true;
774+ app.state.push_log("benchmark: measuring crack speed (3s)…");
775+ cx.notify();
776+ if !app.is_mock {
777+ // The worker holds its own Arc; the flag is never flipped by
778+ // the UI, so dropping our copy is safe.
779+ drop(crate::attack::spawn_benchmark(3, app.tx.clone()));
780+ return;
781+ }
782+ // Mock: fabricate a BenchmarkDone after ~1.5 s. No epoch
783+ // invalidation: bench_running already blocks a concurrent second
784+ // click, and a crack started meanwhile does not invalidate a
785+ // machine-speed measurement.
786+ let tx = app.tx.clone();
787+ cx.spawn(async move |this, cx| {
788+ cx.background_executor()
789+ .timer(Duration::from_millis(1500))
790+ .await;
791+ let live = this.update(cx, |app, _cx| app.bench_running).unwrap_or(false);
792+ if live {
793+ let _ = tx.send(Event::BenchmarkDone {
794+ gpu_hps: Some(MOCK_HPS),
795+ cpu_hps: 310_000.0,
796+ });
797+ }
798+ })
799+ .detach();
800+ });
801+}
802+
803+/// Estimate worst-case crack durations from the measured benchmark rate
804+/// and the current input fields; results go to the activity log as
805+/// "estimate:" lines (candidate-space math always, times only when a
806+/// benchmark has run).
807+fn estimate(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
808+ view.update(cx, |app, cx| {
809+ let hps = match (app.state.bench_gpu, app.state.bench_cpu) {
810+ (Some(g), Some(c)) => Some(g.max(c)),
811+ (Some(g), None) => Some(g),
812+ (None, Some(c)) => Some(c),
813+ (None, None) => None,
814+ };
815+ let Some(hps) = hps.filter(|h| *h > 0.0) else {
816+ app.state
817+ .push_log("estimate: run Benchmark for times; candidate-space math only");
818+ cx.notify();
819+ return;
820+ };
821+
822+ // (a) wordlist family: lines × rules (rules mode) at best rate.
823+ let wl = app.wordlist_input.read(cx).content().trim().to_string();
824+ let wl_space: Option<u128> = if wl.is_empty() {
825+ Some(WORDLIST_TOTAL as u128)
193 } else {826 } else {
194- app.state.cracker.running = false;827+ match crate::wordlist::line_count(std::path::Path::new(&wl)) {
195- app.crack_inflight = false;828+ Ok(n) => Some(n as u128),
196- app.state.push_log("cracker: stopped");829+ Err(e) => {
830+ app.state
831+ .push_log(format!("estimate: wordlist unreadable: {e:#}"));
832+ None
833+ }
834+ }
835+ };
836+ if let Some(mut space) = wl_space {
837+ let mut what = format!("wordlist {}", if wl.is_empty() { "(mock-size)" } else { &wl });
838+ if app.attack_mode == "rules" {
839+ let rp = app.rules_input.read(cx).content().trim().to_string();
840+ match crate::attack::rule_count(std::path::Path::new(&rp)) {
841+ Ok(r) if r > 0 => {
842+ space = space.saturating_mul(r as u128);
843+ what = format!("{what} × {r} rules");
844+ }
845+ Ok(_) => {}
846+ Err(e) => {
847+ app.state
848+ .push_log(format!("estimate: rules unreadable: {e:#}"));
849+ space = 0;
850+ }
851+ }
852+ }
853+ if space > 0 {
854+ app.state.push_log(format!(
855+ "estimate: {what}: {space} candidates, worst case ~{} @ {}",
856+ fmt_dur(space as f64 / hps),
857+ fmt_hps(hps)
858+ ));
859+ }
860+ }
861+
862+ // (b) bruteforce space at best rate.
863+ let custom = app
864+ .charset_input
865+ .read(cx)
866+ .content()
867+ .trim_end_matches(['\r', '\n'])
868+ .as_bytes()
869+ .to_vec();
870+ let charset = crate::attack::charset::compose(
871+ app.cs_lower,
872+ app.cs_upper,
873+ app.cs_digits,
874+ app.cs_special,
875+ &custom,
876+ );
877+ if charset.is_empty() {
878+ app.state.push_log("estimate: empty charset — bruteforce space n/a");
879+ } else {
880+ let min = app
881+ .len_min_input
882+ .read(cx)
883+ .content()
884+ .trim()
885+ .parse::<usize>()
886+ .unwrap_or(8);
887+ let max = app
888+ .len_max_input
889+ .read(cx)
890+ .content()
891+ .trim()
892+ .parse::<usize>()
893+ .unwrap_or(10);
894+ match crate::attack::BruteForce::new(charset.clone(), min, max, false) {
895+ Ok(bf) => {
896+ let space = bf.space();
897+ app.state.push_log(format!(
898+ "estimate: bruteforce {min}..={max}: {space} candidates, worst case ~{} @ {}",
899+ fmt_dur(space as f64 / hps),
900+ fmt_hps(hps)
901+ ));
902+ }
903+ Err(e) => app
904+ .state
905+ .push_log(format!("estimate: bruteforce range invalid: {e:#}")),
906+ }
907+ }
908+
909+ // (c) entropy of the strength-input candidate against the current
910+ // charset union: bits ≈ len × log2(charset size).
911+ let candidate = app.strength_input.read(cx).content().trim().to_string();
912+ if !candidate.is_empty() && !charset.is_empty() {
913+ let csize = charset.len() as f64;
914+ let bits = candidate.len() as f64 * csize.log2();
915+ let guess_s = 2f64.powf(bits - 1.0) / hps;
916+ app.state.push_log(format!(
917+ "estimate: {} chars × log2({}) ≈ {bits:.0} bits — avg crack ~{} @ {}",
918+ candidate.len(),
919+ charset.len(),
920+ fmt_dur(guess_s),
921+ fmt_hps(hps)
922+ ));
923+ } else if candidate.is_empty() {
924+ app.state.push_log("estimate: type a candidate for its entropy line");
197 }925 }
198 cx.notify();926 cx.notify();
199 });927 });
200 }928 }
201 929
930+/// One bruteforce charset preset chip. Toggling flips the app flag;
931+/// [`crate::attack::charset::compose`] unions the active chips with the
932+/// custom field at Start.
933+fn charset_chip(
934+ id: &'static str,
935+ label: &'static str,
936+ active: bool,
937+ view: &Entity<AppRoot>,
938+ cx: &gpui::App,
939+ flag: fn(&mut AppRoot) -> &mut bool,
940+) -> gpui::Stateful<gpui::Div> {
941+ let theme = cx.theme().clone();
942+ let hover = theme.accent_bg();
943+ div()
944+ .id(gpui::SharedString::from(id))
945+ .px_2()
946+ .py_1()
947+ .rounded_md()
948+ .border_1()
949+ .border_color(theme.border())
950+ .cursor_pointer()
951+ .text_xs()
952+ .when(active, |el| el.bg(theme.accent_bg()))
953+ .when(!active, |el| el.hover(move |style| style.bg(hover)))
954+ .child(label)
955+ .on_click({
956+ let view = view.clone();
957+ move |_, _window, cx| {
958+ view.update(cx, |app, cx| {
959+ let f = flag(app);
960+ *f = !*f;
961+ cx.notify();
962+ });
963+ }
964+ })
965+}
966+
967+/// Throughput curve of the current run: one bar per progress sample,
968+/// right-aligned (newest at the right edge), height scaled to the run's
969+/// own maximum so a CPU-scale run doesn't render as a flat line next to
970+/// GPU-scale history.
971+fn hps_curve(
972+ hist: &std::collections::VecDeque<f64>,
973+ accent: gpui::Hsla,
974+) -> Option<gpui::AnyElement> {
975+ if hist.len() < 2 {
976+ return None;
977+ }
978+ const COLUMNS: usize = 40;
979+ const MAX_H: f32 = 14.0;
980+ let max = hist.iter().copied().fold(0.0f64, f64::max).max(1.0);
981+ let mut cols: Vec<gpui::Div> = Vec::with_capacity(COLUMNS);
982+ let shown: Vec<f64> = hist.iter().copied().rev().take(COLUMNS).collect();
983+ for _ in 0..COLUMNS.saturating_sub(shown.len()) {
984+ cols.push(div().w(px(6.)).h(px(1.)));
985+ }
986+ for h in shown.iter().rev() {
987+ let hpx = (2.0 + MAX_H * (*h as f32 / max as f32)).min(MAX_H + 2.0);
988+ cols.push(div().w(px(6.)).h(px(hpx)).bg(accent));
989+ }
990+ Some(h_stack().gap_1().items_end().children(cols).into_any_element())
991+}
992+
202 pub fn render(993 pub fn render(
203 app: &mut AppRoot,994 app: &mut AppRoot,
204 view: &Entity<AppRoot>,995 view: &Entity<AppRoot>,
@@ -208,24 +999,267 @@ pub fn render(
208 let theme = cx.theme().clone();999 let theme = cx.theme().clone();
209 let cracker = &app.state.cracker;1000 let cracker = &app.state.cracker;
210 let running = cracker.running || app.crack_inflight;1001 let running = cracker.running || app.crack_inflight;
211- // Real runs stream an unknown-size wordlist: progress fraction is only1002+ let rainbow_building = cracker.rainbow_building;
212- // meaningful in the bounded mock run.1003+ // Coverage fraction: mock is bounded by construction; real runs get
213- let frac = if app.is_mock {1004+ // their worst-case total from the worker (wordlist lines, brute
214- (cracker.tried as f64 / WORDLIST_TOTAL as f64).clamp(0.0, 1.0)1005+ // space, table entries) when countable.
1006+ let effective_total = if app.is_mock {
1007+ Some(WORDLIST_TOTAL)
215 } else {1008 } else {
216- 0.01009+ cracker.total.filter(|t| *t > 0)
217 };1010 };
218- // Real mode: cracker needs the radio free — capture must be stopped1011+ let frac = effective_total
219- // and a service must have run at least once (it owns the cracker's1012+ .map(|t| (cracker.tried as f64 / t as f64).clamp(0.0, 1.0))
220- // stop flag). After the first "Stop capture" this stays permanently1013+ .unwrap_or(0.0);
221- // unblocked: the service is kept alive across sessions.1014+ let candidates = if let Some(t) = effective_total {
222- let crack_blocked =1015+ format!("candidates: {} / {t}", cracker.tried)
223- !app.is_mock && (app.state.iface_running || app.service.is_none());
224- let candidates = if app.is_mock {
225- format!("candidates: {} / {WORDLIST_TOTAL}", cracker.tried)
226 } else {1016 } else {
227 format!("candidates: {}", cracker.tried)1017 format!("candidates: {}", cracker.tried)
228 };1018 };
1019+ // Worst-case remaining time (real runs): every untried candidate at
1020+ // the current measured rate.
1021+ let eta = (!app.is_mock && running)
1022+ .then(|| fmt_worst_case(cracker.tried, cracker.hps, cracker.total))
1023+ .flatten();
1024+
1025+ // Per-mode inputs, swapped under the attack-mode dropdown.
1026+ let mode_inputs: gpui::AnyElement = match app.attack_mode.as_str() {
1027+ "bruteforce" => h_stack()
1028+ .gap_2()
1029+ .items_center()
1030+ .child(charset_chip("cs-lower", "a-z", app.cs_lower, view, cx, |a| &mut a.cs_lower))
1031+ .child(charset_chip("cs-upper", "A-Z", app.cs_upper, view, cx, |a| &mut a.cs_upper))
1032+ .child(charset_chip("cs-digits", "0-9", app.cs_digits, view, cx, |a| &mut a.cs_digits))
1033+ .child(charset_chip("cs-special", "!@#…", app.cs_special, view, cx, |a| &mut a.cs_special))
1034+ .child(charset_chip("cs-freq-order", "freq-order", app.freq_order, view, cx, |a| {
1035+ &mut a.freq_order
1036+ }))
1037+ .child(
1038+ div().w(px(160.)).child(
1039+ text_field(&app.charset_input, cx)
1040+ .placeholder("custom chars")
1041+ .full_width(true),
1042+ ),
1043+ )
1044+ .child(
1045+ div().w(px(64.)).child(
1046+ text_field(&app.len_min_input, cx)
1047+ .placeholder("min")
1048+ .full_width(true),
1049+ ),
1050+ )
1051+ .child(
1052+ div().w(px(64.)).child(
1053+ text_field(&app.len_max_input, cx)
1054+ .placeholder("max")
1055+ .full_width(true),
1056+ ),
1057+ )
1058+ .child(small("chips + custom · min..max len · freq-order: common characters first").muted())
1059+ .into_any_element(),
1060+ "rules" => h_stack()
1061+ .gap_2()
1062+ .items_end()
1063+ .child(
1064+ div().w(px(320.)).child(
1065+ text_field(&app.wordlist_input, cx)
1066+ .placeholder("/path/to/wordlist")
1067+ .full_width(true),
1068+ ),
1069+ )
1070+ .child(
1071+ div().w(px(320.)).child(
1072+ text_field(&app.rules_input, cx)
1073+ .placeholder("/path/to/rules (hashcat-subset)")
1074+ .full_width(true),
1075+ ),
1076+ )
1077+ .child(small("word × mutation rules").muted())
1078+ .into_any_element(),
1079+ "hybrid" => h_stack()
1080+ .gap_2()
1081+ .items_center()
1082+ .child(
1083+ div().w(px(280.)).child(
1084+ text_field(&app.wordlist_input, cx)
1085+ .placeholder("/path/to/wordlist")
1086+ .full_width(true),
1087+ ),
1088+ )
1089+ .child(charset_chip("cs-lower", "a-z", app.cs_lower, view, cx, |a| &mut a.cs_lower))
1090+ .child(charset_chip("cs-upper", "A-Z", app.cs_upper, view, cx, |a| &mut a.cs_upper))
1091+ .child(charset_chip("cs-digits", "0-9", app.cs_digits, view, cx, |a| &mut a.cs_digits))
1092+ .child(charset_chip("cs-special", "!@#…", app.cs_special, view, cx, |a| &mut a.cs_special))
1093+ .child(
1094+ div().w(px(120.)).child(
1095+ text_field(&app.charset_input, cx)
1096+ .placeholder("custom chars")
1097+ .full_width(true),
1098+ ),
1099+ )
1100+ .child(
1101+ div().w(px(56.)).child(
1102+ text_field(&app.hyb_min_input, cx)
1103+ .placeholder("min")
1104+ .full_width(true),
1105+ ),
1106+ )
1107+ .child(
1108+ div().w(px(56.)).child(
1109+ text_field(&app.hyb_max_input, cx)
1110+ .placeholder("max")
1111+ .full_width(true),
1112+ ),
1113+ )
1114+ .child(small("word + charset suffix len min..max (1..=4)").muted())
1115+ .into_any_element(),
1116+ "rainbow" => h_stack()
1117+ .gap_2()
1118+ .items_end()
1119+ .child(
1120+ div().w(px(360.)).child(
1121+ text_field(&app.rainbow_input, cx)
1122+ .placeholder("/path/to/pmk-table")
1123+ .full_width(true),
1124+ ),
1125+ )
1126+ .child(
1127+ div().w(px(280.)).child(
1128+ text_field(&app.wordlist_input, cx)
1129+ .placeholder("wordlist to build from")
1130+ .full_width(true),
1131+ ),
1132+ )
1133+ .child(
1134+ button("btn-rainbow-build", "Build table")
1135+ .disabled(rainbow_building || running)
1136+ .on_click({
1137+ let view = view.clone();
1138+ move |_, window, cx| build(&view, window, cx)
1139+ }),
1140+ )
1141+ .into_any_element(),
1142+ _ => div()
1143+ .w(px(360.))
1144+ .child(
1145+ text_field(&app.wordlist_input, cx)
1146+ .placeholder("/path/to/wordlist")
1147+ .full_width(true),
1148+ )
1149+ .into_any_element(),
1150+ };
1151+
1152+ // Recent cracker activity: surfaces errors, estimates, import and
1153+ // benchmark results that would otherwise only be visible on the Log
1154+ // page.
1155+ let activity: Vec<String> = app
1156+ .state
1157+ .log
1158+ .iter()
1159+ .filter(|line| {
1160+ line.starts_with("cracker:")
1161+ || line.starts_with("rainbow:")
1162+ || line.starts_with("estimate:")
1163+ || line.starts_with("benchmark:")
1164+ || line.starts_with("import:")
1165+ || line.starts_with("pmk cache")
1166+ || line.starts_with("profiles:")
1167+ || line.contains("PASSWORD")
1168+ })
1169+ .rev()
1170+ .take(5)
1171+ .cloned()
1172+ .collect::<Vec<_>>()
1173+ .into_iter()
1174+ .rev()
1175+ .collect();
1176+
1177+ // Presets + recent wordlists: one-click chips applied to the
1178+ // wordlist/rules fields and (for presets) the attack-mode select.
1179+ let hover_bg = theme.accent_bg();
1180+ let mut preset_row = h_stack().gap_2().items_center();
1181+ let has_presets = !app.profiles.profiles.is_empty() || !app.profiles.recent_wordlists.is_empty();
1182+ for p in &app.profiles.profiles {
1183+ let profile = p.clone();
1184+ preset_row = preset_row.child(
1185+ div()
1186+ .id(gpui::SharedString::from(format!("preset-{}", p.name)))
1187+ .px_2()
1188+ .py_1()
1189+ .rounded_md()
1190+ .border_1()
1191+ .border_color(theme.border())
1192+ .cursor_pointer()
1193+ .text_xs()
1194+ .hover(move |style| style.bg(hover_bg))
1195+ .child(p.name.clone())
1196+ .on_click({
1197+ let view = view.clone();
1198+ move |_, _window, cx| apply_preset(profile.clone(), &view, cx)
1199+ }),
1200+ );
1201+ }
1202+ if !app.profiles.profiles.is_empty() {
1203+ preset_row = preset_row.child(
1204+ button("btn-preset-save", "Save preset")
1205+ .on_click({
1206+ let view = view.clone();
1207+ move |_, window, cx| save_preset(&view, window, cx)
1208+ }),
1209+ );
1210+ }
1211+ let mut recent_row = h_stack().gap_2().items_center();
1212+ for wl in &app.profiles.recent_wordlists {
1213+ let wl_path = wl.clone();
1214+ let base = std::path::Path::new(wl)
1215+ .file_name()
1216+ .map(|n| n.to_string_lossy().into_owned())
1217+ .unwrap_or_else(|| wl.clone());
1218+ recent_row = recent_row.child(
1219+ div()
1220+ .id(gpui::SharedString::from(format!("recent-{wl}")))
1221+ .px_2()
1222+ .py_1()
1223+ .rounded_md()
1224+ .border_1()
1225+ .border_color(theme.border())
1226+ .cursor_pointer()
1227+ .text_xs()
1228+ .hover(move |style| style.bg(hover_bg))
1229+ .child(base)
1230+ .on_click({
1231+ let view = view.clone();
1232+ move |_, _window, cx| {
1233+ let wl = wl_path.clone();
1234+ view.update(cx, |app, cx| {
1235+ app.wordlist_input.update(cx, |input, cx| {
1236+ input.set_content(wl, cx);
1237+ });
1238+ cx.notify();
1239+ });
1240+ }
1241+ }),
1242+ );
1243+ }
1244+
1245+ // Benchmark card lines (below the Start/Stop row).
1246+ let bench_gpu_line = match app.state.bench_gpu {
1247+ Some(g) => format!("GPU: {}", fmt_hps(g)),
1248+ None => {
1249+ if app.state.bench_cpu.is_some() {
1250+ "GPU: none (CPU only)".to_string()
1251+ } else {
1252+ "not measured — run Benchmark".to_string()
1253+ }
1254+ }
1255+ };
1256+ let bench_cpu_line = app
1257+ .state
1258+ .bench_cpu
1259+ .map(|c| format!("CPU: {}", fmt_hps(c)))
1260+ .unwrap_or_default();
1261+ let bench_disabled =
1262+ app.bench_running || app.crack_inflight || cracker.running || cracker.rainbow_building;
229 1263
230 let mut page = v_stack()1264 let mut page = v_stack()
231 .size_full()1265 .size_full()
@@ -236,22 +1270,44 @@ pub fn render(
236 .items_center()1270 .items_center()
237 .gap_3()1271 .gap_3()
238 .child(h3("Handshake Cracker"))1272 .child(h3("Handshake Cracker"))
239- .child(small("PBKDF2-SHA1 · WPA/WPA2")),1273+ .child(small("PBKDF2-SHA1 · WPA/WPA2"))
1274+ .child(div().flex_1())
1275+ .child(
1276+ button("btn-import", "Import .cap/.pcap/.hc22000")
1277+ .disabled(app.import_busy)
1278+ .on_click({
1279+ let view = view.clone();
1280+ move |_, window, cx| import_captures(&view, window, cx)
1281+ }),
1282+ ),
240 )1283 )
1284+ .when(has_presets, |el| {
1285+ el.child(preset_row)
1286+ .when(
1287+ !app.profiles.recent_wordlists.is_empty() || !app.profiles.profiles.is_empty(),
1288+ |el2| el2.child(recent_row),
1289+ )
1290+ })
1291+ .when(!has_presets, |el| {
1292+ // No saved state yet — still offer one-click saving of the
1293+ // current setup.
1294+ el.child(
1295+ h_stack().gap_2().items_center().child(
1296+ button("btn-preset-save", "Save preset")
1297+ .on_click({
1298+ let view = view.clone();
1299+ move |_, window, cx| save_preset(&view, window, cx)
1300+ }),
1301+ ),
1302+ )
1303+ })
241 .child(1304 .child(
242 h_stack()1305 h_stack()
243 .gap_3()1306 .gap_3()
244 .items_end()1307 .items_end()
245 .child(div().w(px(360.)).child(app.target_select.clone()))1308 .child(div().w(px(360.)).child(app.target_select.clone()))
246- .child(1309+ .child(div().w(px(200.)).child(app.attack_select.clone()))
247- div()1310+ .child(mode_inputs)
248- .w(px(360.))
249- .child(
250- text_field(&app.wordlist_input, cx)
251- .placeholder("/path/to/wordlist")
252- .full_width(true),
253- ),
254- )
255 .child(text(backend_label(app.is_mock)).small().muted()),1311 .child(text(backend_label(app.is_mock)).small().muted()),
256 )1312 )
257 .child(1313 .child(
@@ -260,7 +1316,7 @@ pub fn render(
260 .items_center()1316 .items_center()
261 .child(1317 .child(
262 button("btn-crack-start", "Start")1318 button("btn-crack-start", "Start")
263- .disabled(running || crack_blocked)1319+ .disabled(running || app.bench_running)
264 .on_click({1320 .on_click({
265 let view = view.clone();1321 let view = view.clone();
266 move |_, window, cx| start(&view, window, cx)1322 move |_, window, cx| start(&view, window, cx)
@@ -275,14 +1331,7 @@ pub fn render(
275 move |_, window, cx| stop(&view, window, cx)1331 move |_, window, cx| stop(&view, window, cx)
276 }),1332 }),
277 )1333 )
278- .when(running, |el| el.child(loading_indicator().small()))1334+ .when(running, |el| el.child(loading_indicator().small())),
279- .when(crack_blocked, |el| {
280- el.child(small(if app.state.iface_running {
281- "stop capture first — cracker needs the radio"
282- } else {
283- "start then stop capture to enable the cracker"
284- }))
285- }),
286 )1335 )
287 .child(gpuikit::elements::separator::separator())1336 .child(gpuikit::elements::separator::separator())
288 .child(1337 .child(
@@ -291,14 +1340,99 @@ pub fn render(
291 .child(small(format!("rate: {}", fmt_hps(if running { cracker.hps } else { 0.0 }))))1340 .child(small(format!("rate: {}", fmt_hps(if running { cracker.hps } else { 0.0 }))))
292 .child(small(candidates))1341 .child(small(candidates))
293 .child(1342 .child(
294- small(if app.is_mock {1343+ small({
295- format!("{:.1}%", frac * 100.0)1344+ // Coverage % whenever a total exists; ETA needs a
296- } else {1345+ // live run too.
297- String::new()1346+ let pct = effective_total.map(|_| format!("{:.1}%", frac * 100.0));
1347+ match (pct, &eta) {
1348+ (Some(p), Some(e)) => format!("{p} · {e}"),
1349+ (Some(p), None) => p,
1350+ (None, Some(e)) => e.clone(),
1351+ (None, None) => String::new(),
1352+ }
298 }),1353 }),
299 ),1354 ),
300 )1355 )
301- .child(progress(frac as f32).width(px(520.)));1356+ .child(progress(frac as f32).width(px(520.)))
1357+ .children(
1358+ hps_curve(&app.state.hps_hist, theme.accent()).map(|curve| {
1359+ v_stack()
1360+ .gap_1()
1361+ .child(small("rate over time (one bar per progress sample)").muted())
1362+ .child(curve)
1363+ }),
1364+ )
1365+ .child(
1366+ // Benchmark card: measured crack speed on this machine.
1367+ h_stack()
1368+ .gap_3()
1369+ .items_center()
1370+ .p_3()
1371+ .rounded_md()
1372+ .border_1()
1373+ .border_color(theme.border())
1374+ .child(small("crack speed on this machine"))
1375+ .child(
1376+ button("btn-benchmark", "Benchmark (3s)")
1377+ .disabled(bench_disabled)
1378+ .on_click({
1379+ let view = view.clone();
1380+ move |_, window, cx| benchmark(&view, window, cx)
1381+ }),
1382+ )
1383+ .when(app.bench_running, |el| el.child(loading_indicator().small()))
1384+ .child(small(bench_gpu_line).muted())
1385+ .child(small(bench_cpu_line).muted()),
1386+ )
1387+ .child(
1388+ // Estimator card: worst-case times from the measured rate.
1389+ h_stack()
1390+ .gap_3()
1391+ .items_center()
1392+ .p_3()
1393+ .rounded_md()
1394+ .border_1()
1395+ .border_color(theme.border())
1396+ .child(small("candidate strength / time estimate"))
1397+ .child(
1398+ div().w(px(220.)).child(
1399+ text_field(&app.strength_input, cx)
1400+ .placeholder("type a candidate password")
1401+ .full_width(true),
1402+ ),
1403+ )
1404+ .child(
1405+ button("btn-estimate", "Estimate")
1406+ .disabled(app.bench_running)
1407+ .on_click({
1408+ let view = view.clone();
1409+ move |_, window, cx| estimate(&view, window, cx)
1410+ }),
1411+ )
1412+ .child(small("results land in recent activity below").muted()),
1413+ );
1414+
1415+ // Recent captures: the newest few crackable targets, so the page shows
1416+ // what material exists without opening the dropdown. Newest last in
1417+ // state → reversed for display.
1418+ let recent_caps: Vec<String> = app
1419+ .state
1420+ .capture_descs()
1421+ .into_iter()
1422+ .rev()
1423+ .take(4)
1424+ .collect();
1425+ if !recent_caps.is_empty() {
1426+ page = page.child(
1427+ v_stack()
1428+ .gap_1()
1429+ .child(small("recent captures (all of them are in the target dropdown)").muted())
1430+ .children(recent_caps.into_iter().map(|d| {
1431+ text(d).code().small().into_any_element()
1432+ }))
1433+ .into_any_element(),
1434+ );
1435+ }
302 1436
303 if let Some(found) = &cracker.found {1437 if let Some(found) = &cracker.found {
304 page = page.child(1438 page = page.child(
@@ -315,5 +1449,78 @@ pub fn render(
315 );1449 );
316 }1450 }
317 1451
1452+ // Interrupted-run resume banner (saved session file matched to a
1453+ // loaded capture; hidden while anything runs).
1454+ if !running && !rainbow_building && !app.is_mock {
1455+ if let Some(r) = &cracker.resume {
1456+ let status = match r.total {
1457+ Some(t) => format!("{} / {t} tried", r.done),
1458+ None => format!("{} tried", r.done),
1459+ };
1460+ page = page.child(
1461+ h_stack()
1462+ .gap_3()
1463+ .items_center()
1464+ .p_3()
1465+ .rounded_md()
1466+ .border_1()
1467+ .border_color(theme.border())
1468+ .bg(theme.accent_bg())
1469+ .child(small(format!(
1470+ "saved run: {} — {} · {status}",
1471+ r.target_desc,
1472+ r.attack.describe()
1473+ )))
1474+ .child(
1475+ button("btn-crack-resume", "Resume")
1476+ .on_click({
1477+ let view = view.clone();
1478+ move |_, window, cx| resume_saved(&view, window, cx)
1479+ }),
1480+ )
1481+ .child(
1482+ button("btn-crack-discard", "Discard")
1483+ .destructive()
1484+ .on_click({
1485+ let view = view.clone();
1486+ move |_, window, cx| discard_saved(&view, window, cx)
1487+ }),
1488+ ),
1489+ );
1490+ }
1491+ }
1492+
1493+ if !activity.is_empty() {
1494+ let mut block = v_stack().gap_1();
1495+ for line in activity {
1496+ block = block.child(small(line).muted());
1497+ }
1498+ page = page.child(block);
1499+ }
1500+
1501+ if rainbow_building {
1502+ page = page.child(
1503+ h_stack()
1504+ .gap_3()
1505+ .items_center()
1506+ .child(loading_indicator().small())
1507+ .child(small(format!(
1508+ "rainbow build: {} PMKs · {} · {}",
1509+ cracker.rainbow_done,
1510+ fmt_hps(cracker.rainbow_hps),
1511+ fmt_worst_case(cracker.rainbow_done, cracker.rainbow_hps, cracker.rainbow_total)
1512+ .unwrap_or_default()
1513+ )))
1514+ .child(
1515+ button("btn-rainbow-stop", "Stop build")
1516+ .destructive()
1517+ .on_click({
1518+ let view = view.clone();
1519+ move |_, window, cx| build_stop(&view, window, cx)
1520+ }),
1521+ ),
1522+ );
1523+ }
1524+
318 page1525 page
319 }1526 }
src/ui/log.rsmodified+44 -29
@@ -1,29 +1,33 @@
1-//! Log page: scrolling monospace view of the backend event log, newest1+//! Log page: read-only multiline text area over the backend event log
2-//! entries first.2+//! (plain text widgets are NOT selectable; the input gives mouse-
3+//! selection + Ctrl-C for free). A "Copy log" button puts the whole
4+//! buffer, oldest first, straight on the clipboard.
3 5
4-use gpui::{Context, Entity, ParentElement, Styled, Window};6+use gpui::{ClipboardItem, Context, Entity, ParentElement, Styled, Window};
5-use gpuikit::elements::scroll_area::scroll_area;7+use gpuikit::elements::button::button;
6-use gpuikit::elements::typography::{h3, small, text};8+use gpuikit::elements::input::text_area;
9+use gpuikit::elements::typography::{h3, small};
7 use gpuikit::layout::{h_stack, v_stack};10 use gpuikit::layout::{h_stack, v_stack};
8-use gpuikit::theme::{ActiveTheme, Themeable};
9 11
10 use crate::ui::app::AppRoot;12 use crate::ui::app::AppRoot;
11 13
12 pub fn render(14 pub fn render(
13 app: &mut AppRoot,15 app: &mut AppRoot,
14- _view: &Entity<AppRoot>,16+ view: &Entity<AppRoot>,
15 _window: &mut Window,17 _window: &mut Window,
16 cx: &mut Context<AppRoot>,18 cx: &mut Context<AppRoot>,
17 ) -> gpui::Div {19 ) -> gpui::Div {
18- let theme = cx.theme().clone();20+ // Sync the read-only view with the log buffer, oldest first.
19-21+ let joined = app
20- let mut lines_view = v_stack().gap_0p5();22+ .state
21- if app.state.log.is_empty() {23+ .log
22- lines_view = lines_view.child(small("log is empty"));24+ .iter()
23- } else {25+ .cloned()
24- for line in app.state.log.iter().rev() {26+ .collect::<Vec<_>>()
25- lines_view = lines_view.child(text(line.clone()).code().small());27+ .join("\n");
26- }28+ if app.log_input.read(cx).content() != joined {
29+ app.log_input
30+ .update(cx, |input, cx| input.set_content_silent(joined, cx));
27 }31 }
28 32
29 v_stack()33 v_stack()
@@ -35,18 +39,29 @@ pub fn render(
35 .items_center()39 .items_center()
36 .gap_3()40 .gap_3()
37 .child(h3("Log"))41 .child(h3("Log"))
38- .child(small(format!("{} lines (newest first)", app.state.log.len()))),42+ .child(small(format!(
39- )43+ "{} lines — click, drag, Ctrl-A/Ctrl-C to copy",
40- .child(44+ app.state.log.len()
41- scroll_area("log-scroll")45+ )))
42- .vertical()46+ .child(gpui::div().flex_1())
43- .full_height(true)47+ .child(button("btn-copy-log", "Copy log").on_click({
44- .child(48+ let view = view.clone();
45- lines_view49+ move |_, _window, cx| {
46- .w_full()50+ let joined = view
47- .p_2()51+ .read(cx)
48- .rounded_md()52+ .state
49- .bg(theme.surface_secondary()),53+ .log
50- ),54+ .iter()
55+ .cloned()
56+ .collect::<Vec<_>>()
57+ .join("\n");
58+ cx.write_to_clipboard(ClipboardItem::new_string(joined));
59+ view.update(cx, |app, cx| {
60+ app.state.push_log("log copied to clipboard");
61+ cx.notify();
62+ });
63+ }
64+ })),
51 )65 )
66+ .child(gpui::div().flex_1().min_h_0().child(text_area(&app.log_input, cx)))
52 }67 }
src/ui/mock.rsmodified+164 -14
@@ -8,7 +8,8 @@ use std::time::{Duration, Instant};
8 use crossbeam_channel::Sender;8 use crossbeam_channel::Sender;
9 9
10 use crate::common::{10 use crate::common::{
11- AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture, Security, now_ms,11+ AccessPoint, Akm, ChannelStat, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture,
12+ ProbeInfo, Security, now_ms,
12 };13 };
13 14
14 /// Salted deterministic PRNG (xorshift64) — no rand crate, values only need15 /// Salted deterministic PRNG (xorshift64) — no rand crate, values only need
@@ -43,9 +44,14 @@ pub const MOCK_CLIENTS: [MacAddr; 4] = [
43 MacAddr([0x44, 0x55, 0x66, 0x77, 0x88, 0x99]),44 MacAddr([0x44, 0x55, 0x66, 0x77, 0x88, 0x99]),
44 ];45 ];
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").
49+pub const MOCK_ROT1: MacAddr = MacAddr([0x02, 0xa0, 0xb1, 0xc2, 0xd3, 0xe4]);
50+pub const MOCK_ROT2: MacAddr = MacAddr([0x06, 0x5f, 0x4e, 0x3d, 0x2c, 0x1b]);
51+
46 fn seed_aps() -> Vec<AccessPoint> {52 fn seed_aps() -> Vec<AccessPoint> {
47 let now = now_ms();53 let now = now_ms();
48- let ap = |mac: [u8; 6], ssid: &str, channel, security, rssi| AccessPoint {54+ let ap = |mac: [u8; 6], ssid: &str, channel, security, rssi, akms: Vec<Akm>| AccessPoint {
49 bssid: MacAddr(mac),55 bssid: MacAddr(mac),
50 ssid: ssid.to_string(),56 ssid: ssid.to_string(),
51 channel,57 channel,
@@ -53,31 +59,96 @@ fn seed_aps() -> Vec<AccessPoint> {
53 rssi_dbm: rssi,59 rssi_dbm: rssi,
54 beacons: 200,60 beacons: 200,
55 last_seen_ms: now,61 last_seen_ms: now,
62+ akms,
56 };63 };
57 vec![64 vec![
58- ap([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], "parafin", 6, Security::Wpa2, -42),65+ ap(
59- ap([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e], "labnet", 1, Security::Wpa2, -55),66+ [0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff],
60- ap([0x02, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e], "coffeeshop", 11, Security::Wpa2, -68),67+ "parafin",
61- ap([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb], "corp-wpa3", 36, Security::Wpa3, -61),68+ 6,
62- ap([0x02, 0xde, 0xad, 0xbe, 0xef, 0x00], "legacy-prn", 3, Security::Wep, -80),69+ Security::Wpa2,
63- ap([0x02, 0x00, 0x11, 0x22, 0x33, 0x44], "open-wifi", 6, Security::Open, -72),70+ -42,
71+ vec![Akm::Psk],
72+ ),
73+ ap(
74+ [0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e],
75+ "labnet",
76+ 1,
77+ Security::Wpa2,
78+ -55,
79+ vec![Akm::Psk],
80+ ),
81+ ap(
82+ [0x02, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e],
83+ "coffeeshop",
84+ 11,
85+ Security::Wpa2,
86+ -68,
87+ vec![Akm::Psk],
88+ ),
89+ ap(
90+ [0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb],
91+ "corp-wpa3",
92+ 36,
93+ Security::Wpa3,
94+ -61,
95+ vec![Akm::Psk, Akm::Sae],
96+ ),
97+ ap(
98+ [0x02, 0xde, 0xad, 0xbe, 0xef, 0x00],
99+ "legacy-prn",
100+ 3,
101+ Security::Wep,
102+ -80,
103+ Vec::new(),
104+ ),
105+ ap(
106+ [0x02, 0x00, 0x11, 0x22, 0x33, 0x44],
107+ "open-wifi",
108+ 6,
109+ Security::Open,
110+ -72,
111+ Vec::new(),
112+ ),
113+ // Same SSID as `parafin` but OPEN + different BSSID: trips the
114+ // UI's rogue-AP detection so the warning path is visible in mock.
115+ ap(
116+ [0x02, 0x66, 0x66, 0x66, 0x66, 0x66],
117+ "parafin",
118+ 11,
119+ Security::Open,
120+ -77,
121+ Vec::new(),
122+ ),
64 ]123 ]
65 }124 }
66 125
67 fn seed_clients() -> Vec<ClientInfo> {126 fn seed_clients() -> Vec<ClientInfo> {
68 let now = now_ms();127 let now = now_ms();
69- let cl = |mac: MacAddr, ap: MacAddr, rssi| ClientInfo {128+ let cl = |mac: MacAddr, ap: MacAddr, rssi, connected: bool| ClientInfo {
70 mac,129 mac,
71 ap: Some(ap),130 ap: Some(ap),
72 rssi_dbm: rssi,131 rssi_dbm: rssi,
73 frames: 40,132 frames: 40,
74 last_seen_ms: now,133 last_seen_ms: now,
134+ connected,
135+ ident_group: None,
136+ ident_conf: None,
75 };137 };
76 vec![138 vec![
77- cl(MOCK_CLIENTS[0], MOCK_BSSID, -44),139+ cl(MOCK_CLIENTS[0], MOCK_BSSID, -44, true),
78- cl(MOCK_CLIENTS[1], MOCK_BSSID, -51),140+ cl(MOCK_CLIENTS[1], MOCK_BSSID, -51, true),
79- cl(MOCK_CLIENTS[2], MacAddr([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e]), -60),141+ cl(MOCK_CLIENTS[2], MacAddr([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e]), -60, true),
80- cl(MOCK_CLIENTS[3], MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]), -63),142+ // Locally-administered (randomized) MAC — the ROT2 milestone below
143+ // pairs it with ROT1 as one physical radio.
144+ cl(MOCK_ROT1, MOCK_BSSID, -48, true),
145+ // Deauth-flagged so the disconnected state is visible in mock mode.
146+ cl(
147+ MOCK_CLIENTS[3],
148+ MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]),
149+ -63,
150+ false,
151+ ),
81 ]152 ]
82 }153 }
83 154
@@ -148,7 +219,7 @@ pub fn spawn_mock(tx: Sender<Event>) {
148 219
149 fn run(tx: Sender<Event>) {220 fn run(tx: Sender<Event>) {
150 let _ = tx.send(Event::Log(format!(221 let _ = tx.send(Event::Log(format!(
151- "mock: scanning on {MOCK_IFACE} (6 APs, 4 clients)"222+ "mock: scanning on {MOCK_IFACE} (7 APs, 4 clients)"
152 )));223 )));
153 224
154 let mut rng = Rng(0x9e37_79b9_7f4a_7c15);225 let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
@@ -163,6 +234,21 @@ fn run(tx: Sender<Event>) {
163 234
164 let started = Instant::now();235 let started = Instant::now();
165 let mut stage = 0usize;236 let mut stage = 0usize;
237+ let mut tick = 0u64;
238+ // Drifting cumulative per-channel counters for the ChannelStats feed.
239+ let mut chan_frames: [u64; 4] = [120, 980, 340, 60];
240+ let mut chan_beacons: [u64; 4] = [40, 210, 90, 12];
241+ // Probe-request feed cycles these (client, ssid) pairs.
242+ const PROBE_FEED: &[(MacAddr, Option<&str>)] = &[
243+ (MOCK_CLIENTS[0], Some("HOME-WIFI")),
244+ (MOCK_CLIENTS[1], Some("labnet")),
245+ (MOCK_CLIENTS[2], None),
246+ (MOCK_CLIENTS[3], Some("coffeeshop")),
247+ (MOCK_CLIENTS[1], None),
248+ ];
249+ let mut probe_step = 0usize;
250+ let mut ident_fed = false;
251+ let mut deauth_alert_sent = false;
166 const LOG_LINES: &[&str] = &[252 const LOG_LINES: &[&str] = &[
167 "hop: ch 1 → ch 6",253 "hop: ch 1 → ch 6",
168 "probe request from 11:22:33:44:55:66 (\"labnet\")",254 "probe request from 11:22:33:44:55:66 (\"labnet\")",
@@ -175,9 +261,73 @@ fn run(tx: Sender<Event>) {
175 261
176 loop {262 loop {
177 thread::sleep(Duration::from_millis(200));263 thread::sleep(Duration::from_millis(200));
264+ tick += 1;
178 let t = started.elapsed().as_secs_f32();265 let t = started.elapsed().as_secs_f32();
179 let now = now_ms();266 let now = now_ms();
180 267
268+ // Per-channel activity snapshot every ~2 s (10 ticks).
269+ if tick % 10 == 0 {
270+ let mut stats = Vec::with_capacity(4);
271+ for (i, ch) in [1u8, 6, 11, 36].iter().enumerate() {
272+ chan_frames[i] += 20 + rng.below(180);
273+ chan_beacons[i] += rng.below(6);
274+ stats.push(ChannelStat {
275+ channel: *ch,
276+ frames: chan_frames[i],
277+ beacons: chan_beacons[i],
278+ });
279+ }
280+ let _ = tx.send(Event::ChannelStats(stats));
281+ }
282+
283+ // Probe-request feed every ~3 s (15 ticks).
284+ if tick % 15 == 0 {
285+ let (client, ssid) = PROBE_FEED[probe_step % PROBE_FEED.len()];
286+ probe_step += 1;
287+ let _ = tx.send(Event::ProbeObserved(ProbeInfo {
288+ client,
289+ ssid: ssid.map(str::to_string),
290+ rssi_dbm: -(40 + rng.below(45) as i8),
291+ at_ms: now,
292+ }));
293+ }
294+
295+ // MAC-rotation storyline at ~6 s: a new randomized MAC appears and
296+ // the correlator pairs both into device group #1.
297+ if !ident_fed && t >= 6.0 {
298+ ident_fed = true;
299+ let _ = tx.send(Event::ClientIdent {
300+ mac: MOCK_ROT1,
301+ group: 1,
302+ confidence: crate::common::IdentConfidence::Strong,
303+ });
304+ let _ = tx.send(Event::ClientUpdated(ClientInfo {
305+ mac: MOCK_ROT2,
306+ ap: Some(MOCK_BSSID),
307+ rssi_dbm: -46,
308+ frames: 3,
309+ last_seen_ms: now,
310+ connected: true,
311+ ident_group: None,
312+ ident_conf: None,
313+ }));
314+ let _ = tx.send(Event::ClientIdent {
315+ mac: MOCK_ROT2,
316+ group: 1,
317+ confidence: crate::common::IdentConfidence::Strong,
318+ });
319+ }
320+
321+ // One foreign-deauth storm milestone at ~12 s.
322+ if !deauth_alert_sent && t >= 12.0 {
323+ deauth_alert_sent = true;
324+ let _ = tx.send(Event::DeauthAlert {
325+ source: MOCK_BSSID,
326+ target: MacAddr::BROADCAST,
327+ count: 64,
328+ });
329+ }
330+
181 // RSSI drift + beacon/frame counters on every tick.331 // RSSI drift + beacon/frame counters on every tick.
182 for ap in &mut aps {332 for ap in &mut aps {
183 ap.rssi_dbm = (ap.rssi_dbm + (rng.below(5) as i8 - 2)).clamp(-90, -30);333 ap.rssi_dbm = (ap.rssi_dbm + (rng.below(5) as i8 - 2)).clamp(-90, -30);
src/ui/mod.rsmodified+1 -1
@@ -8,7 +8,7 @@ mod app;
8 mod attacks;8 mod attacks;
9 mod cracker;9 mod cracker;
10 mod log;10 mod log;
11-mod mock;11+pub(crate) mod mock;
12 mod networks;12 mod networks;
13 pub mod state;13 pub mod state;
14 14
src/ui/networks.rsmodified+646 -59
@@ -3,26 +3,45 @@
3 3
4 use gpui::{Context, Entity, IntoElement, ParentElement, Styled, Window, div, px};4 use gpui::{Context, Entity, IntoElement, ParentElement, Styled, Window, div, px};
5 use gpuikit::elements::badge::badge;5 use gpuikit::elements::badge::badge;
6+use gpuikit::elements::button::button;
7+use gpuikit::elements::progress::progress;
6 use gpuikit::elements::table::{CellAlign, Column, Row, SortDirection, Table, table};8 use gpuikit::elements::table::{CellAlign, Column, Row, SortDirection, Table, table};
7-use gpuikit::elements::typography::{h3, small};9+use gpuikit::elements::text_field::text_field;
8-use gpuikit::layout::v_stack;10+use gpuikit::elements::typography::{h3, small, text};
11+use gpuikit::layout::{h_stack, v_stack};
12+use gpuikit::theme::{ActiveTheme, Themeable};
9 13
10-use crate::common::{AccessPoint, ClientInfo, MacAddr, Security};14+use crate::common::{AccessPoint, ClientInfo, MacAddr, ProbeInfo, Security};
11 use crate::ui::app::AppRoot;15 use crate::ui::app::AppRoot;
12 16
17+use std::collections::VecDeque;
18+
13 const COL_BSSID: usize = 0;19 const COL_BSSID: usize = 0;
14 const COL_SSID: usize = 1;20 const COL_SSID: usize = 1;
15-const COL_CH: usize = 2;21+// Column-order documentation; vendor columns are not sortable, so nothing
16-const COL_SEC: usize = 3;22+// references these by value (sort arms only name the sortable consts).
17-const COL_RSSI: usize = 4;23+#[allow(dead_code)]
18-const COL_BEACONS: usize = 5;24+const COL_VENDOR: usize = 2;
19-const COL_AGE: usize = 6;25+const COL_LABEL: usize = 3;
26+const COL_CH: usize = 4;
27+const COL_BAND: usize = 5;
28+const COL_SEC: usize = 6;
29+const COL_RSSI: usize = 7;
30+const COL_BEACONS: usize = 8;
31+const COL_AGE: usize = 9;
20 32
21 const CCOL_MAC: usize = 0;33 const CCOL_MAC: usize = 0;
22-const CCOL_AP: usize = 1;34+#[allow(dead_code)]
23-const CCOL_RSSI: usize = 2;35+const CCOL_VENDOR: usize = 1;
24-const CCOL_FRAMES: usize = 3;36+const CCOL_STATE: usize = 2;
25-const CCOL_AGE: usize = 4;37+const CCOL_LABEL: usize = 3;
38+const CCOL_AP: usize = 4;
39+const CCOL_RSSI: usize = 5;
40+const CCOL_FRAMES: usize = 6;
41+const CCOL_AGE: usize = 7;
42+// Device-group id (MAC-randomization pairing); not sortable.
43+#[allow(dead_code)]
44+const CCOL_ID: usize = 8;
26 45
27 /// Human "last seen" age, e.g. `2s`, `5m`, `1h`. `last_seen_ms` comes from46 /// Human "last seen" age, e.g. `2s`, `5m`, `1h`. `last_seen_ms` comes from
28 /// the UI/service-side process-local clock ([`crate::common::now_ms`]).47 /// the UI/service-side process-local clock ([`crate::common::now_ms`]).
@@ -37,22 +56,179 @@ pub fn age(last_seen_ms: u64) -> String {
37 }56 }
38 }57 }
39 58
40-fn sec_badge(sec: Security) -> gpuikit::elements::badge::Badge {59+/// Band label for display: 2.4 GHz when the channel maps below 3 GHz,
60+/// else 5 GHz. (6 GHz channel numbers collide with 2.4 GHz in this app —
61+/// the scanner treats them as cosmetic, so 6 GHz APs may read "2.4".)
62+pub(crate) fn band(ch: u8) -> &'static str {
63+ match crate::common::freq_of_channel(ch) {
64+ Some(f) if f < 3000 => "2.4",
65+ Some(_) => "5",
66+ None => "?",
67+ }
68+}
69+
70+pub(crate) fn sec_badge_label(label: &str, sec: Security) -> gpuikit::elements::badge::Badge {
41 match sec {71 match sec {
42- Security::Open => badge(sec.label()).outline(),72+ Security::Open => badge(label).outline(),
43- Security::Wep => badge(sec.label()).destructive(),73+ Security::Wep => badge(label).destructive(),
44- Security::Wpa | Security::Wpa2 => badge(sec.label()),74+ Security::Wpa | Security::Wpa2 => badge(label),
45- Security::Wpa3 => badge(sec.label()).secondary(),75+ Security::Wpa3 => badge(label).secondary(),
76+ }
77+}
78+
79+fn sec_badge(sec: Security) -> gpuikit::elements::badge::Badge {
80+ sec_badge_label(sec.label(), sec)
81+}
82+
83+/// Refined security label for the badge. The AKM suites of the RSN IE know
84+/// more than the broad `Security` buckets: a transition AP (PSK+SAE) reads
85+/// `WPA2/3`, an SAE-only AP reads `WPA3`, an OWE-only AP `OWE`.
86+pub(crate) fn sec_label(ap: &AccessPoint) -> String {
87+ let has = |k: crate::common::Akm| ap.akms.contains(&k);
88+ if ap.security == Security::Wpa3 && has(crate::common::Akm::Sae) {
89+ let pskish = has(crate::common::Akm::Psk)
90+ || has(crate::common::Akm::PskSha256)
91+ || has(crate::common::Akm::FtPsk);
92+ if !pskish {
93+ return "WPA3".to_string();
94+ }
95+ }
96+ // OWE ("enhanced open") still carries an RSN IE, so it lands in the
97+ // Wpa2 bucket — only the AKM list reveals it.
98+ if has(crate::common::Akm::Owe) && ap.akms.len() == 1 {
99+ return "OWE".to_string();
46 }100 }
101+ ap.security.label().to_string()
102+}
103+
104+/// Station liveness badge: `up` while frames are flowing, `down` once the
105+/// scanner observed a deauth/disassoc hitting this client.
106+fn conn_badge(cl: &ClientInfo) -> gpuikit::elements::badge::Badge {
107+ if cl.connected {
108+ badge("up").secondary()
109+ } else {
110+ badge("down").destructive()
111+ }
112+}
113+
114+/// Client-table text cell. Disconnected rows are dimmed so the flagged
115+/// stations visually recede from the live ones.
116+fn client_cell(cl: &ClientInfo, body: String, cx: &mut gpui::App) -> gpui::AnyElement {
117+ let mut cell = div().child(body);
118+ if !cl.connected {
119+ cell = cell.text_color(cx.theme().fg_muted());
120+ }
121+ cell.into_any_element()
122+}
123+
124+/// Clients-section subtitle: `N stations`, `N stations (M down)` when the
125+/// scanner flagged disconnects.
126+fn client_counts(app: &AppRoot) -> String {
127+ let total = app.state.clients.len();
128+ let down = app.state.clients.values().filter(|c| !c.connected).count();
129+ if down == 0 {
130+ format!("{total} stations")
131+ } else {
132+ format!("{total} stations ({down} down)")
133+ }
134+}
135+
136+/// OUI vendor for a MAC; `random` for locally-administered MACs (modern
137+/// phones/laptops rotate these — look at the ID column for the pairing),
138+/// `—` for unknown prefixes.
139+pub(crate) fn vendor_of(mac: &MacAddr) -> &'static str {
140+ if crate::oui::is_locally_administered(mac) {
141+ "random"
142+ } else {
143+ crate::oui::lookup(mac).unwrap_or("—")
144+ }
145+}
146+
147+/// Normalized (trim + lowercase) form matching `state.rogue_ssids` keys.
148+fn norm_ssid(s: &str) -> String {
149+ s.trim().to_lowercase()
150+}
151+
152+/// Sparkline cell: up to 20 bars from the recent RSSI history of `mac`,
153+/// right-aligned in recency order (last 20 values), padded to a stable
154+/// 20-slot width with transparent placeholders. Height maps rssi -95..-30
155+/// dBm onto 2..10 px.
156+pub(crate) fn sparkline(
157+ hist: Option<&VecDeque<i8>>,
158+ accent: gpui::Hsla,
159+) -> gpui::AnyElement {
160+ let mut bars: Vec<gpui::Div> = Vec::with_capacity(20);
161+ if let Some(hist) = hist {
162+ for &r in hist.iter().rev().take(20) {
163+ let r = r as f32;
164+ let h = ((r + 95.0) / 65.0 * 8.0 + 2.0).clamp(2.0, 10.0);
165+ bars.push(div().w(px(3.)).h(px(h)).bg(accent));
166+ }
167+ bars.reverse();
168+ }
169+ while bars.len() < 20 {
170+ bars.insert(0, div().w(px(3.)).h(px(1.)));
171+ }
172+ h_stack()
173+ .items_end()
174+ .gap(px(1.))
175+ .h(px(10.))
176+ .children(bars)
177+ .into_any_element()
178+}
179+
180+/// MAC of the row the label editor targets: a selected client wins over
181+/// the selected AP.
182+fn label_target(app: &AppRoot) -> Option<MacAddr> {
183+ app.selected_client.or(app.selected)
184+}
185+
186+/// Prefill the label input with the current label of `mac` (empty when
187+/// none) — called whenever a row becomes the label target.
188+fn prefill_label(app: &AppRoot, mac: MacAddr, cx: &mut Context<AppRoot>) {
189+ let cur = app.state.labels.get(&mac).cloned().unwrap_or_default();
190+ app.label_input
191+ .update(cx, |input, cx| input.set_content(cur, cx));
192+}
193+
194+/// Save button: write the input as the label of the current target (empty
195+/// input = clear), then persist the whole map to `~/wifilab/labels.json`.
196+fn save_label(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) {
197+ view.update(cx, |app, cx| {
198+ let Some(mac) = label_target(app) else {
199+ app.state.push_log("label: select an AP or client row first");
200+ cx.notify();
201+ return;
202+ };
203+ let raw = app.label_input.read(cx).content().trim().to_string();
204+ if raw.is_empty() {
205+ if app.state.labels.remove(&mac).is_some() {
206+ app.state.push_log(format!("label cleared: {mac}"));
207+ }
208+ } else {
209+ app.state.labels.insert(mac, raw.clone());
210+ app.state.push_log(format!("label set: {mac} = \"{raw}\""));
211+ }
212+ if let Err(e) = crate::store::save(&app.state.labels) {
213+ app.state.push_log(format!("label save FAILED: {e:#}"));
214+ }
215+ cx.notify();
216+ });
47 }217 }
48 218
49 fn sorted_aps(app: &AppRoot) -> Vec<AccessPoint> {219 fn sorted_aps(app: &AppRoot) -> Vec<AccessPoint> {
50 let mut rows: Vec<AccessPoint> = app.state.aps.values().cloned().collect();220 let mut rows: Vec<AccessPoint> = app.state.aps.values().cloned().collect();
51 if let Some(sort) = app.ap_sort {221 if let Some(sort) = app.ap_sort {
222+ let labels = &app.state.labels;
52 let ord = |l: &AccessPoint, r: &AccessPoint| match sort.column {223 let ord = |l: &AccessPoint, r: &AccessPoint| match sort.column {
53 COL_BSSID => l.bssid.cmp(&r.bssid),224 COL_BSSID => l.bssid.cmp(&r.bssid),
54 COL_SSID => l.ssid.cmp(&r.ssid).then_with(|| l.bssid.cmp(&r.bssid)),225 COL_SSID => l.ssid.cmp(&r.ssid).then_with(|| l.bssid.cmp(&r.bssid)),
226+ COL_LABEL => labels
227+ .get(&l.bssid)
228+ .cmp(&labels.get(&r.bssid))
229+ .then_with(|| l.bssid.cmp(&r.bssid)),
55 COL_CH => l.channel.cmp(&r.channel),230 COL_CH => l.channel.cmp(&r.channel),
231+ COL_BAND => band(l.channel).cmp(band(r.channel)),
56 COL_SEC => l.security.label().cmp(r.security.label()),232 COL_SEC => l.security.label().cmp(r.security.label()),
57 COL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm),233 COL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm),
58 COL_BEACONS => l.beacons.cmp(&r.beacons),234 COL_BEACONS => l.beacons.cmp(&r.beacons),
@@ -70,9 +246,26 @@ fn sorted_aps(app: &AppRoot) -> Vec<AccessPoint> {
70 fn sorted_clients(app: &AppRoot) -> Vec<ClientInfo> {246 fn sorted_clients(app: &AppRoot) -> Vec<ClientInfo> {
71 let mut rows: Vec<ClientInfo> = app.state.clients.values().cloned().collect();247 let mut rows: Vec<ClientInfo> = app.state.clients.values().cloned().collect();
72 if let Some(sort) = app.client_sort {248 if let Some(sort) = app.client_sort {
249+ let labels = &app.state.labels;
73 let ord = |l: &ClientInfo, r: &ClientInfo| match sort.column {250 let ord = |l: &ClientInfo, r: &ClientInfo| match sort.column {
74 CCOL_MAC => l.mac.cmp(&r.mac),251 CCOL_MAC => l.mac.cmp(&r.mac),
75- CCOL_AP => l.ap.cmp(&r.ap),252+ CCOL_STATE => l.connected.cmp(&r.connected),
253+ CCOL_LABEL => labels
254+ .get(&l.mac)
255+ .cmp(&labels.get(&r.mac))
256+ .then_with(|| l.mac.cmp(&r.mac)),
257+ CCOL_AP => {
258+ // Sort by what the column shows: the AP's SSID (bssid falls
259+ // back behind named entries, ties on raw MAC).
260+ let key = |c: &ClientInfo| {
261+ c.ap
262+ .and_then(|b| app.state.aps.get(&b))
263+ .filter(|a| !a.ssid.is_empty())
264+ .map(|a| a.ssid.to_lowercase())
265+ .unwrap_or_else(|| "\u{10ffff}".into())
266+ };
267+ key(l).cmp(&key(r)).then_with(|| l.ap.cmp(&r.ap))
268+ }
76 CCOL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm),269 CCOL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm),
77 CCOL_FRAMES => l.frames.cmp(&r.frames),270 CCOL_FRAMES => l.frames.cmp(&r.frames),
78 CCOL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(),271 CCOL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(),
@@ -83,6 +276,11 @@ fn sorted_clients(app: &AppRoot) -> Vec<ClientInfo> {
83 SortDirection::Descending => ord(l, r).reverse(),276 SortDirection::Descending => ord(l, r).reverse(),
84 });277 });
85 }278 }
279+ // Disconnected (deauth-flagged) stations sink below every connected
280+ // row regardless of the active sort — the state column answers "what
281+ // is still here", the partition is the answer at a glance. Stable
282+ // sort keeps the user-chosen order within each group.
283+ rows.sort_by_key(|c| !c.connected);
86 rows284 rows
87 }285 }
88 286
@@ -97,7 +295,14 @@ fn ap_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<AccessPoint> {
97 move |_window, cx| {295 move |_window, cx| {
98 view.update(cx, |app, cx| {296 view.update(cx, |app, cx| {
99 app.selected = Some(bssid);297 app.selected = Some(bssid);
298+ // Keep the target's AP row for the Attacks card —
299+ // the live record can vanish (host-capture mode
300+ // never re-scans), the snapshot holds.
301+ if let Some(row) = app.state.aps.get(&bssid) {
302+ app.selected_ap = Some(row.clone());
303+ }
100 app.selected_client = None;304 app.selected_client = None;
305+ prefill_label(app, bssid, cx);
101 app.state.push_log(format!("target selected: {bssid}"));306 app.state.push_log(format!("target selected: {bssid}"));
102 cx.notify();307 cx.notify();
103 });308 });
@@ -106,6 +311,9 @@ fn ap_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<AccessPoint> {
106 })311 })
107 .collect::<Vec<_>>();312 .collect::<Vec<_>>();
108 313
314+ let rogues = app.state.rogue_ssids.clone();
315+ let rssi_hist = app.state.rssi_hist.clone();
316+
109 table("networks-aps")317 table("networks-aps")
110 .column(318 .column(
111 Column::new("BSSID", |ap: &AccessPoint, _w, _cx| {319 Column::new("BSSID", |ap: &AccessPoint, _w, _cx| {
@@ -114,14 +322,50 @@ fn ap_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<AccessPoint> {
114 .sortable()322 .sortable()
115 .min_width(px(150.)),323 .min_width(px(150.)),
116 )324 )
117- .column(325+ .column({
118- Column::new("SSID", |ap: &AccessPoint, _w, _cx| {326+ let rogues = rogues.clone();
119- div().child(ap.ssid.clone()).into_any_element()327+ Column::new("SSID", move |ap: &AccessPoint, _w, _cx| {
328+ let mut cell = h_stack().gap_2().items_center().child(div().child(
329+ if ap.ssid.is_empty() {
330+ "<hidden>".to_string()
331+ } else {
332+ ap.ssid.clone()
333+ },
334+ ));
335+ if !ap.ssid.is_empty() && rogues.contains(&norm_ssid(&ap.ssid)) {
336+ cell = cell.child(badge("rogue?").destructive());
337+ }
338+ // Weak-encryption marker: Open/WEP is a liability everyone
339+ // in range should notice straight away.
340+ if matches!(ap.security, Security::Open | Security::Wep) {
341+ cell = cell.child(badge("weak").destructive());
342+ }
343+ cell.into_any_element()
120 })344 })
121 .sortable()345 .sortable()
122 .flex(2.0)346 .flex(2.0)
123- .min_width(px(120.)),347+ .min_width(px(120.))
348+ })
349+ .column(
350+ Column::new("VENDOR", |ap: &AccessPoint, _w, _cx| {
351+ div().child(vendor_of(&ap.bssid)).into_any_element()
352+ })
353+ .flex(1.0)
354+ .min_width(px(90.)),
124 )355 )
356+ .column({
357+ // Snapshot per render pass (the table is rebuilt with fresh
358+ // state each time anyway).
359+ let labels = app.state.labels.clone();
360+ Column::new("LABEL", move |ap: &AccessPoint, _w, _cx| {
361+ div()
362+ .child(labels.get(&ap.bssid).cloned().unwrap_or_default())
363+ .into_any_element()
364+ })
365+ .sortable()
366+ .flex(1.0)
367+ .min_width(px(100.))
368+ })
125 .column(369 .column(
126 Column::new("CH", |ap: &AccessPoint, _w, _cx| {370 Column::new("CH", |ap: &AccessPoint, _w, _cx| {
127 div().child(ap.channel.to_string()).into_any_element()371 div().child(ap.channel.to_string()).into_any_element()
@@ -131,23 +375,50 @@ fn ap_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<AccessPoint> {
131 .end(),375 .end(),
132 )376 )
133 .column(377 .column(
134- Column::new("SEC", |ap: &AccessPoint, _w, _cx| {378+ Column::new("BAND", |ap: &AccessPoint, _w, _cx| {
135- sec_badge(ap.security).into_any_element()379+ div()
380+ .child(format!("{} GHz", band(ap.channel)))
381+ .into_any_element()
136 })382 })
137 .sortable()383 .sortable()
138- .fixed(px(110.))384+ .fixed(px(80.))
139- .align(CellAlign::Center),385+ .end(),
140 )386 )
141 .column(387 .column(
142- Column::new("RSSI", |ap: &AccessPoint, _w, _cx| {388+Column::new("SEC", |ap: &AccessPoint, _w, _cx| {
143- div()389+ // Fixed-width badge slot: the AKM text starts at the same x in
144- .child(format!("{} dBm", ap.rssi_dbm))390+ // every row regardless of badge-label width.
145- .into_any_element()391+ let badge_slot = div()
392+ .w(px(52.))
393+ .flex_none()
394+ .child(sec_badge_label(&sec_label(ap), ap.security));
395+ let joined = ap
396+ .akms
397+ .iter()
398+ .map(|a| a.label())
399+ .collect::<Vec<_>>()
400+ .join("+");
401+ let mut cell = h_stack().gap_1().items_center().child(badge_slot);
402+ if !joined.is_empty() {
403+ cell = cell
404+ .child(div().flex_none().whitespace_nowrap().child(small(joined)))
405+ .justify_start();
406+ }
407+ cell.into_any_element()
408+ })
409+ .sortable()
410+ .fixed(px(170.))
411+ .align(CellAlign::Center),
412+ )
413+ .column({
414+ let rssi_hist = rssi_hist.clone();
415+ Column::new("SIGNAL", move |ap: &AccessPoint, _w, cx| {
416+ sparkline(rssi_hist.get(&ap.bssid), cx.theme().accent())
146 })417 })
147 .sortable()418 .sortable()
148 .fixed(px(90.))419 .fixed(px(90.))
149- .end(),420+ .align(CellAlign::Center)
150- )421+ })
151 .column(422 .column(
152 Column::new("BEACONS", |ap: &AccessPoint, _w, _cx| {423 Column::new("BEACONS", |ap: &AccessPoint, _w, _cx| {
153 div().child(ap.beacons.to_string()).into_any_element()424 div().child(ap.beacons.to_string()).into_any_element()
@@ -192,12 +463,37 @@ fn client_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<ClientInfo> {
192 .selected(app.selected_client == Some(mac))463 .selected(app.selected_client == Some(mac))
193 .on_click(move |_window, cx| {464 .on_click(move |_window, cx| {
194 view.update(cx, |app, cx| {465 view.update(cx, |app, cx| {
195- if let Some(ap) = ap {466+ match ap {
196- app.selected = Some(ap);467+ // Mapped client: its AP becomes the target.
197- app.selected_client = Some(mac);468+ Some(ap) => {
198- app.state469+ app.selected = Some(ap);
199- .push_log(format!("target selected: {ap} (client {mac})"));470+ if let Some(row) = app.state.aps.get(&ap) {
200- cx.notify();471+ app.selected_ap = Some(row.clone());
472+ }
473+ app.selected_client = Some(mac);
474+ prefill_label(app, mac, cx);
475+ app.state
476+ .push_log(format!("target selected: {ap} (client {mac})"));
477+ cx.notify();
478+ }
479+ // Unmapped client (scanner never resolved the
480+ // association): keep the current target, target
481+ // the client at it for deauth.
482+ None if app.selected.is_some() => {
483+ let target = app.selected.expect("checked above");
484+ app.selected_client = Some(mac);
485+ prefill_label(app, mac, cx);
486+ app.state.push_log(format!(
487+ "client selected: {mac} (AP unmapped — deauth targets {target})"
488+ ));
489+ cx.notify();
490+ }
491+ None => {
492+ app.state.push_log(format!(
493+ "client {mac}: AP unknown — pick a target AP row first"
494+ ));
495+ cx.notify();
496+ }
201 }497 }
202 });498 });
203 })499 })
@@ -206,51 +502,121 @@ fn client_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<ClientInfo> {
206 502
207 table("networks-clients")503 table("networks-clients")
208 .column(504 .column(
209- Column::new("MAC", |cl: &ClientInfo, _w, _cx| {505+ Column::new("MAC", |cl: &ClientInfo, _w, cx| {
210- div().child(cl.mac.to_string()).into_any_element()506+ client_cell(cl, cl.mac.to_string(), cx)
211 })507 })
212 .sortable()508 .sortable()
213 .min_width(px(150.)),509 .min_width(px(150.)),
214 )510 )
215 .column(511 .column(
216- Column::new("AP", |cl: &ClientInfo, _w, _cx| {512+ Column::new("VENDOR", |cl: &ClientInfo, _w, cx| {
217- div()513+ client_cell(cl, vendor_of(&cl.mac).to_string(), cx)
218- .child(514+ })
219- cl.ap515+ .flex(1.0)
220- .map(|ap: MacAddr| ap.to_string())516+ .min_width(px(90.)),
221- .unwrap_or_else(|| "—".into()),517+ )
222- )518+ .column(
223- .into_any_element()519+ Column::new("STATE", |cl: &ClientInfo, _w, _cx| {
520+ conn_badge(cl).into_any_element()
224 })521 })
225 .sortable()522 .sortable()
226- .min_width(px(150.)),523+ .fixed(px(90.))
524+ .align(CellAlign::Center),
227 )525 )
526+ .column({
527+ let labels = app.state.labels.clone();
528+ Column::new("LABEL", move |cl: &ClientInfo, _w, cx| {
529+ client_cell(cl, labels.get(&cl.mac).cloned().unwrap_or_default(), cx)
530+ })
531+ .sortable()
532+ .flex(1.0)
533+ .min_width(px(100.))
534+ })
535+ .column({
536+ // BSSID → SSID resolution: "which network does this client
537+ // belong to" reads as a name, not a MAC.
538+ let ap_names: std::collections::BTreeMap<MacAddr, String> = app
539+ .state
540+ .aps
541+ .iter()
542+ .filter(|(_, a)| !a.ssid.is_empty())
543+ .map(|(b, a)| (*b, a.ssid.clone()))
544+ .collect();
545+ Column::new("AP", move |cl: &ClientInfo, _w, cx| {
546+ let Some(bssid) = cl.ap else {
547+ return client_cell(cl, "—".into(), cx);
548+ };
549+ match ap_names.get(&bssid) {
550+ None => client_cell(cl, bssid.to_string(), cx),
551+ Some(name) => {
552+ let mut cell = div().child(name.clone());
553+ if !cl.connected {
554+ cell = cell.text_color(cx.theme().fg_muted());
555+ }
556+ let sub = div()
557+ .text_color(cx.theme().fg_muted())
558+ .child(small(bssid.to_string()));
559+ v_stack().child(cell).child(sub).into_any_element()
560+ }
561+ }
562+ })
563+ .sortable()
564+ .min_width(px(150.))
565+ })
228 .column(566 .column(
229- Column::new("RSSI", |cl: &ClientInfo, _w, _cx| {567+ Column::new("RSSI", |cl: &ClientInfo, _w, cx| {
230- div()568+ client_cell(cl, format!("{} dBm", cl.rssi_dbm), cx)
231- .child(format!("{} dBm", cl.rssi_dbm))
232- .into_any_element()
233 })569 })
234 .sortable()570 .sortable()
235 .fixed(px(90.))571 .fixed(px(90.))
236 .end(),572 .end(),
237 )573 )
238 .column(574 .column(
239- Column::new("FRAMES", |cl: &ClientInfo, _w, _cx| {575+ Column::new("FRAMES", |cl: &ClientInfo, _w, cx| {
240- div().child(cl.frames.to_string()).into_any_element()576+ client_cell(cl, cl.frames.to_string(), cx)
241 })577 })
242 .sortable()578 .sortable()
243 .fixed(px(90.))579 .fixed(px(90.))
244 .end(),580 .end(),
245 )581 )
246 .column(582 .column(
247- Column::new("AGE", |cl: &ClientInfo, _w, _cx| {583+ Column::new("AGE", |cl: &ClientInfo, _w, cx| {
248- div().child(age(cl.last_seen_ms)).into_any_element()584+ client_cell(cl, age(cl.last_seen_ms), cx)
249 })585 })
250 .sortable()586 .sortable()
251 .fixed(px(70.))587 .fixed(px(70.))
252 .end(),588 .end(),
253 )589 )
590+ .column({
591+ // Device-group id + member count (`#1~ (2)`: group 1, "~" =
592+ // strong witness, two known MACs — the MAC-randomization
593+ // pairing). Confidence labels per `IdentConfidence::label`.
594+ let counts: std::collections::BTreeMap<u64, usize> = app
595+ .state
596+ .ident_groups
597+ .iter()
598+ .map(|(g, ms)| (*g, ms.len()))
599+ .collect();
600+ Column::new("ID", move |cl: &ClientInfo, _w, cx| {
601+ let Some(gid) = cl.ident_group else {
602+ return client_cell(cl, String::new(), cx);
603+ };
604+ let conf = cl.ident_conf.map(|c| c.label()).unwrap_or("");
605+ let n = counts.get(&gid).copied().unwrap_or(1);
606+ let body = if n > 1 {
607+ format!("#{gid}{conf} ({n})")
608+ } else {
609+ format!("#{gid}{conf}")
610+ };
611+ let mut cell = div().child(body);
612+ if n > 1 {
613+ cell = cell.text_color(cx.theme().accent());
614+ }
615+ cell.into_any_element()
616+ })
617+ .fixed(px(90.))
618+ .align(CellAlign::Center)
619+ })
254 .rows(rows)620 .rows(rows)
255 .sorted_by(app.client_sort)621 .sorted_by(app.client_sort)
256 .on_sort({622 .on_sort({
@@ -266,7 +632,218 @@ fn client_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<ClientInfo> {
266 .empty("No client stations observed")632 .empty("No client stations observed")
267 }633 }
268 634
269-pub fn render(app: &mut AppRoot, view: &Entity<AppRoot>, _window: &mut Window, _cx: &mut Context<AppRoot>) -> gpui::Div {635+/// Recently observed probe requests, newest first, capped at 300 rows.
636+fn probe_table(app: &AppRoot) -> Table<ProbeInfo> {
637+ let rows: Vec<ProbeInfo> = app.state.probes.iter().rev().take(300).cloned().collect();
638+ let rogues = app.state.rogue_ssids.clone();
639+
640+ table("networks-probes")
641+ .column(
642+ Column::new("CLIENT", |p: &ProbeInfo, _w, _cx| {
643+ div()
644+ .child(format!("{} ({})", p.client, vendor_of(&p.client)))
645+ .into_any_element()
646+ })
647+ .min_width(px(190.)),
648+ )
649+ .column({
650+ let rogues = rogues.clone();
651+ Column::new("SSID", move |p: &ProbeInfo, _w, cx| {
652+ match &p.ssid {
653+ Some(s) => {
654+ let mut cell = div().child(s.clone());
655+ if !s.is_empty() && rogues.contains(&norm_ssid(s)) {
656+ cell = cell.text_color(cx.theme().warning());
657+ }
658+ cell.into_any_element()
659+ }
660+ None => div().child("<any>").into_any_element(),
661+ }
662+ })
663+ .flex(2.0)
664+ .min_width(px(120.))
665+ })
666+ .column(
667+ Column::new("RSSI", |p: &ProbeInfo, _w, _cx| {
668+ div()
669+ .child(format!("{} dBm", p.rssi_dbm))
670+ .into_any_element()
671+ })
672+ .fixed(px(90.))
673+ .end(),
674+ )
675+ .column(
676+ Column::new("AGE", |p: &ProbeInfo, _w, _cx| {
677+ div().child(age(p.at_ms)).into_any_element()
678+ })
679+ .fixed(px(70.))
680+ .end(),
681+ )
682+ .rows(rows.into_iter().map(Row::new).collect::<Vec<_>>())
683+ .max_h(px(220.))
684+ .empty("No probe requests observed")
685+}
686+
687+/// Per-channel activity strip: one cell per observed channel with a small
688+/// progress bar scaled to the busiest channel. Hidden when idle. Used as
689+/// the fallback of [`channel_activity`] until the timeline has ≥2
690+/// snapshots.
691+fn channel_strip(app: &AppRoot) -> Option<gpui::AnyElement> {
692+ let mut stats = app.state.channel_stats.clone();
693+ if stats.is_empty() {
694+ return None;
695+ }
696+ stats.sort_by_key(|s| s.channel);
697+ let max_frames = stats.iter().map(|s| s.frames).max().unwrap_or(0);
698+ Some(
699+ h_stack()
700+ .gap_3()
701+ .items_center()
702+ .children(stats.into_iter().map(|s| {
703+ let frac = if max_frames < 1 {
704+ 0.0
705+ } else {
706+ s.frames as f32 / max_frames as f32
707+ };
708+ v_stack()
709+ .gap_1()
710+ .child(small(format!("ch{}", s.channel)))
711+ .child(progress(frac).width(px(60.)).height(px(4.)))
712+ .child(small(s.frames.to_string()))
713+ }))
714+ .into_any_element(),
715+ )
716+}
717+
718+/// Timeline over the static strip: one row per busiest channel (max 8),
719+/// each row a right-aligned run of per-snapshot frame-delta columns
720+/// (opacity = relative intensity). A channel hosting ≥4 APs gets a
721+/// crowded warning — overlapping BSSs eat each other's airtime.
722+fn channel_timeline(app: &AppRoot, theme: &gpuikit::theme::Theme) -> Option<gpui::AnyElement> {
723+ let tl = &app.state.chan_timeline;
724+ if tl.len() < 2 {
725+ return None;
726+ }
727+ const COLUMNS: usize = 45;
728+ const CROWD_WARN: usize = 4;
729+
730+ // Busiest channels by latest cumulative frame count.
731+ let latest = tl.back().expect("len checked");
732+ let mut busy: Vec<crate::common::ChannelStat> = latest.clone();
733+ busy.sort_by_key(|s| std::cmp::Reverse(s.frames));
734+ busy.truncate(8);
735+
736+ // AP count per channel → crowded-channel warning.
737+ let mut crowd: std::collections::HashMap<u8, usize> = std::collections::HashMap::new();
738+ for ap in app.state.aps.values() {
739+ if ap.channel > 0 {
740+ *crowd.entry(ap.channel).or_default() += 1;
741+ }
742+ }
743+
744+ let accent = theme.accent();
745+ let rows: Vec<gpui::AnyElement> = busy
746+ .iter()
747+ .filter_map(|b| {
748+ let ch = b.channel;
749+ // Frame series for this channel across snapshots the scanner
750+ // reported it in (missed snapshots are skipped, minor skew).
751+ let series: Vec<u64> = tl
752+ .iter()
753+ .filter_map(|snap| snap.iter().find(|s| s.channel == ch).map(|s| s.frames))
754+ .collect();
755+ let deltas: Vec<u64> = series
756+ .windows(2)
757+ .map(|w| w[1].saturating_sub(w[0]))
758+ .collect();
759+ if deltas.is_empty() {
760+ return None;
761+ }
762+ let max = deltas.iter().copied().max().unwrap_or(0).max(1) as f32;
763+ let shown: &[u64] = &deltas[deltas.len().saturating_sub(COLUMNS)..];
764+ let mut cols: Vec<gpui::Div> = Vec::with_capacity(COLUMNS);
765+ // Left-pad quiet history so rows align at the newest edge.
766+ for _ in 0..COLUMNS.saturating_sub(shown.len()) {
767+ cols.push(div().w(px(4.)).h(px(12.)));
768+ }
769+ for &d in shown {
770+ let a = 0.15 + 0.85 * (d as f32 / max);
771+ cols.push(div().w(px(4.)).h(px(12.)).bg(accent.opacity(a)));
772+ }
773+ let crowd_n = *crowd.get(&ch).unwrap_or(&0);
774+ let mut label = div().w(px(80.)).flex_none().text_xs();
775+ let label_text = if crowd_n >= CROWD_WARN {
776+ format!("ch{ch} ⚠{crowd_n} APs")
777+ } else {
778+ format!("ch{ch}")
779+ };
780+ if crowd_n >= CROWD_WARN {
781+ label = label.text_color(theme.warning());
782+ } else {
783+ label = label.text_color(theme.fg_muted());
784+ }
785+ let last_delta = *deltas.last().unwrap_or(&0);
786+ Some(
787+ h_stack()
788+ .gap_2()
789+ .items_center()
790+ .child(label.child(label_text))
791+ .child(h_stack().items_end().children(cols))
792+ .child(
793+ div()
794+ .w(px(70.))
795+ .flex_none()
796+ .text_xs()
797+ .text_color(theme.fg_muted())
798+ .child(format!("{last_delta} fr")),
799+ )
800+ .into_any_element(),
801+ )
802+ })
803+ .collect();
804+ if rows.is_empty() {
805+ return None;
806+ }
807+ Some(
808+ v_stack()
809+ .gap_1()
810+ .child(small(format!(
811+ "channel activity — last {} snapshots (one column each), brightest = busiest",
812+ tl.len()
813+ )))
814+ .children(rows)
815+ .into_any_element(),
816+ )
817+}
818+
819+/// Channel activity visualization: scrolling timeline once ≥2 snapshots
820+/// exist, static strip before that, hidden when silent.
821+fn channel_activity(app: &AppRoot, theme: &gpuikit::theme::Theme) -> Option<gpui::AnyElement> {
822+ channel_timeline(app, theme).or_else(|| channel_strip(app))
823+}
824+
825+pub fn render(app: &mut AppRoot, view: &Entity<AppRoot>, _window: &mut Window, cx: &mut Context<AppRoot>) -> gpui::Div {
826+ // Persistent label editor: applies to the selected row (a selected
827+ // client wins over the selected AP — see [`label_target`]).
828+ let label_bar = label_target(app).map(|mac| {
829+ h_stack()
830+ .items_center()
831+ .gap_2()
832+ .child(small("label for"))
833+ .child(text(mac.to_string()).code().small().into_any_element())
834+ .child(
835+ div()
836+ .w(px(240.))
837+ .child(text_field(&app.label_input, cx).placeholder("name this device…")),
838+ )
839+ .child(button("btn-label-save", "Save").on_click({
840+ let view = view.clone();
841+ move |_, window, cx| save_label(&view, window, cx)
842+ }))
843+ .child(small("(empty saves as no label)"))
844+ .into_any_element()
845+ });
846+
270 v_stack()847 v_stack()
271 .size_full()848 .size_full()
272 .gap_3()849 .gap_3()
@@ -281,13 +858,23 @@ pub fn render(app: &mut AppRoot, view: &Entity<AppRoot>, _window: &mut Window, _
281 app.state.aps.len()858 app.state.aps.len()
282 ))),859 ))),
283 )860 )
861+ .children(label_bar)
862+ .children(channel_activity(app, cx.theme()))
284 .child(ap_table(app, view))863 .child(ap_table(app, view))
285 .child(864 .child(
286 gpuikit::layout::h_stack()865 gpuikit::layout::h_stack()
287 .items_center()866 .items_center()
288 .gap_3()867 .gap_3()
289 .child(h3("Clients"))868 .child(h3("Clients"))
290- .child(small(format!("{} stations", app.state.clients.len()))),869+ .child(small(client_counts(app))),
291 )870 )
292 .child(client_table(app, view))871 .child(client_table(app, view))
872+ .child(
873+ gpuikit::layout::h_stack()
874+ .items_center()
875+ .gap_3()
876+ .child(h3("Probes"))
877+ .child(small(format!("{} observed", app.state.probes.len()))),
878+ )
879+ .child(probe_table(app))
293 }880 }
src/ui/state.rsmodified+347 -4
@@ -1,9 +1,12 @@
1 //! Application state: the UI-side home for everything arriving over the1 //! Application state: the UI-side home for everything arriving over the
2 //! service event channel (mock thread or privileged-service reader).2 //! service event channel (mock thread or privileged-service reader).
3 3
4-use std::collections::{BTreeMap, VecDeque};4+use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
5 5
6-use crate::common::{AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture};6+use crate::common::{
7+ AccessPoint, ChannelStat, ClientInfo, Event, HandshakeCapture, IdentConfidence, MacAddr,
8+ PmkidCapture, ProbeInfo, Security,
9+};
7 use crate::crypto::CrackTarget;10 use crate::crypto::CrackTarget;
8 11
9 /// Ring capacity of the on-screen log.12 /// Ring capacity of the on-screen log.
@@ -22,6 +25,39 @@ pub struct CrackerState {
22 pub tried: u64,25 pub tried: u64,
23 /// Recovered password, once found.26 /// Recovered password, once found.
24 pub found: Option<String>,27 pub found: Option<String>,
28+ /// Rainbow-table build job in flight (RainbowProgress feeds the
29+ /// counters, RainbowBuilt clears the flag).
30+ pub rainbow_building: bool,
31+ /// PMKs written by the running build job.
32+ pub rainbow_done: u64,
33+ /// Build job throughput.
34+ pub rainbow_hps: f64,
35+ /// Worst-case candidate total of the running crack (wordlist lines /
36+ /// brute-force space / table entries), when countable.
37+ pub total: Option<u64>,
38+ /// Worst-case size of the table being built (wordlist lines).
39+ pub rainbow_total: Option<u64>,
40+ /// The currently running attack, tracked so the UI can persist a
41+ /// resume session ([`crate::store::CrackSession`]) without the
42+ /// worker's cooperation. Cleared when the run settles.
43+ pub active_attack: Option<crate::attack::Attack>,
44+ /// A saved, interrupted run matched against a loaded capture —
45+ /// shown as a resume banner on the cracker page.
46+ pub resume: Option<ResumeInfo>,
47+}
48+
49+/// Saved-run banner payload (mirror of [`crate::store::CrackSession`]
50+/// resolved to the capture's current description).
51+#[derive(Clone)]
52+pub struct ResumeInfo {
53+ /// Dropdown description of the capture this run belongs to.
54+ pub target_desc: String,
55+ /// Attack definition at the saved candidate offset.
56+ pub attack: crate::attack::Attack,
57+ /// Candidates already tried when the run was saved.
58+ pub done: u64,
59+ /// Worst-case total of the saved run, when countable.
60+ pub total: Option<u64>,
25 }61 }
26 62
27 /// Everything the window renders. Updated exclusively by63 /// Everything the window renders. Updated exclusively by
@@ -32,6 +68,10 @@ pub struct AppState {
32 pub ifname: String,68 pub ifname: String,
33 pub aps: BTreeMap<MacAddr, AccessPoint>,69 pub aps: BTreeMap<MacAddr, AccessPoint>,
34 pub clients: BTreeMap<MacAddr, ClientInfo>,70 pub clients: BTreeMap<MacAddr, ClientInfo>,
71+ /// User-assigned names by MAC (APs and clients share one namespace;
72+ /// a MAC is unique). Persisted to `~/wifilab/labels.json`
73+ /// ([`crate::store`]); UI-side only.
74+ pub labels: BTreeMap<MacAddr, String>,
35 pub handshakes: Vec<HandshakeCapture>,75 pub handshakes: Vec<HandshakeCapture>,
36 pub pmkids: Vec<PmkidCapture>,76 pub pmkids: Vec<PmkidCapture>,
37 /// [`capture_descs`]-aligned crack targets: `capture_targets()[i]` is77 /// [`capture_descs`]-aligned crack targets: `capture_targets()[i]` is
@@ -40,8 +80,59 @@ pub struct AppState {
40 capture_targets: Vec<CrackTarget>,80 capture_targets: Vec<CrackTarget>,
41 pub log: VecDeque<String>,81 pub log: VecDeque<String>,
42 pub cracker: CrackerState,82 pub cracker: CrackerState,
83+ /// Last per-channel frame/beacon counters snapshot
84+ /// ([`Event::ChannelStats`]).
85+ pub channel_stats: Vec<ChannelStat>,
86+ /// Observed probe requests, newest last.
87+ pub probes: VecDeque<ProbeInfo>,
88+ /// Recent RSSI samples per MAC (APs and clients keyed by their own
89+ /// MAC) — the Networks page renders these as sparklines.
90+ pub rssi_hist: HashMap<MacAddr, VecDeque<i8>>,
91+ /// Normalized (trim, lowercase) SSIDs observed on more than one BSSID
92+ /// with differing security — possible rogue APs.
93+ pub rogue_ssids: HashSet<String>,
94+ /// One-shot rogue-AP alert message; taken by the app drain into a toast.
95+ pub rogue_alert: Option<String>,
96+ /// One-shot deauth-storm alert message; taken by the app drain into a
97+ /// toast.
98+ pub deauth_alert: Option<String>,
99+ /// Last benchmark throughput (H/s); `None` = no GPU / not run yet.
100+ pub bench_gpu: Option<f64>,
101+ pub bench_cpu: Option<f64>,
102+ /// MAC-randomization pairing ([`Event::ClientIdent`]): device-group id +
103+ /// confidence per correlated MAC. Outlives the client row (groups keep
104+ /// their members while any one of them is live).
105+ pub idents: HashMap<MacAddr, (u64, IdentConfidence)>,
106+ /// Reverse view per group: set of currently-known member MACs (live
107+ /// rows + remembered) — the Networks page shows "N MACs" per device.
108+ pub ident_groups: HashMap<u64, HashSet<MacAddr>>,
109+ /// One-shot pairing alert ("device rotated MAC, paired into group #N");
110+ /// taken by the app drain into a toast.
111+ pub ident_alert: Option<String>,
112+ /// SSID (normalized) → BSSID → security seen, backing `rogue_ssids`.
113+ seen_ssids: BTreeMap<String, BTreeMap<MacAddr, Security>>,
114+ /// ChannelStats time-series, one entry per snapshot, oldest first
115+ /// (~3 min at the scanner's 2 s cadence) — the Networks page renders
116+ /// it as a scrolling per-channel activity timeline.
117+ pub chan_timeline: VecDeque<Vec<ChannelStat>>,
118+ /// Crack H/s samples, one per [`Event::CrackProgress`] of the current
119+ /// run (cleared at run start) — the Cracker page renders it as a
120+ /// throughput curve.
121+ pub hps_hist: VecDeque<f64>,
43 }122 }
44 123
124+/// Cap on [`AppState::probes`] (oldest dropped first).
125+const PROBE_CAP: usize = 2000;
126+
127+/// RSSI samples kept per MAC in [`AppState::rssi_hist`].
128+const RSSI_CAP: usize = 60;
129+
130+/// ChannelStats snapshots kept in [`AppState::chan_timeline`].
131+const CHAN_TL_CAP: usize = 90;
132+
133+/// H/s samples kept in [`AppState::hps_hist`].
134+const HPS_CAP: usize = 240;
135+
45 impl AppState {136 impl AppState {
46 pub fn new(ifname: &str) -> Self {137 pub fn new(ifname: &str) -> Self {
47 AppState {138 AppState {
@@ -49,12 +140,42 @@ impl AppState {
49 ifname: ifname.to_string(),140 ifname: ifname.to_string(),
50 aps: BTreeMap::new(),141 aps: BTreeMap::new(),
51 clients: BTreeMap::new(),142 clients: BTreeMap::new(),
143+ labels: BTreeMap::new(),
52 handshakes: Vec::new(),144 handshakes: Vec::new(),
53 pmkids: Vec::new(),145 pmkids: Vec::new(),
54 capture_targets: Vec::new(),146 capture_targets: Vec::new(),
55 log: VecDeque::with_capacity(LOG_CAP),147 log: VecDeque::with_capacity(LOG_CAP),
56 cracker: CrackerState::default(),148 cracker: CrackerState::default(),
149+ channel_stats: Vec::new(),
150+ probes: VecDeque::with_capacity(64),
151+ rssi_hist: HashMap::new(),
152+ rogue_ssids: HashSet::new(),
153+ rogue_alert: None,
154+ deauth_alert: None,
155+ bench_gpu: None,
156+ bench_cpu: None,
157+ idents: HashMap::new(),
158+ ident_groups: HashMap::new(),
159+ ident_alert: None,
160+ seen_ssids: BTreeMap::new(),
161+ chan_timeline: VecDeque::with_capacity(CHAN_TL_CAP + 1),
162+ hps_hist: VecDeque::with_capacity(HPS_CAP + 1),
163+ }
164+ }
165+
166+ /// Append one RSSI sample for `mac` (APs and clients keyed by their
167+ /// own MAC), capping the per-MAC history.
168+ fn note_rssi(&mut self, mac: MacAddr, rssi_dbm: i8) {
169+ let hist = self.rssi_hist.entry(mac).or_default();
170+ if hist.len() == RSSI_CAP {
171+ hist.pop_front();
57 }172 }
173+ hist.push_back(rssi_dbm);
174+ }
175+
176+ /// Normalize an SSID for rogue comparison (trim + lowercase).
177+ fn norm_ssid(ssid: &str) -> String {
178+ ssid.trim().to_lowercase()
58 }179 }
59 180
60 /// Crack target described by `capture_descs()[i]` (cloned — the cracker181 /// Crack target described by `capture_descs()[i]` (cloned — the cracker
@@ -63,6 +184,18 @@ impl AppState {
63 self.capture_targets.get(i).cloned()184 self.capture_targets.get(i).cloned()
64 }185 }
65 186
187+ /// The same capture as a [`crate::store::StoredCapture`] (resume
188+ /// session identity), `capture_descs()`-aligned like
189+ /// [`AppState::crack_target_at`]: handshakes first, then PMKIDs.
190+ pub fn stored_capture_at(&self, i: usize) -> Option<crate::store::StoredCapture> {
191+ if i < self.handshakes.len() {
192+ return Some(crate::store::StoredCapture::Handshake(self.handshakes[i].clone()));
193+ }
194+ self.pmkids
195+ .get(i - self.handshakes.len())
196+ .map(|p| crate::store::StoredCapture::Pmkid(p.clone()))
197+ }
198+
66 pub fn push_log(&mut self, line: impl Into<String>) {199 pub fn push_log(&mut self, line: impl Into<String>) {
67 if self.log.len() == LOG_CAP {200 if self.log.len() == LOG_CAP {
68 self.log.pop_front();201 self.log.pop_front();
@@ -73,8 +206,73 @@ impl AppState {
73 /// Reduce one service event into state. Returns `true` when the set of206 /// Reduce one service event into state. Returns `true` when the set of
74 /// crackable captures changed (callers rebuild dependent widgets).207 /// crackable captures changed (callers rebuild dependent widgets).
75 pub fn apply(&mut self, event: Event) -> bool {208 pub fn apply(&mut self, event: Event) -> bool {
209+ let changed = self.reduce(event);
210+ self.sweep_stale_clients();
211+ changed
212+ }
213+
214+ /// Backstop mirror of the scanner's 60 s client-expiry: rows learned
215+ /// before a scanner restart (the restart wipes the scanner's internal
216+ /// map, so no ClientLost can ever come for them) would linger as "up"
217+ /// forever without this. Clock-offset between the service and UI
218+ /// epochs (both `now_ms`, different process-local zero points) is a
219+ /// few seconds at most — negligible against a 60 s threshold.
220+ fn sweep_stale_clients(&mut self) {
221+ const UI_CLIENT_EXPIRE_MS: u64 = 60_000;
222+ let now = crate::common::now_ms();
223+ let swept: Vec<MacAddr> = self
224+ .clients
225+ .iter()
226+ .filter(|(_, c)| now.saturating_sub(c.last_seen_ms) > UI_CLIENT_EXPIRE_MS)
227+ .map(|(m, _)| *m)
228+ .collect();
229+ for m in swept {
230+ self.clients.remove(&m);
231+ self.forget_ident(&m);
232+ }
233+ }
234+
235+ /// Drop a MAC's pairing record (client row gone).
236+ fn forget_ident(&mut self, mac: &MacAddr) {
237+ if let Some((gid, _)) = self.idents.remove(mac) {
238+ if let Some(set) = self.ident_groups.get_mut(&gid) {
239+ set.remove(mac);
240+ if set.is_empty() {
241+ self.ident_groups.remove(&gid);
242+ }
243+ }
244+ }
245+ }
246+
247+ fn reduce(&mut self, event: Event) -> bool {
76 match event {248 match event {
77 Event::ApUpdated(ap) => {249 Event::ApUpdated(ap) => {
250+ self.note_rssi(ap.bssid, ap.rssi_dbm);
251+ // Rogue detection: the same non-empty SSID advertised by a
252+ // *different* BSSID with *different* security settings is
253+ // the classic evil-twin smell (same security on multi-AP
254+ // deployments is normal).
255+ let norm = Self::norm_ssid(&ap.ssid);
256+ if !norm.is_empty() {
257+ let entry = self.seen_ssids.entry(norm.clone()).or_default();
258+ if !self.rogue_ssids.contains(&norm) {
259+ let conflict = entry
260+ .iter()
261+ .find(|(b, sec)| **b != ap.bssid && **sec != ap.security);
262+ if let Some((known, sec1)) = conflict {
263+ self.rogue_ssids.insert(norm.clone());
264+ self.rogue_alert = Some(format!(
265+ "possible rogue AP: \"{}\" on {} ({}) vs {} ({})",
266+ norm,
267+ known,
268+ sec1.label(),
269+ ap.bssid,
270+ ap.security.label()
271+ ));
272+ }
273+ }
274+ entry.insert(ap.bssid, ap.security);
275+ }
78 self.aps.insert(ap.bssid, ap);276 self.aps.insert(ap.bssid, ap);
79 false277 false
80 }278 }
@@ -82,10 +280,49 @@ impl AppState {
82 self.aps.remove(&bssid);280 self.aps.remove(&bssid);
83 false281 false
84 }282 }
85- Event::ClientUpdated(client) => {283+ Event::ClientUpdated(mut client) => {
284+ self.note_rssi(client.mac, client.rssi_dbm);
285+ // Overlay the known pairing (the wire fields may lag or be
286+ // absent for clients learned before this process knew the
287+ // group).
288+ if let Some(&(gid, conf)) = self.idents.get(&client.mac) {
289+ client.ident_group = Some(gid);
290+ client.ident_conf = Some(conf);
291+ }
86 self.clients.insert(client.mac, client);292 self.clients.insert(client.mac, client);
87 false293 false
88 }294 }
295+ Event::ClientLost(mac) => {
296+ self.clients.remove(&mac);
297+ self.forget_ident(&mac);
298+ false
299+ }
300+ Event::ClientIdent { mac, group, confidence } => {
301+ let rotated = self
302+ .ident_groups
303+ .get(&group)
304+ .is_some_and(|ms| ms.iter().any(|m| *m != mac));
305+ self.idents.insert(mac, (group, confidence));
306+ self.ident_groups.entry(group).or_default().insert(mac);
307+ // Message names the whole rotation set — the actionable fact
308+ // is "these N MACs are one radio".
309+ let n = self.ident_groups.get(&group).map_or(1, |ms| ms.len());
310+ let msg = format!(
311+ "device paired: {mac} → group #{group} ({n} MAC{}) [{}]",
312+ if n == 1 { "" } else { "s" },
313+ confidence.label()
314+ );
315+ self.push_log(msg.clone());
316+ if rotated {
317+ self.ident_alert = Some(msg);
318+ }
319+ // Live row gets the badge immediately.
320+ if let Some(c) = self.clients.get_mut(&mac) {
321+ c.ident_group = Some(group);
322+ c.ident_conf = Some(confidence);
323+ }
324+ false
325+ }
89 Event::HandshakeProgress { ap, client, have } => {326 Event::HandshakeProgress { ap, client, have } => {
90 self.push_log(format!(327 self.push_log(format!(
91 "4-way {ap} → {client}: {}/4 messages",328 "4-way {ap} → {client}: {}/4 messages",
@@ -114,10 +351,15 @@ impl AppState {
114 self.push_log(format!("deauth: {count} frames → {target} (AP {ap})"));351 self.push_log(format!("deauth: {count} frames → {target} (AP {ap})"));
115 false352 false
116 }353 }
117- Event::CrackProgress { done, hps } => {354+ Event::CrackProgress { done, hps, total } => {
118 if self.cracker.running {355 if self.cracker.running {
119 self.cracker.tried = done;356 self.cracker.tried = done;
120 self.cracker.hps = hps;357 self.cracker.hps = hps;
358+ self.cracker.total = total;
359+ if self.hps_hist.len() == HPS_CAP {
360+ self.hps_hist.pop_front();
361+ }
362+ self.hps_hist.push_back(hps);
121 }363 }
122 false364 false
123 }365 }
@@ -134,6 +376,19 @@ impl AppState {
134 self.cracker.running = false;376 self.cracker.running = false;
135 true // force dependent-widget refresh so the cracker page updates promptly377 true // force dependent-widget refresh so the cracker page updates promptly
136 }378 }
379+ Event::RainbowProgress { done, hps, total } => {
380+ if self.cracker.rainbow_building {
381+ self.cracker.rainbow_done = done;
382+ self.cracker.rainbow_hps = hps;
383+ self.cracker.rainbow_total = total;
384+ }
385+ false
386+ }
387+ Event::RainbowBuilt { path, entries } => {
388+ self.push_log(format!("rainbow: table finished: {path} ({entries} PMKs)"));
389+ self.cracker.rainbow_building = false;
390+ false
391+ }
137 Event::Log(line) => {392 Event::Log(line) => {
138 self.push_log(line);393 self.push_log(line);
139 false394 false
@@ -142,6 +397,57 @@ impl AppState {
142 self.push_log(format!("ERROR: {line}"));397 self.push_log(format!("ERROR: {line}"));
143 false398 false
144 }399 }
400+ Event::ChannelStats(stats) => {
401+ if self.chan_timeline.len() == CHAN_TL_CAP {
402+ self.chan_timeline.pop_front();
403+ }
404+ self.chan_timeline.push_back(stats.clone());
405+ self.channel_stats = stats;
406+ false
407+ }
408+ Event::ProbeObserved(probe) => {
409+ self.note_rssi(probe.client, probe.rssi_dbm);
410+ if self.probes.len() == PROBE_CAP {
411+ self.probes.pop_front();
412+ }
413+ self.probes.push_back(probe);
414+ false
415+ }
416+ Event::BenchmarkDone { gpu_hps, cpu_hps } => {
417+ self.bench_gpu = gpu_hps;
418+ self.bench_cpu = Some(cpu_hps);
419+ self.push_log(format!(
420+ "benchmark: gpu {} H/s, cpu {} H/s",
421+ gpu_hps.map(|h| h.to_string()).unwrap_or_else(|| "none".to_string()),
422+ cpu_hps
423+ ));
424+ false
425+ }
426+ Event::DeauthAlert { source, target, count } => {
427+ let msg = format!("DEAUTH STORM: {source} → {target} x{count}");
428+ self.push_log(msg.clone());
429+ self.deauth_alert = Some(msg);
430+ false
431+ }
432+ Event::CaptureImported(cap) => {
433+ match cap {
434+ crate::common::ImportedCapture::Handshake(h) => {
435+ self.push_log(format!(
436+ "imported handshake: {} ({} ⇄ {})",
437+ h.essid, h.ap, h.client
438+ ));
439+ self.capture_targets
440+ .push(CrackTarget::Handshake(h.as_ref().clone()));
441+ self.handshakes.push(*h);
442+ }
443+ crate::common::ImportedCapture::Pmkid(p) => {
444+ self.push_log(format!("imported PMKID: {} ({})", p.essid, p.ap));
445+ self.capture_targets.push(CrackTarget::Pmkid(p.clone()));
446+ self.pmkids.push(p);
447+ }
448+ }
449+ true
450+ }
145 }451 }
146 }452 }
147 453
@@ -166,3 +472,40 @@ impl AppState {
166 out472 out
167 }473 }
168 }474 }
475+
476+#[cfg(test)]
477+mod tests {
478+ use super::*;
479+
480+ fn stat(ch: u8, frames: u64) -> ChannelStat {
481+ ChannelStat { channel: ch, frames, beacons: 0 }
482+ }
483+
484+ #[test]
485+ fn channel_timeline_keeps_snapshots_and_caps() {
486+ let mut s = AppState::new("wlan0");
487+ for i in 0..(CHAN_TL_CAP + 5) {
488+ s.apply(Event::ChannelStats(vec![stat(1, i as u64 + 1)]));
489+ }
490+ assert_eq!(s.chan_timeline.len(), CHAN_TL_CAP);
491+ // Oldest dropped: the first surviving snapshot is frames=6.
492+ assert_eq!(s.chan_timeline.front().unwrap()[0].frames, 6);
493+ assert_eq!(s.channel_stats[0].frames, (CHAN_TL_CAP + 5) as u64);
494+ }
495+
496+ #[test]
497+ fn hps_history_advances_only_while_running() {
498+ let mut s = AppState::new("wlan0");
499+ s.apply(Event::CrackProgress { done: 10, hps: 100.0, total: None });
500+ assert!(s.hps_hist.is_empty(), "stopped run must not feed the curve");
501+ s.cracker.running = true;
502+ s.apply(Event::CrackProgress { done: 20, hps: 200.0, total: Some(50) });
503+ s.apply(Event::CrackProgress { done: 30, hps: 300.0, total: Some(50) });
504+ assert_eq!(
505+ s.hps_hist.iter().copied().collect::<Vec<_>>(),
506+ vec![200.0, 300.0]
507+ );
508+ assert_eq!(s.cracker.tried, 30);
509+ assert_eq!(s.cracker.total, Some(50));
510+ }
511+}