From 1e4e538cbc9275ba46f00d505af76316e69f9444 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 14 Oct 2026 11:40:00 +0300 Subject: [PATCH] :sparkles: feat(ui): device columns + labels, persistent capture store, mode-rich cracker, desktop notify --- src/store.rs | 456 +++++++++++++++ src/ui/app.rs | 473 +++++++++++++-- src/ui/attacks.rs | 846 +++++++++++++++++++++++++-- src/ui/cracker.rs | 1375 +++++++++++++++++++++++++++++++++++++++++--- src/ui/log.rs | 73 ++- src/ui/mock.rs | 178 +++++- src/ui/mod.rs | 2 +- src/ui/networks.rs | 705 +++++++++++++++++++++-- src/ui/state.rs | 351 ++++++++++- 9 files changed, 4168 insertions(+), 291 deletions(-) create mode 100644 src/store.rs diff --git a/src/store.rs b/src/store.rs new file mode 100644 index 0000000..df44f03 --- /dev/null +++ b/src/store.rs @@ -0,0 +1,456 @@ +//! Persistent UI-side data under `~/wifilab`: +//! - `labels.json` — user-assigned names by MAC (APs and clients share one +//! namespace; a MAC is unique). +//! - `captures.jsonl` — every complete handshake / PMKID capture, one JSON +//! line each, appended as they arrive and reloaded at startup (the +//! cracker keeps working across restarts without re-attacking). +//! +//! UI-only data — the privileged service never touches it. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; + +use crate::common::{HandshakeCapture, MacAddr, PmkidCapture}; + +/// `~/wifilab` — falls back to `./wifilab` when HOME is unset. +pub fn data_dir() -> PathBuf { + std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(".")) + .join("wifilab") +} + +fn labels_path() -> PathBuf { + data_dir().join("labels.json") +} + +fn captures_path() -> PathBuf { + data_dir().join("captures.jsonl") +} + +fn session_path() -> PathBuf { + data_dir().join("crack-session.json") +} + +/// One persisted capture (tagged JSON line in `captures.jsonl`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum StoredCapture { + Handshake(HandshakeCapture), + Pmkid(PmkidCapture), +} + +impl StoredCapture { + /// Display identity used for dedup on load. + fn id(&self) -> String { + match self { + StoredCapture::Handshake(h) => format!("hs:{}:{}", h.ap, h.client), + StoredCapture::Pmkid(p) => format!("pmkid:{}", p.ap), + } + } +} + +fn load_labels_from(path: &Path) -> Result> { + let raw = match std::fs::read_to_string(path) { + Ok(s) => s, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Ok(BTreeMap::new()); + } + Err(e) => return Err(e).context("reading labels.json"), + }; + let by_str: BTreeMap = + serde_json::from_str(&raw).context("parsing labels.json")?; + let mut out = BTreeMap::new(); + for (mac, label) in by_str { + let mac: MacAddr = mac.parse().with_context(|| format!("bad MAC key {mac:?}"))?; + if !label.is_empty() { + out.insert(mac, label); + } + } + Ok(out) +} + +/// Load all labels; a missing file is an empty store, a corrupt one is an +/// error (callers log it and start empty rather than clobbering). +pub fn load() -> Result> { + load_labels_from(&labels_path()) +} + +fn save_labels_to(path: &Path, labels: &BTreeMap) -> Result<()> { + let dir = path.parent().expect("labels path has a parent"); + std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; + let by_str: BTreeMap = + labels.iter().map(|(mac, l)| (mac.to_string(), l)).collect(); + let body = serde_json::to_string_pretty(&by_str).expect("string map serialization"); + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, body).with_context(|| format!("writing {}", tmp.display()))?; + std::fs::rename(&tmp, path) + .with_context(|| format!("renaming {} → {}", tmp.display(), path.display())) +} + +/// Persist the whole label map (labels are few; rewriting is cheap and +/// atomic enough via write-to-tmp + rename). +pub fn save(labels: &BTreeMap) -> Result<()> { + save_labels_to(&labels_path(), labels) +} + +fn append_capture_to(path: &Path, cap: &StoredCapture) -> Result<()> { + let dir = path.parent().expect("captures path has a parent"); + std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; + use std::io::Write as _; + let mut f = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .with_context(|| format!("opening {}", path.display()))?; + let line = serde_json::to_string(cap).context("serializing capture")?; + writeln!(f, "{line}").with_context(|| format!("appending to {}", path.display())) +} + +/// Append one capture to `captures.jsonl`. Called the moment a capture +/// arrives — the file survives a crash right after. +pub fn append_capture(cap: &StoredCapture) -> Result<()> { + append_capture_to(&captures_path(), cap) +} + +fn load_captures_from(path: &Path) -> Result> { + let raw = match std::fs::read_to_string(path) { + Ok(s) => s, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(e).context("reading captures.jsonl"), + }; + let mut seen = std::collections::BTreeSet::new(); + let mut out = Vec::new(); + for (n, line) in raw.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + match serde_json::from_str::(line) { + Ok(cap) => { + if seen.insert(cap.id()) { + out.push(cap); + } + } + // One corrupt line must not kill the whole archive. + Err(e) => eprintln!("wifilab: skipping corrupt captures.jsonl line {}: {e}", n + 1), + } + } + Ok(out) +} + +/// Load every stored capture (deduped by AP/client identity). A corrupt +/// FILE is an error; individual corrupt lines are skipped. +pub fn load_captures() -> Result> { + load_captures_from(&captures_path()) +} + +// --------------------------------------------------------------------------- +// Crack session (resume): the interrupted run's position, so a later start +// — in this or a future session — continues instead of restarting. +// --------------------------------------------------------------------------- + +/// A stopped (not finished) crack run: which capture, which attack, how +/// far it had gotten. Written throttle-throttled on progress and once on +/// stop; deleted when the run finds the password or exhausts the space. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CrackSession { + pub capture: StoredCapture, + pub attack: crate::attack::Attack, + /// Candidates checked so far (resume skips/seeks past these). + pub done: u64, + /// Worst-case total of the run (see the ETA plumbing), when countable. + pub total: Option, +} + +fn save_session_to(path: &Path, session: &CrackSession) -> Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).context("creating ~/wifilab")?; + } + let json = serde_json::to_string_pretty(session).context("serializing crack session")?; + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, json).with_context(|| format!("writing {}", tmp.display()))?; + std::fs::rename(&tmp, path).with_context(|| format!("renaming {}", path.display()))?; + Ok(()) +} + +/// Persist the session (atomic-ish: write tmp + rename, like labels). +pub fn save_session(session: &CrackSession) -> Result<()> { + save_session_to(&session_path(), session) +} + +fn load_session_from(path: &Path) -> Result> { + match std::fs::read_to_string(path) { + Ok(s) => Ok(Some( + serde_json::from_str(&s).context("parsing crack-session.json")?, + )), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e).context("reading crack-session.json"), + } +} + +/// Load the saved session; `None` when no run was interrupted. A corrupt +/// file is an error (callers log it and start fresh rather than resuming +/// garbage). +pub fn load_session() -> Result> { + load_session_from(&session_path()) +} + +/// Drop the saved session (run found/exhausted, or user discarded). +/// Missing file is fine. +pub fn clear_session() -> Result<()> { + match std::fs::remove_file(session_path()) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e).context("removing crack-session.json"), + } +} + +// --------------------------------------------------------------------------- +// Per-SSID PMK cache: `~/wifilab/cache/.pmk` in rainbow text +// format — PMKs computed on earlier CPU runs are reusable for ANY capture +// of the same SSID without re-running PBKDF2. +// --------------------------------------------------------------------------- + +/// `~/wifilab/cache` — created on use by the cache readers/writers. +pub fn cache_dir() -> PathBuf { + data_dir().join("cache") +} + +/// Cache table path for one SSID: lowercase hex of the raw SSID bytes + +/// `.pmk` (filesystem-safe for arbitrary SSID encodings). +pub fn cache_file(ssid: &str) -> PathBuf { + let hex: String = ssid.bytes().map(|b| format!("{b:02x}")).collect(); + cache_dir().join(format!("{hex}.pmk")) +} + +// --------------------------------------------------------------------------- +// Crack profiles + recent wordlists (`~/wifilab/profiles.json`): user-saved +// attack setups for one-click reuse on the cracker page. +// --------------------------------------------------------------------------- + +/// One saved attack setup (mode/wl/rules as the cracker page fields). +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct CrackProfile { + pub name: String, + pub mode: String, + pub wordlist: String, + pub rules: Option, +} + +/// The whole profiles file: saved presets + MRU wordlist list (cap 5). +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct Profiles { + pub profiles: Vec, + pub recent_wordlists: Vec, +} + +fn profiles_path() -> PathBuf { + data_dir().join("profiles.json") +} + +fn load_profiles_from(path: &Path) -> Result { + match std::fs::read_to_string(path) { + Ok(s) => match serde_json::from_str::(&s) { + Ok(p) => Ok(p), + Err(e) => { + eprintln!("wifilab: profiles.json unreadable ({e}), starting fresh"); + Ok(Profiles::default()) + } + }, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Profiles::default()), + Err(e) => Err(e).context("reading profiles.json"), + } +} + +/// Load profiles; missing or unparseable file starts empty (never clobbers). +pub fn load_profiles() -> Result { + load_profiles_from(&profiles_path()) +} + +fn save_profiles_to(path: &Path, p: &Profiles) -> Result<()> { + let dir = path.parent().expect("profiles path has a parent"); + std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; + let body = serde_json::to_string_pretty(p).context("serializing profiles")?; + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, body).with_context(|| format!("writing {}", tmp.display()))?; + std::fs::rename(&tmp, path) + .with_context(|| format!("renaming {} → {}", tmp.display(), path.display())) +} + +/// Persist profiles (atomic-ish: write tmp + rename, like labels). +pub fn save_profiles(p: &Profiles) -> Result<()> { + save_profiles_to(&profiles_path(), p) +} + +/// MRU-insert a wordlist path at the front of `recent_wordlists`, deduped, +/// capped at 5. +pub fn remember_wordlist(p: &mut Profiles, path: &str) { + p.recent_wordlists.retain(|w| w != path); + p.recent_wordlists.insert(0, path.to_string()); + p.recent_wordlists.truncate(5); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tmp(name: &str) -> PathBuf { + std::env::temp_dir().join(format!("wifilab-store-test-{}-{name}", std::process::id())) + } + + #[test] + fn labels_roundtrip() { + let dir = tmp("labels"); + let path = dir.join("labels.json"); + let mac: MacAddr = "aa:bb:cc:dd:ee:ff".parse().unwrap(); + let mut labels = BTreeMap::new(); + labels.insert(mac, "living room".to_string()); + save_labels_to(&path, &labels).unwrap(); + let back = load_labels_from(&path).unwrap(); + assert_eq!(back.get(&mac).map(String::as_str), Some("living room")); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn labels_missing_file_is_empty() { + let back = load_labels_from(&tmp("nope").join("labels.json")).unwrap(); + assert!(back.is_empty()); + } + + #[test] + fn session_roundtrip_and_missing() { + let dir = tmp("session"); + let path = dir.join("crack-session.json"); + assert!(load_session_from(&path).unwrap().is_none()); + let session = CrackSession { + capture: StoredCapture::Pmkid(PmkidCapture { + ap: "aa:bb:cc:dd:ee:ff".parse().unwrap(), + client: "11:22:33:44:55:66".parse().unwrap(), + essid: "parafin".into(), + pmkid: [7u8; 16], + }), + attack: crate::attack::Attack::Bruteforce { + charset: b"01".to_vec(), + min: 8, + max: 10, + freq_order: true, + }, + done: 12_345, + total: Some(1_114_100), + }; + save_session_to(&path, &session).unwrap(); + let back = load_session_from(&path).unwrap().expect("saved"); + assert_eq!(back, session); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn captures_append_and_load_dedups() { + let dir = tmp("caps"); + let path = dir.join("captures.jsonl"); + let pm = PmkidCapture { + ap: "aa:bb:cc:dd:ee:ff".parse().unwrap(), + client: "11:22:33:44:55:66".parse().unwrap(), + essid: "parafin".into(), + pmkid: [7u8; 16], + }; + let hs = HandshakeCapture::new( + "aa:bb:cc:dd:ee:ff".parse().unwrap(), + "11:22:33:44:55:66".parse().unwrap(), + "parafin".into(), + [1u8; 32], + [2u8; 32], + [3u8; 16], + vec![9u8; 8], + 2, + ); + let cap_pm = StoredCapture::Pmkid(pm.clone()); + let cap_hs = StoredCapture::Handshake(hs.clone()); + append_capture_to(&path, &cap_pm).unwrap(); + append_capture_to(&path, &cap_pm).unwrap(); // duplicate line on disk + append_capture_to(&path, &cap_hs).unwrap(); + // One corrupt line must not kill the rest. + std::fs::write( + &path, + format!("{}{{not json}}\n", std::fs::read_to_string(&path).unwrap()), + ) + .unwrap(); + let back = load_captures_from(&path).unwrap(); + assert_eq!(back, vec![cap_pm, cap_hs]); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn captures_missing_file_is_empty() { + let back = load_captures_from(&tmp("nope").join("captures.jsonl")).unwrap(); + assert!(back.is_empty()); + } + + #[test] + fn profiles_roundtrip_and_missing() { + let dir = tmp("profiles"); + let path = dir.join("profiles.json"); + // Missing file = empty store. + assert_eq!(load_profiles_from(&path).unwrap().profiles.len(), 0); + let mut p = Profiles { + profiles: vec![ + CrackProfile { + name: "wl:rockyou".into(), + mode: "wordlist".into(), + wordlist: "/usr/share/wordlists/rockyou.txt".into(), + rules: None, + }, + CrackProfile { + name: "rules:corp".into(), + mode: "rules".into(), + wordlist: "/home/x/wl.txt".into(), + rules: Some("/home/x/best64.rule".into()), + }, + ], + recent_wordlists: vec!["/a.txt".into(), "/b.txt".into()], + }; + p.recent_wordlists.insert(0, "/c.txt".into()); + save_profiles_to(&path, &p).unwrap(); + let back = load_profiles_from(&path).unwrap(); + assert_eq!(back.profiles.len(), 2); + assert_eq!(back.profiles[0].name, "wl:rockyou"); + assert_eq!(back.profiles[1].rules.as_deref(), Some("/home/x/best64.rule")); + assert_eq!(back.recent_wordlists, p.recent_wordlists); + // Unparseable file = empty store, no error (never clobbered). + std::fs::write(&path, "{{not json").unwrap(); + let back = load_profiles_from(&path).unwrap(); + assert!(back.profiles.is_empty() && back.recent_wordlists.is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn remember_wordlist_front_insert_dedup_cap5() { + let mut p = Profiles::default(); + for w in ["/a", "/b", "/c", "/d", "/e", "/a"] { + remember_wordlist(&mut p, w); + } + // "/a" re-remembered: moves to front, no duplicate. + assert_eq!(p.recent_wordlists, vec!["/a", "/e", "/d", "/c", "/b"]); + // Sixth distinct path evicts the oldest. + remember_wordlist(&mut p, "/f"); + assert_eq!(p.recent_wordlists, vec!["/f", "/a", "/e", "/d", "/c"]); + } + + #[test] + fn cache_file_hex_naming() { + let p = cache_file("parafin"); + assert_eq!( + p.file_name().unwrap().to_str().unwrap(), + "7061726166696e.pmk" + ); + // Hex is lowercase and 2 chars per byte; non-ASCII bytes safe. + let p2 = cache_file("aé"); + assert_eq!(p2.file_name().unwrap().to_str().unwrap(), "61c3a9.pmk"); + assert_eq!(p.parent().unwrap(), cache_dir()); + } +} + diff --git a/src/ui/app.rs b/src/ui/app.rs index c216965..76b0065 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -3,7 +3,9 @@ //! task that polls the service event channel. use std::collections::BTreeMap; -use std::time::Duration; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; use crossbeam_channel::{Receiver, Sender}; use gpui::{ @@ -19,8 +21,9 @@ use gpuikit::elements::toast::ToastExt; use gpuikit::input::InputState; use gpuikit::layout::{h_stack, v_stack}; use gpuikit::theme::{ActiveTheme, Themeable}; +use gpuikit::traits::disableable::Disableable; -use crate::common::{Cmd, Event, MacAddr}; +use crate::common::{AccessPoint, Cmd, Event, MacAddr}; use crate::service::ServiceClient; use crate::ui::{attacks, cracker, log as log_view, networks, state::AppState}; @@ -47,6 +50,15 @@ impl Page { Page::Log => "Log", } } + + /// Startup page override (`WIFILAB_PAGE=attacks`) — dev/visual-verification + /// hook; unknown values fall through to Networks. + fn from_name(name: &str) -> Option { + Page::ALL + .iter() + .copied() + .find(|p| p.label().eq_ignore_ascii_case(name)) + } } pub struct AppRoot { @@ -56,18 +68,26 @@ pub struct AppRoot { /// UI-triggered actions are injected into the same pipeline. pub tx: Sender, pub page: Page, - /// Privilege indicator; real value from [`crate::iface::is_root`]. - /// Informational only — the UI never needs root itself; the service - /// elevates via polkit when it spawns. + /// UI-process privilege ([`crate::iface::is_root`]); the header badge + /// combines this with `service` presence to show the SERVICE's + /// privilege state — any running service is root (direct spawn or + /// pkexec). pub is_root: bool, - /// Privileged radio service client (owns the child process + the - /// UI-side cracker stop flag). `None` in mock mode or before the - /// first "Start capture". Kept across stop/start cycles. + /// Privileged radio service client (owns the child process). `None` + /// in mock mode or before the first "Start capture". Kept across + /// stop/start cycles. NOT involved in cracking — crack jobs are + /// UI-process threads tracked via [`AppRoot::crack_stop`]. pub service: Option, /// Mock data mode (`--mock` / `WIFILAB_MOCK=1`): never touches devices. pub is_mock: bool, /// Target BSSID picked on the Networks page (AP row or client row). pub selected: Option, + /// Last-known AP row for [`AppRoot::selected`], snapshotted at click + /// time and refreshed whenever the live record updates. The Attacks + /// page builds its target card from this even when the live row is + /// momentarily absent (host-capture mode never re-scans: a target + /// picked before the lock may have no AP row at all). + pub selected_ap: Option, /// Client station picked on the Networks page; deauth targets it /// instead of the broadcast address when set (AP stays `selected`). pub selected_client: Option, @@ -77,11 +97,24 @@ pub struct AppRoot { /// "Spinner shown" flags for attack buttons awaiting results. pub attacking_handshake: bool, pub attacking_pmkid: bool, + /// Channels the scanner is parked on for attacks (restricted StartScan + /// plan; several entries cover dual-band targets). `None` = full hop + /// list. Blanket spectrum-wide hopping makes capture/PMKID/deauth + /// mostly deaf and blind to one band. + pub parked_channels: Option>, /// Crack run in flight; cleared when CrackStopped arrives. pub crack_inflight: bool, - /// Toast queued by the event loop (no Window there) — shown on the - /// next render pass. - pub pending_toast: Option, + /// Stop flag of the running crack job (UI-process thread, see + /// [`crate::attack`]); flipped by Stop and on window close. + pub crack_stop: Option>, + /// Stop flag of the running rainbow-table build job. + pub rainbow_stop: Option>, + /// Throttle for resume-session writes (see [`AppRoot::maybe_save_crack_session`]). + pub last_session_save: Instant, + /// Toasts queued by the event loop (no Window there) — shown on the + /// next render pass. Capped (oldest dropped) so a burst of alerts + /// can't bury the window. + pub pending_toast: std::collections::VecDeque, /// NetworkManager seen active when capture started (fights channels). pub nm_active: bool, /// Used to invalidate stale cracker simulation ticks after Stop/re-Start. @@ -92,7 +125,49 @@ pub struct AppRoot { pub iface_select: Entity>, pub target_select: Entity>, pub wordlist_input: Entity, + /// Cracker attack-mode picker ([`crate::attack::Attack`]: wordlist / + /// bruteforce / rainbow). + pub attack_select: Entity>, + /// Selected attack mode value ("wordlist" | "bruteforce" | "rainbow"). + pub attack_mode: String, + /// Bruteforce preset chips ([`crate::attack::charset`]): unioned with + /// the custom field into the effective charset. + pub cs_lower: bool, + pub cs_upper: bool, + pub cs_digits: bool, + pub cs_special: bool, + /// Bruteforce mode inputs: charset and min/max word length. + pub charset_input: Entity, + pub len_min_input: Entity, + pub len_max_input: Entity, + /// Rainbow mode: PMK table path; the build job writes it, the run + /// reads it. + pub rainbow_input: Entity, pub deauth_input: Entity, + /// Networks-page label editor; the labels themselves live in + /// `state.labels` ([`crate::store`]). + pub label_input: Entity, + /// Log page body: read-only multiline input so log text is + /// mouse-selectable / Ctrl-C-copyable (plain text widgets aren't). + pub log_input: Entity, + /// Rules-attack mode: hashcat-style rule file path. + pub rules_input: Entity, + /// Crack-time estimator candidate (how strong might the password be). + pub strength_input: Entity, + /// Hybrid mode: appended-suffix length bounds. + pub hyb_min_input: Entity, + pub hyb_max_input: Entity, + /// Bruteforce charset ordering: most-common characters first. + pub freq_order: bool, + /// A throughput benchmark run is in flight. + pub bench_running: bool, + /// A capture-file import is in flight. + pub import_busy: bool, + /// Target count behind the "Deauth all clients (N)" button label + /// (0 = hidden); computed during attack-page render prep. + pub deauth_all_targets: usize, + /// Saved cracking presets + recent wordlists (~/wifilab/profiles.json). + pub profiles: crate::store::Profiles, } impl AppRoot { @@ -141,21 +216,73 @@ impl AppRoot { input.set_content("16", cx); }); + let label_input = cx.new(InputState::new_singleline); + let log_input = cx.new(|cx| InputState::new_multiline(cx).read_only(true)); + + let attack_select = cx.new(|_cx| { + SelectState::new( + select( + "cracker-attack", + "Attack", + vec![ + ("wordlist".to_string(), "wordlist".to_string()), + ("rules".to_string(), "rules".to_string()), + ("hybrid".to_string(), "hybrid".to_string()), + ("bruteforce".to_string(), "bruteforce".to_string()), + ("rainbow".to_string(), "rainbow".to_string()), + ], + ) + .selected("wordlist".to_string()) + .on_change({ + let view = view.clone(); + move |mode, _window, cx| { + view.update(cx, |app, cx| { + app.attack_mode = mode; + cx.notify(); + }); + } + }), + ) + }); + let charset_input = cx.new(InputState::new_singleline); + let len_min_input = cx.new(InputState::new_singleline); + len_min_input.update(cx, |input, cx| input.set_content("8", cx)); + let len_max_input = cx.new(InputState::new_singleline); + len_max_input.update(cx, |input, cx| input.set_content("10", cx)); + let rainbow_input = cx.new(InputState::new_singleline); + let rules_input = cx.new(InputState::new_singleline); + rules_input.update(cx, |input, cx| { + input.set_content("/path/to/rules (e.g. best64.rule)", cx); + }); + let strength_input = cx.new(InputState::new_singleline); + let hyb_min_input = cx.new(InputState::new_singleline); + hyb_min_input.update(cx, |input, cx| input.set_content("1", cx)); + let hyb_max_input = cx.new(InputState::new_singleline); + hyb_max_input.update(cx, |input, cx| input.set_content("2", cx)); + let mut this = AppRoot { state: AppState::new(&selected_iface), rx, tx, - page: Page::Networks, + page: std::env::var("WIFILAB_PAGE") + .ok() + .and_then(|p| Page::from_name(&p)) + .unwrap_or(Page::Networks), is_root: crate::iface::is_root(), service: None, is_mock, selected: None, + selected_ap: None, selected_client: None, hs_progress: BTreeMap::new(), attacking_handshake: false, attacking_pmkid: false, + parked_channels: None, crack_inflight: false, - pending_toast: None, + crack_stop: None, + rainbow_stop: None, + last_session_save: Instant::now(), + pending_toast: std::collections::VecDeque::new(), nm_active: false, crack_epoch: 0, ap_sort: None, @@ -167,9 +294,74 @@ impl AppRoot { SelectState::new(select("cracker-target", "Crack target", empty)) }), wordlist_input, + attack_select, + attack_mode: "wordlist".to_string(), + cs_lower: false, + cs_upper: false, + cs_digits: true, + cs_special: false, + charset_input, + len_min_input, + len_max_input, + rainbow_input, deauth_input, + label_input, + log_input, + rules_input, + strength_input, + hyb_min_input, + hyb_max_input, + freq_order: true, + bench_running: false, + import_busy: false, + deauth_all_targets: 0, + profiles: match crate::store::load_profiles() { + Ok(p) => p, + Err(e) => { + eprintln!("profiles: load failed, starting empty: {e:#}"); + crate::store::Profiles::default() + } + }, }; + match crate::store::load() { + Ok(labels) => { + let n = labels.len(); + this.state.labels = labels; + this.state + .push_log(format!("labels: {n} loaded from ~/wifilab/labels.json")); + } + Err(e) => this + .state + .push_log(format!("labels: load failed, starting empty: {e:#}")), + } + // Restore previous captures so the cracker can keep working across + // restarts without re-running attacks. + match crate::store::load_captures() { + Ok(caps) => { + let n = caps.len(); + for cap in caps { + match cap { + crate::store::StoredCapture::Handshake(h) => { + this.state.apply(Event::HandshakeComplete(Box::new(h))); + } + crate::store::StoredCapture::Pmkid(p) => { + this.state.apply(Event::PmkidCaptured(p)); + } + } + } + if n > 0 { + this.state + .push_log(format!("captures: {n} restored from ~/wifilab/captures.jsonl")); + } + } + Err(e) => this + .state + .push_log(format!("captures: restore failed: {e:#}")), + } this.rebuild_target_select(cx); + if !is_mock { + this.restore_crack_session(); + } this.state.push_log(if is_mock { "wifilab UI started (mock backend)".to_string() } else { @@ -179,9 +371,15 @@ impl AppRoot { }); cx.on_release(|this, _cx| { - // Window closed → root view released → shut the service down - // (it stops workers, restores managed mode, exits) and stop - // any UI-side crack job. + // Window closed → root view released → stop UI-process jobs + // (crack + rainbow build) and shut the service down (it stops + // workers, restores managed mode, exits). + for flag in [this.crack_stop.take(), this.rainbow_stop.take()] + .into_iter() + .flatten() + { + flag.store(true, Ordering::Relaxed); + } if let Some(svc) = this.service.take() { svc.shutdown(); } @@ -239,7 +437,11 @@ impl AppRoot { .push_log("ui: stopping capture, service restores managed mode…"); svc.stop_scan(); } + // Stopping also kills every attack worker — un-spin buttons. self.state.iface_running = false; + self.parked_channels = None; + self.attacking_handshake = false; + self.attacking_pmkid = false; cx.notify(); } else { // NetworkManager fight: pin-to-connected-channel makes ONLY the @@ -251,8 +453,8 @@ impl AppRoot { network's channel; you will likely see ONLY that SSID. Use \"Stop NM\" in the header." .to_string(), ); - self.pending_toast = Some( - "NetworkManager is active — only your connected network may be visible; stop it from the header".into(), + self.queue_toast( + "NetworkManager is active — only your connected network may be visible; stop it from the header", ); } let ifname = self.state.ifname.clone(); @@ -262,8 +464,11 @@ impl AppRoot { svc.cmd(&Cmd::StartScan { ifname: ifname.clone(), channels: None, + spool: Some(crate::store::data_dir().join("spool.pcap")), + fresh_spool: true, }); self.state.iface_running = true; + self.parked_channels = None; self.state .push_log(format!("ui: capture started on {ifname}")); cx.notify(); @@ -279,8 +484,7 @@ impl AppRoot { Err(e) => { self.state .push_log(format!("ERROR: start capture on {ifname}: {e:#}")); - self.pending_toast = - Some(format!("start capture failed: {e:#}").into()); + self.queue_toast(format!("start capture failed: {e:#}")); } } cx.notify(); @@ -305,6 +509,15 @@ impl AppRoot { cx.notify(); } + /// Queue a toast for the next render pass (the event loop has no + /// Window). Capped at 3 — oldest dropped first. + pub fn queue_toast(&mut self, msg: impl Into) { + if self.pending_toast.len() == 3 { + self.pending_toast.pop_front(); + } + self.pending_toast.push_back(msg.into()); + } + /// Drain every queued event, track handshake progress, refresh widgets /// derived from the capture set. fn drain_events(&mut self, cx: &mut Context) { @@ -319,9 +532,19 @@ impl AppRoot { Event::HandshakeComplete(cap) => { self.hs_progress.remove(&(cap.ap, cap.client)); self.attacking_handshake = false; + if let Err(e) = crate::store::append_capture( + &crate::store::StoredCapture::Handshake(cap.as_ref().clone()), + ) { + self.state.push_log(format!("capture save FAILED: {e:#}")); + } } - Event::PmkidCaptured(_) => { + Event::PmkidCaptured(cap) => { self.attacking_pmkid = false; + if let Err(e) = crate::store::append_capture( + &crate::store::StoredCapture::Pmkid(cap.clone()), + ) { + self.state.push_log(format!("capture save FAILED: {e:#}")); + } } // Service child died (EOF seen by the reader thread): // un-flip every running flag and drop the client so the @@ -343,10 +566,13 @@ impl AppRoot { self.attacking_handshake = false; self.attacking_pmkid = false; } + // Terminal attack-worker log lines un-spin the buttons. + // NOT a generic prefix match: "handshake: listening for + // 4-way…" fires right at worker start and would instantly + // kill the spinner while the worker runs. Event::Log(line) - if ["handshake:", "pmkid:"] - .iter() - .any(|p| line.starts_with(p)) => + if line.starts_with("handshake: capture ended") + || line.starts_with("pmkid: no PMKID") => { self.attacking_handshake = false; self.attacking_pmkid = false; @@ -355,22 +581,79 @@ impl AppRoot { Event::Log(line) if line.starts_with("nm:") => { if line == "nm: stopped" { self.nm_active = false; - self.pending_toast = Some( - "NetworkManager stopped — all networks become visible as the hopper cycles" - .into(), + self.queue_toast( + "NetworkManager stopped — all networks become visible as the hopper cycles", ); } } - Event::CrackStopped { .. } => { + Event::CrackProgress { .. } => { + self.maybe_save_crack_session(); + } + Event::CrackStopped { found } => { self.crack_inflight = false; + self.crack_stop = None; + self.finalize_crack_session(*found); + } + Event::RainbowBuilt { .. } => { + self.rainbow_stop = None; } Event::CrackFound { password } => { - self.pending_toast = - Some(format!("password recovered: {password}").into()); + self.queue_toast(format!("password recovered: {password}")); + // Best-effort desktop notification; headless/no-D-Bus + // just drops the error. + let _ = notify_rust::Notification::new() + .summary("wifilab: password found") + .body(&format!("password recovered: {password}")) + .show(); + } + Event::CaptureImported(cap) => { + let stored = match cap { + crate::common::ImportedCapture::Handshake(h) => { + crate::store::StoredCapture::Handshake(h.as_ref().clone()) + } + crate::common::ImportedCapture::Pmkid(p) => { + crate::store::StoredCapture::Pmkid(p.clone()) + } + }; + if let Err(e) = crate::store::append_capture(&stored) { + self.state + .push_log(format!("import: capture save FAILED: {e:#}")); + } + } + Event::BenchmarkDone { .. } => { + self.bench_running = false; } _ => {} } captures_changed |= self.state.apply(event); + if let Some(m) = self.state.deauth_alert.take() { + self.queue_toast(m); + } + if let Some(m) = self.state.rogue_alert.take() { + self.queue_toast(m); + } + if let Some(m) = self.state.ident_alert.take() { + self.queue_toast(m); + } + } + // Keep the target snapshot in lockstep with the live AP row (a + // click-time-only snapshot goes stale: channel jumps, beacon + // counts, security updates). Also self-heals after service + // restarts, when only the live row exists. + if let Some(live) = self + .selected + .and_then(|b| self.state.aps.get(&b).cloned()) + { + self.selected_ap = Some(live); + } + // Mock-only convenience: pre-select the first heard AP so the + // Attacks page shows its target card without a manual click — + // invaluable for headless UI verification. Never in real mode. + if self.is_mock && self.selected.is_none() { + if let Some((&b, _)) = self.state.aps.first_key_value() { + self.selected = Some(b); + self.selected_ap = self.state.aps.get(&b).cloned(); + } } if captures_changed { self.rebuild_target_select(cx); @@ -380,9 +663,115 @@ impl AppRoot { } } + /// Persist the interrupted crack run (resume file), throttled to one + /// write per 2 s of progress events. UI-thread only (called from the + /// event drain). + fn maybe_save_crack_session(&mut self) { + if self.last_session_save.elapsed() < Duration::from_secs(2) { + return; + } + self.last_session_save = Instant::now(); + self.save_crack_session(); + } + + /// Write the current run to ~/wifilab/crack-session.json. No-op when + /// nothing resumable is in flight (mock runs never persist). + fn save_crack_session(&mut self) { + let (Some(attack), Some(desc)) = ( + self.state.cracker.active_attack.clone(), + self.state.cracker.target.clone(), + ) else { + return; + }; + let done = self.state.cracker.tried; + if done == 0 { + return; + } + let Some(idx) = self + .state + .capture_descs() + .iter() + .position(|d| *d == desc) + else { + return; + }; + let Some(capture) = self.state.stored_capture_at(idx) else { + return; + }; + let total = self.state.cracker.total; + let session = crate::store::CrackSession { capture, attack, done, total }; + if let Err(e) = crate::store::save_session(&session) { + self.state.push_log(format!("cracker: session save failed: {e:#}")); + return; + } + // The just-saved run is resumable right now (same session or the + // next start): keep the banner in sync. + self.state.cracker.resume = Some(crate::ui::state::ResumeInfo { + target_desc: desc, + attack: session.attack, + done, + total, + }); + } + + /// Settle the session file when a run ends: found/exhausted → delete + /// (nothing left to resume); stopped mid-way → final save + banner. + fn finalize_crack_session(&mut self, found: bool) { + let done = self.state.cracker.tried; + let total = self.state.cracker.total; + let exhausted = !found && total.is_some_and(|t| done >= t); + if found || exhausted { + if let Err(e) = crate::store::clear_session() { + self.state.push_log(format!("cracker: session clear failed: {e:#}")); + } + self.state.cracker.resume = None; + } else if self.state.cracker.active_attack.is_some() { + // User-stopped (or worker-ended) with room left: persist the + // position — this is the whole point of the feature. + self.last_session_save = Instant::now(); + self.save_crack_session(); + } + self.state.cracker.active_attack = None; + } + + /// Match a saved session against the loaded captures on startup: + /// a match arms the resume banner on the cracker page. + fn restore_crack_session(&mut self) { + let session = match crate::store::load_session() { + Ok(Some(s)) => s, + Ok(None) => return, + Err(e) => { + self.state + .push_log(format!("cracker: saved session unreadable: {e:#}")); + return; + } + }; + let descs = self.state.capture_descs(); + let hit = descs.iter().enumerate().find(|(i, _)| { + self.state.stored_capture_at(*i).as_ref() == Some(&session.capture) + }); + match hit.map(|(_, d)| d) { + Some(d) => { + let done = session.done; + self.state.cracker.resume = Some(crate::ui::state::ResumeInfo { + target_desc: d.clone(), + attack: session.attack, + done, + total: session.total, + }); + self.state + .push_log(format!("cracker: resumable saved run restored ({d}, {done} tried)")); + } + None => self + .state + .push_log("cracker: saved session ignored — its capture is gone".to_string()), + } + } + /// The cracker target dropdown mirrors `state.capture_descs()`; rebuild /// it whenever a handshake/PMKID arrives, keeping the current choice if - /// it still exists. + /// it still exists. With no captures the select is disabled so its + /// (empty) popup cannot open. pub fn rebuild_target_select(&mut self, cx: &mut Context) { let descs = self.state.capture_descs(); let keep = self @@ -397,7 +786,12 @@ impl AppRoot { "Crack target", descs.iter().map(|d| (d.clone(), d.clone())).collect::>(), ) - .placeholder("Select a capture…") + .placeholder(if descs.is_empty() { + "no captures yet — capture a handshake or PMKID first" + } else { + "Select a capture…" + }) + .disabled(descs.is_empty()) .on_change(move |value, _window, cx| { view.update(cx, |app, cx| { app.state.cracker.target = Some(value); @@ -445,12 +839,17 @@ impl AppRoot { let theme = cx.theme().clone(); let running = self.state.iface_running; - let privilege = if self.is_root { - badge("root").secondary() - } else if self.is_mock { + // Status of the SERVICE process (the thing that actually touches + // the radio): any running service is root — spawned directly when + // the UI is root, via pkexec (root by definition) otherwise. + let privilege = if self.is_mock { badge("not root (mock)").secondary() + } else if self.service.is_some() { + badge("service: root").secondary() + } else if self.is_root { + badge("ui: root · service not started").secondary() } else { - badge("user (service will elevate)").secondary() + badge("ui: user · service not started").secondary() }; let toggle = button( @@ -558,7 +957,7 @@ impl Render for AppRoot { let view = cx.entity(); // Flush toasts queued by the event-drain loop (which has no Window). - if let Some(msg) = self.pending_toast.take() { + while let Some(msg) = self.pending_toast.pop_front() { cx.toast(msg).show(_window, cx); } diff --git a/src/ui/attacks.rs b/src/ui/attacks.rs index f94f2c2..fdfb989 100644 --- a/src/ui/attacks.rs +++ b/src/ui/attacks.rs @@ -16,7 +16,7 @@ use gpuikit::elements::typography::{h3, small, text}; use gpuikit::layout::{h_stack, v_stack}; use gpuikit::theme::{ActiveTheme, Themeable}; -use crate::common::{Cmd, Event, HandshakeCapture, MacAddr, PmkidCapture}; +use crate::common::{Akm, ClientInfo, Cmd, Event, HandshakeCapture, MacAddr, PmkidCapture}; use crate::ui::app::AppRoot; use crate::ui::mock; @@ -94,6 +94,53 @@ fn export_hc22000(view: &Entity, _window: &mut Window, cx: &mut gpui::A .detach(); } +/// Export the raw pcap spool (every frame the scanner saw since the +/// capture started) via the platform save dialog; falls back to a fixed +/// path under ./captures when the dialog is refused. +fn export_pcap(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + let spool = crate::store::data_dir().join("spool.pcap"); + if !spool.is_file() { + view.update(cx, |app, cx| { + app.state + .push_log("pcap export: no spool yet — start a capture first"); + cx.notify(); + }); + return; + } + + let suggested = format!("wifilab-{}.pcap", unix_secs()); + let prompt = cx.prompt_for_new_path(Path::new("./captures"), Some(&suggested)); + let weak = view.downgrade(); + cx.spawn(async move |cx| { + // Dialog refused/cancelled → fixed fallback; explicit cancel aborts. + let path: Option = match prompt.await { + Ok(Ok(Some(p))) => Some(p), + Ok(Ok(None)) => None, + _ => Some(PathBuf::from("./captures").join(&suggested)), + }; + let _ = weak.update(cx, |app, cx| { + match path { + None => app.state.push_log("pcap export: cancelled"), + Some(path) => { + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + match std::fs::copy(&spool, &path) { + Ok(n) => app + .state + .push_log(format!("pcap export: {n} bytes → {}", path.display())), + Err(e) => app + .state + .push_log(format!("pcap export FAILED: {e} ({})", path.display())), + } + } + } + cx.notify(); + }); + }) + .detach(); +} + /// Selected target with its current AP row (channel + essid). fn target_info(app: &AppRoot) -> Option<(MacAddr, u8, String)> { let ap = app.selected?; @@ -101,6 +148,115 @@ fn target_info(app: &AppRoot) -> Option<(MacAddr, u8, String)> { Some((ap, row.channel, row.ssid.clone())) } +/// The selected target's AP row for rendering: the live record wins; +/// otherwise the snapshot taken at click time (host-capture mode never +/// re-scans, so a valid target may have no live row at all). Second tuple +/// element is true when falling back to the (possibly stale) snapshot. +fn target_row(app: &AppRoot) -> Option<(&crate::common::AccessPoint, bool)> { + let sel = app.selected?; + if let Some(row) = app.state.aps.get(&sel) { + return Some((row, false)); + } + app.selected_ap.as_ref().map(|row| (row, true)) +} + +/// Material already captured for this AP (dual-band siblings count as +/// their own BSSIDs — a handshake grabbed on the 5 GHz twin crackable +/// for the same password, so count the whole ESSID family). +fn material_for(app: &AppRoot, ap: &crate::common::AccessPoint) -> (usize, usize) { + let essids = sibling_targets(app, &ap.ssid) + .into_iter() + .map(|(b, _)| b) + .collect::>(); + let hs = app + .state + .handshakes + .iter() + .filter(|h| essids.contains(&h.ap)) + .count(); + let pm = app + .state + .pmkids + .iter() + .filter(|p| essids.contains(&p.ap)) + .count(); + (hs, pm) +} + +/// One-line "best next move" for the selected target, computed from what +/// the scanner already knows — the answer to "which button do I press". +/// Second tuple element: true = actionable path, false = dead end (the +/// card colors accordingly). +fn advisor(app: &AppRoot, ap: &crate::common::AccessPoint) -> (&'static str, bool) { + use crate::common::Security; + let akms = &ap.akms; + let sae = !akms.is_empty() + && akms.contains(&Akm::Sae) + && !akms.contains(&Akm::Psk) + && !akms.contains(&Akm::PskSha256); + if sae { + return ( + "advice: SAE-only — no offline-crackable material exists (dead end for today)", + false, + ); + } + match ap.security { + Security::Open => return ("advice: open network — nothing to crack", false), + Security::Wep => { + return ( + "advice: WEP — ancient; out of scope here (use dedicated tools)", + false, + ); + } + _ => {} + } + if !akms.is_empty() && akms.contains(&Akm::Owe) && !akms.contains(&Akm::Psk) { + return ("advice: OWE (enhanced open) — no password to recover", false); + } + let (hs, pm) = material_for(app, ap); + if hs + pm > 0 { + return ( + "advice: capture material in hand — crack it on the Cracker page", + true, + ); + } + if sae_transition(akms) { + return ( + "advice: WPA3 transition (PSK still offered) — handshake capture or PMKID works", + true, + ); + } + if connected_clients(app, ap.bssid).is_empty() { + ( + "advice: no clients mapped — run PMKID first (clientless), then park a handshake capture", + true, + ) + } else { + ( + "advice: deauth a client while handshake capture runs — it re-auths with a fresh 4-way", + true, + ) + } +} + +fn sae_transition(akms: &[Akm]) -> bool { + akms.contains(&Akm::Sae) && (akms.contains(&Akm::Psk) || akms.contains(&Akm::PskSha256)) +} + +/// WPA3 SAE-only targets yield no offline-crackable material: the +/// dragonfly handshake can't be brute-forced offline and SAE APs never +/// hand out a PMKID. Transition-mode APs (PSK alongside SAE) still work. +fn sae_only(app: &AppRoot) -> bool { + let Some((row, _stale)) = target_row(app) else { + return false; + }; + let akms = &row.akms; + !akms.is_empty() + && akms.contains(&Akm::Sae) + && !akms.contains(&Akm::Psk) + && !akms.contains(&Akm::PskSha256) +} + /// Capture Handshake. /// Mock mode: drive a fresh fabricated 4-way through the event pipeline. /// Real mode: spawn the backend capture worker (channel probed first via @@ -125,18 +281,25 @@ fn capture_handshake(view: &Entity, _window: &mut Window, cx: &mut gpui cx.notify(); if !app.is_mock { - let Some((ap, channel, essid)) = target_info(app) else { + let Some((_sel_bssid, _sel_ch, essid)) = target_info(app) else { app.state .push_log("handshake: target AP not in scan table yet"); app.attacking_handshake = false; cx.notify(); return; }; + // Dual-band: watch EVERY BSSID of this ESSID (the scanner + // parks on the union of channels, so all bands are covered). + let targets = sibling_targets(app, &essid); + let channels = channels_of(&targets); app.state.push_log(format!( - "handshake capture on {essid} ({ap}, ch {channel})…" + "handshake capture on {essid} — {} bssid(s), ch [{}]… deauth a client to force re-auth", + targets.len(), + channels.iter().map(u8::to_string).collect::>().join(", ") )); + park_channels(app, &channels); if let Some(svc) = &app.service { - svc.cmd(&Cmd::CaptureHs { ap, channel, essid }); + svc.cmd(&Cmd::CaptureHs { targets, essid }); } cx.notify(); return; @@ -222,6 +385,7 @@ fn pmkid_attack(view: &Entity, _window: &mut Window, cx: &mut gpui::App }; app.state .push_log(format!("pmkid attack on {essid} ({ap}, ch {channel})…")); + park_channels(app, &[channel]); if let Some(svc) = &app.service { svc.cmd(&Cmd::Pmkid { ap, channel, essid }); } @@ -257,74 +421,324 @@ fn pmkid_attack(view: &Entity, _window: &mut Window, cx: &mut gpui::App }); } -/// Deauth: broadcast by default, or target the selected client's station. -/// Real mode blasts from the backend's own socket; mock mode fabricates +/// Every BSSID sharing the target's ESSID, with the selected target +/// first — dual-band routers broadcast one SSID on several bands and the +/// client picks one; attacks must cover all of them. Falls back to just +/// the selected target when nothing else is known. +fn sibling_targets(app: &AppRoot, essid: &str) -> Vec<(MacAddr, u8)> { + let mut targets: Vec<(MacAddr, u8)> = Vec::new(); + let mut others: Vec<(MacAddr, u8)> = Vec::new(); + for a in app.state.aps.values() { + if a.ssid == essid && a.channel != 0 { + if Some(a.bssid) == app.selected { + targets.push((a.bssid, a.channel)); + } else { + others.push((a.bssid, a.channel)); + } + } + } + targets.extend(others); + targets +} + +/// Union of channels of a target list (sorted, deduped, zeros dropped). +fn channels_of(targets: &[(MacAddr, u8)]) -> Vec { + let mut ch: Vec = targets.iter().map(|(_, c)| *c).collect(); + ch.sort_unstable(); + ch.dedup(); + ch +} + +/// Restrict the scanner to the target channels so attack workers aren't +/// fighting the 100 ms spectrum-wide hopper (capture/PMKID listen, deauth +/// injects — a far-away radio is mostly deaf/blind). Restarts the scanner +/// with the restricted plan when not already parked on it; a no-op +/// otherwise and in mock mode. +fn park_channels(app: &mut AppRoot, channels: &[u8]) { + let mut want = channels.to_vec(); + want.sort_unstable(); + want.dedup(); + if app.is_mock || want.is_empty() || app.parked_channels.as_deref() == Some(&want) { + return; + } + // A channel-plan restart also stops any running attack worker — the + // new plan invalidates them; the caller (re)spawns its own worker + // right after. + if let Some(svc) = &app.service { + svc.cmd(&Cmd::StartScan { + ifname: app.state.ifname.clone(), + channels: Some(want.clone()), + // Keep appending to the same spool across attack-mode restarts + // — only the toggle-monitor start truncates. + spool: Some(crate::store::data_dir().join("spool.pcap")), + fresh_spool: false, + }); + app.parked_channels = Some(want.clone()); + app.state + .push_log(format!("scanner parked on ch [{}] (attack mode)", want.iter().map(u8::to_string).collect::>().join(", "))); + } +} + +/// Deauth `target` (a station, or [`MacAddr::BROADCAST`] for the whole +/// net) against the selected AP, `count` rounds from the count field. +/// Real mode blasts from the service's own socket; mock mode fabricates /// the same DeauthSent event the real worker emits. +fn do_deauth(app: &mut AppRoot, cx: &mut Context, target: MacAddr) { + let Some(ap) = app.selected else { + app.state.push_log("deauth: no target selected"); + cx.notify(); + return; + }; + let count64: u64 = app + .deauth_input + .read(cx) + .content() + .trim() + .parse() + // 64 rounds ≈ 2 s of airtime per direction — short bursts + // (16 × 15 ms ≈ 0.25 s) slip entirely under a power-save client's + // doze window and land nothing (verified on lab mt7922). + .unwrap_or(64); + + if !app.is_mock { + if !app.state.iface_running { + app.state + .push_log("deauth: start capture first (injection needs monitor mode)"); + cx.notify(); + return; + } + if app.service.is_none() { + app.state + .push_log("deauth: start capture first (the service owns the radio)"); + cx.notify(); + return; + } + let Some((_sel_bssid, _sel_ch, essid)) = target_info(app) else { + app.state + .push_log("deauth: target AP not in scan table yet"); + cx.notify(); + return; + }; + // Dual-band: blast every BSSID of this ESSID — the client picks + // the band, we don't get to. The service worker walks the list + // sequentially. + let aps = sibling_targets(app, &essid); + let channels = channels_of(&aps); + // Park ONCE on the final plan before sending ANY attack command: + // a channel-plan restart stop-joins all workers, so parking later + // would kill the capture worker armed just below. + park_channels(app, &channels); + // A deauth without a listener yields nothing: arm a handshake + // capture first when none is running (the flag is app-global — + // one target at a time, matching the attacks page). CaptureHs is + // handled before Deauth (single command pipe), and the service + // holds the channel synchronously there, so the blast can't shake + // a client loose onto an unwatched band. + if !app.attacking_handshake { + app.attacking_handshake = true; + app.state.push_log(format!( + "deauth: no capture running — auto-armed handshake capture on {essid}" + )); + app.service + .as_ref() + .expect("service presence checked above") + .cmd(&Cmd::CaptureHs { + targets: aps.clone(), + essid: essid.clone(), + }); + } + let count = count64.min(u32::MAX as u64) as u32; + let kind = if target.is_broadcast() { + "broadcast".to_string() + } else { + format!("client {target}") + }; + app.state.push_log(format!( + "deauth: {count} rounds → {kind} ({} bssid(s), ch [{}])", + aps.len(), + channels.iter().map(u8::to_string).collect::>().join(", ") + )); + app.service + .as_ref() + .expect("service presence checked above") + .cmd(&Cmd::Deauth { aps: aps.clone(), target, count }); + // Optimistic DOWN marking: monitor-mode TX never loops back to + // the scanner socket (verified: PACKET_OUTGOING never surfaces on + // mt7921e injection), so the scanner can't observe our own blast + // and the row would stay "up" until the client talks again + // (ClientUpdated flips it back) or ages out. Broadcast → every + // station mapped to a sibling BSSID of this ESSID. + for cl in app.state.clients.values_mut() { + let blasted = if target.is_broadcast() { + cl.ap.is_some_and(|cap| aps.iter().any(|(b, _)| *b == cap)) + } else { + cl.mac == target + }; + if blasted { + cl.connected = false; + } + } + cx.notify(); + return; + } + + let _ = app.tx.send(Event::DeauthSent { + ap, + target, + count: count64, + }); + // Same optimistic DOWN marking as the real branch (see there). + for cl in app.state.clients.values_mut() { + let blasted = if target.is_broadcast() { + cl.ap.is_none_or(|cap| cap == ap) + } else { + cl.mac == target + }; + if blasted { + cl.connected = false; + } + } + cx.notify(); +} + +/// A client row counts as belonging to the selected target when the +/// scanner mapped it there — OR when its AP is unknown (the scanner often +/// never resolves the association; trust the user's pick). +fn client_on_target(app: &AppRoot, mac: &MacAddr, ap: MacAddr) -> bool { + app.state + .clients + .get(mac) + .is_some_and(|c| c.ap.is_none_or(|cap| cap == ap)) +} + +/// Deauth button: a selected client row (see [`client_on_target`]) wins; +/// otherwise deauth the whole net broadcast-style. fn deauth(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + let target = app + .selected + .and_then(|ap| { + app.selected_client + .filter(|mac| client_on_target(app, mac, ap)) + }) + .unwrap_or(MacAddr::BROADCAST); + do_deauth(app, cx, target); + }); +} + +/// Per-station Deauth button in the stations table: fires immediately at +/// that station, no handshake capture required. +fn deauth_station(view: &Entity, station: MacAddr, cx: &mut gpui::App) { + view.update(cx, |app, cx| do_deauth(app, cx, station)); +} + +/// Connected clients mapped to the selected AP (strict association — +/// `client_on_target`'s "unknown AP" leniency would sweep strangers into +/// a bulk blast). +fn connected_clients(app: &AppRoot, ap: MacAddr) -> Vec { + let mut macs: Vec = app + .state + .clients + .values() + .filter(|c| c.ap == Some(ap) && c.connected && !c.mac.is_broadcast()) + .map(|c| c.mac) + .collect(); + macs.sort(); + macs +} + +/// Bulk deauth: every connected client of the selected AP in one service +/// job (single channel pin, per-client rounds, then one broadcast blast). +/// Mock mode fabricates the same DeauthSent stream per client. +fn deauth_all(view: &Entity, cx: &mut gpui::App) { view.update(cx, |app, cx| { let Some(ap) = app.selected else { - app.state.push_log("deauth: no target selected"); + app.state.push_log("deauth-all: no target selected"); cx.notify(); return; }; + let targets = connected_clients(app, ap); + if targets.len() < 2 { + app.state + .push_log("deauth-all: fewer than 2 connected clients — deauth them one by one"); + cx.notify(); + return; + } let count64: u64 = app .deauth_input .read(cx) .content() .trim() .parse() - .unwrap_or(16); + .unwrap_or(64); if !app.is_mock { - if !app.state.iface_running { + if !app.state.iface_running || app.service.is_none() { app.state - .push_log("deauth: start capture first (injection needs monitor mode)"); + .push_log("deauth-all: start capture first (injection needs monitor mode)"); cx.notify(); return; } - let Some(svc) = &app.service else { + let Some((_sel_bssid, channel, essid)) = target_info(app) else { app.state - .push_log("deauth: start capture first (the service owns the radio)"); + .push_log("deauth-all: target AP not in scan table yet"); cx.notify(); return; }; - let Some((ap, channel, _essid)) = target_info(app) else { - app.state - .push_log("deauth: target AP not in scan table yet"); - cx.notify(); - return; - }; - // A selected client row wins; otherwise deauth the whole net - // broadcast-style. (Guard: the pair must still be consistent - // with the live client table.) - let target = app - .selected_client - .filter(|mac| { - app.state - .clients - .get(mac) - .is_some_and(|c| c.ap == Some(ap)) - }) - .unwrap_or(MacAddr::BROADCAST); + // Park before ANY attack command (see do_deauth) and arm a + // capture so the forced re-auths land in a listener. + park_channels(app, &[channel]); + if !app.attacking_handshake { + app.attacking_handshake = true; + app.state.push_log(format!( + "deauth-all: no capture running — auto-armed handshake capture on {essid}" + )); + let aps = sibling_targets(app, &essid); + app.service + .as_ref() + .expect("service presence checked above") + .cmd(&Cmd::CaptureHs { + targets: aps, + essid, + }); + } let count = count64.min(u32::MAX as u64) as u32; app.state.push_log(format!( - "deauth: {count} rounds → {target} (AP {ap}, ch {channel})" + "deauth-all: {count} rounds → {} clients of {ap} (ch {channel})", + targets.len() )); - svc.cmd(&Cmd::Deauth { - ap, - target, - channel, - count, - }); + app.service + .as_ref() + .expect("service presence checked above") + .cmd(&Cmd::DeauthAll { + ap, + channel, + targets: targets.clone(), + count, + }); + // Optimistic DOWN marking (see do_deauth). + for cl in app.state.clients.values_mut() { + if targets.contains(&cl.mac) { + cl.connected = false; + } + } cx.notify(); return; } - let _ = app.tx.send(Event::DeauthSent { - ap, - target: MacAddr::BROADCAST, - count: count64, - }); + // ---- mock path ---- + for target in &targets { + let _ = app.tx.send(Event::DeauthSent { + ap, + target: *target, + count: count64, + }); + } + for cl in app.state.clients.values_mut() { + if targets.contains(&cl.mac) { + cl.connected = false; + } + } cx.notify(); }); } @@ -378,18 +792,107 @@ pub fn render( ) -> gpui::Div { let theme = cx.theme().clone(); - let target_block = match app.selected.and_then(|b| { - app.state - .aps - .get(&b) - .map(|ap| (ap.ssid.clone(), b, ap.channel)) - }) { - Some((ssid, bssid, ch)) => h_stack() - .gap_3() - .items_center() - .child(h3(format!("target: {ssid}"))) - .child(text(format!("{bssid} · ch {ch}")).code().small().into_any_element()) - .into_any_element(), + // Client chip for the banner: the selected client counts when it's + // mapped to the target AP or its association is unknown (scanner often + // never resolves it). + let banner_client: Option = app.selected.and_then(|ap| { + app.selected_client + .filter(|mac| client_on_target(app, mac, ap)) + }); + + // Target context card: everything Networks knows about the target, + // one glance, plus a computed "best next move". Falls back to the + // click-time snapshot when the AP has no live row (host-capture + // lock never re-scans) so the card can't silently go blank. + let target_block: gpui::AnyElement = match target_row(app) { + Some((ap, stale)) => { + let bssid = ap.bssid; + let (hs_n, pm_n) = material_for(app, ap); + let siblings = sibling_targets(app, &ap.ssid).len(); + let akm_join = ap + .akms + .iter() + .map(|a| a.label()) + .collect::>() + .join("+"); + let spark = app.state.rssi_hist.get(&bssid).cloned(); + let label = app.state.labels.get(&bssid).cloned(); + let (advice, actionable) = advisor(app, ap); + let client_line = banner_client.map(|c| { + let lbl = app + .state + .labels + .get(&c) + .map(|l| format!(" “{l}”")) + .unwrap_or_default(); + text(format!("client: {c}{lbl}")).code().small().into_any_element() + }); + v_stack() + .gap_2() + .p_3() + .rounded_md() + .border_1() + .border_color(theme.border()) + .bg(theme.surface()) + .child(h3(format!( + "target: {}{}", + ap.ssid, + label.map(|l| format!(" “{l}”")).unwrap_or_default() + ))) + .child(small(format!( + "{bssid} · ch {} ({} GHz) · vendor {}{}", + ap.channel, + crate::ui::networks::band(ap.channel), + crate::ui::networks::vendor_of(&bssid), + if stale { " · last scan snapshot" } else { "" } + ))) + .child( + v_stack() + .gap_2() + .child( + h_stack() + .gap_2() + .items_center() + .child(crate::ui::networks::sec_badge_label( + &crate::ui::networks::sec_label(ap), + ap.security, + )) + .children((!akm_join.is_empty()).then(|| small(akm_join))) + .children((siblings > 1) + .then(|| badge(format!("dual-band x{siblings}")).secondary())), + ) + .child( + h_stack() + .gap_3() + .items_center() + .child(crate::ui::networks::sparkline( + spark.as_ref(), + theme.accent(), + )) + .child(small(format!( + "{} dBm · {} beacons · seen {} ago", + ap.rssi_dbm, + ap.beacons, + crate::ui::networks::age(ap.last_seen_ms) + ))), + ) + .child(small(format!( + "material for this AP family: {hs_n} handshake(s) · {pm_n} PMKID(s)" + ))) + .children(client_line) + .child( + div() + .text_xs() + .text_color(if actionable { + theme.accent() + } else { + theme.warning() + }) + .child(advice), + ), + ) + .into_any_element() + } None => h_stack() .gap_3() .items_center() @@ -403,15 +906,25 @@ pub fn render( // (a matching hint sits next to them). let not_running = !app.is_mock && !app.state.iface_running; let blocked = no_target || not_running; + // SAE-only: no offline attack applies (see sae_only). + let sae = sae_only(app); let hs_running = app.attacking_handshake; let pm_running = app.attacking_pmkid; + // Bulk-deauth candidates: strictly-mapped connected clients of the + // selected AP. Click-time count for the button label. + let deauth_targets: usize = app + .selected + .map(|ap| connected_clients(app, ap).len()) + .unwrap_or(0); + app.deauth_all_targets = deauth_targets; + let actions = h_stack() .gap_3() .items_center() .child( button("btn-handshake", "Capture Handshake") - .disabled(blocked || hs_running) + .disabled(blocked || hs_running || sae) .on_click({ let view = view.clone(); move |_, window, cx| capture_handshake(&view, window, cx) @@ -419,21 +932,40 @@ pub fn render( ) .child( button("btn-pmkid", "PMKID Attack") - .disabled(blocked || pm_running) + .disabled(blocked || pm_running || sae) .on_click({ let view = view.clone(); move |_, window, cx| pmkid_attack(&view, window, cx) }), ) .child( - button("btn-deauth", "Deauth") - .destructive() - .disabled(blocked) - .on_click({ - let view = view.clone(); - move |_, window, cx| deauth(&view, window, cx) - }), + button( + "btn-deauth", + if banner_client.is_some() { + "Deauth client" + } else { + "Deauth all" + }, + ) + .destructive() + .disabled(blocked || sae) + .on_click({ + let view = view.clone(); + move |_, window, cx| deauth(&view, window, cx) + }), ) + .children((deauth_targets >= 2).then(|| { + button( + "btn-deauth-all", + format!("Deauth all clients ({deauth_targets})"), + ) + .destructive() + .disabled(blocked || sae) + .on_click({ + let view = view.clone(); + move |_, _window, cx| deauth_all(&view, cx) + }) + })) .child( div() .w(px(90.)) @@ -464,13 +996,174 @@ pub fn render( }) .collect(); + // Stations of the target: deauth a client directly (forces its + // re-auth → its 4-way handshake) without touching anything else. + let stations: Vec<&ClientInfo> = app + .selected + .map(|sel| { + app.state + .clients + .values() + .filter(|c| client_on_target(app, &c.mac, sel) && !c.mac.is_broadcast()) + .collect() + }) + .unwrap_or_default(); + + let stations_block = app.selected.map(|_sel| { + let rows: Vec = stations + .iter() + .map(|cl| { + let mac = cl.mac; + let ap_of = cl.ap; + let view = view.clone(); + // MAC-randomization pairing chip: live row's own fields, + // overlaid by the pairing record (wire fields can lag). + let ident = app + .state + .idents + .get(&mac) + .copied() + .or(cl.ident_group.zip(cl.ident_conf)); + h_stack() + .w_full() + .gap_3() + .items_center() + .px_2() + .py_1() + .child( + v_stack() + .w(px(170.)) + .child(text(mac.to_string()).code().small().into_any_element()) + .child( + div() + .text_xs() + .text_color(theme.fg_muted()) + .child(crate::ui::networks::vendor_of(&mac)), + ), + ) + .children( + app.state + .labels + .get(&mac) + .map(|l| small(format!("“{l}”"))), + ) + .children(ident.and_then(|(gid, conf)| { + let n = app + .state + .ident_groups + .get(&gid) + .map_or(1, |ms| ms.len()); + let mut el = div() + .w(px(90.)) + .text_xs() + .child(format!("#{gid}{} ({n})", conf.label())); + if n > 1 { + el = el.text_color(theme.accent()); + } else { + el = el.text_color(theme.fg_muted()); + } + Some(el) + })) + .child( + div() + .w(px(70.)) + .text_xs() + .child(format!("{} dBm", cl.rssi_dbm)), + ) + .child(div().w(px(60.)).text_xs().child(format!( + "{} fr", + cl.frames + ))) + .child( + div() + .w(px(50.)) + .text_xs() + .child(crate::ui::networks::age(cl.last_seen_ms)), + ) + .children((ap_of.is_none()) + .then(|| small("AP unmapped — treating as target's station"))) + .child(div().flex_1()) + .child( + button( + gpui::SharedString::from(format!("deauth-sta-{mac}")), + "Deauth client", + ) + .destructive() + .disabled(!app.is_mock && !app.state.iface_running) + .on_click(move |_, _window, cx| deauth_station(&view, mac, cx)), + ) + .into_any_element() + }) + .collect(); + + let body = if rows.is_empty() { + div().child(small( + "no stations seen on this AP yet — click any client row on the Networks page \ + to target it here anyway", + )) + .into_any_element() + } else { + v_stack().gap_1().children(rows).into_any_element() + }; + + v_stack() + .gap_2() + .child( + h_stack() + .items_center() + .gap_3() + .child(h3("Stations")) + .child(small(format!( + "{} — deauth one to force its handshake while capture runs", + stations.len() + ))), + ) + .child(body) + .into_any_element() + }); + + // Recent attack-relevant activity, so every button press leaves a + // visible trace on THIS page (the full history lives on the Log page). + const ACTIVITY_LINES: usize = 8; + let activity: Vec = app + .state + .log + .iter() + .filter(|line| { + [ + "deauth", "handshake", "pmkid", "4-way", "scanner parked", "ERROR", "PASSWORD", + "target selected", "client selected", + ] + .iter() + .any(|p| line.starts_with(p)) + }) + .rev() + .take(ACTIVITY_LINES) + .cloned() + .collect::>() + .into_iter() + .rev() + .collect(); + let mut page = v_stack() .size_full() .gap_3() .p_4() .child(target_block) + .when(sae, |el| { + el.child( + div() + .text_xs() + .text_color(theme.warning()) + .child( + "SAE-only AP — no offline-crackable handshake or PMKID \ + (WPA3 transition APs with PSK AKM are fine)", + ), + ) + }) .child(actions) .children(progress_cards) + .children(stations_block) .child(gpuikit::elements::separator::separator()) .child( h_stack() @@ -483,6 +1176,12 @@ pub fn render( app.state.pmkids.len() ))) .child(div().flex_1()) + .child( + button("btn-export-pcap", "Export .pcap").on_click({ + let view = view.clone(); + move |_, window, cx| export_pcap(&view, window, cx) + }), + ) .child( button("btn-export", "Export .hc22000").on_click({ let view = view.clone(); @@ -504,5 +1203,26 @@ pub fn render( page = page.child(v_stack().gap_2().children(cards)); } + page = page + .child(gpuikit::elements::separator::separator()) + .child(h3("Activity")).child(if activity.is_empty() { + small("nothing yet — attack output appears here (full history on the Log page)") + .into_any_element() + } else { + v_stack() + .gap_1() + .p_2() + .rounded_md() + .bg(theme.surface()) + .children(activity.iter().map(|line| { + div() + .text_xs() + .text_color(theme.fg_muted()) + .child(line.clone()) + .into_any_element() + })) + .into_any_element() + }); + page.text_color(theme.fg()) } diff --git a/src/ui/cracker.rs b/src/ui/cracker.rs index 95dc305..dc679c4 100644 --- a/src/ui/cracker.rs +++ b/src/ui/cracker.rs @@ -1,13 +1,22 @@ -//! Cracker page: target dropdown (fed by captures), wordlist field, backend -//! label, Start/Stop, live throughput/progress, found-password banner. +//! Cracker page: target dropdown (fed by captures), attack-mode select +//! (wordlist / bruteforce / rainbow PMK table) with per-mode inputs, +//! backend label, Start/Stop, live throughput/progress, rainbow-table +//! build controls, recent-activity log, found-password banner. //! -//! Until the real wgpu cracker lands, Start runs a deterministic simulation -//! on a gpui background task so every control here is live. +//! Cracking is a plain UI-process job ([`crate::attack`]): it does NOT +//! need the privileged radio service and is completely independent of +//! capture state — a run may be started while a capture is live. +//! In mock mode Start runs a deterministic simulation on a gpui +//! background task instead (same event sequence; the attack mode is +//! ignored there). +use std::path::PathBuf; +use std::sync::atomic::Ordering; use std::time::Duration; use gpui::{ - Context, Entity, IntoElement, ParentElement, Styled, Window, div, prelude::FluentBuilder, px, + Context, Entity, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, + Styled, Window, div, prelude::FluentBuilder, px, }; use gpuikit::elements::button::button; use gpuikit::elements::loading_indicator::loading_indicator; @@ -17,6 +26,7 @@ use gpuikit::elements::typography::{h3, small, text}; use gpuikit::layout::{h_stack, v_stack}; use gpuikit::theme::{ActiveTheme, Themeable}; +use crate::attack::Attack; use crate::common::Event; use crate::ui::app::AppRoot; @@ -31,7 +41,7 @@ const fn backend_label(is_mock: bool) -> &'static str { if is_mock { "GPU (wgpu) · mock" } else { - "auto: GPU (wgpu) → CPU" + "GPU (wgpu) → CPU" } } @@ -45,16 +55,180 @@ fn fmt_hps(hps: f64) -> String { } } +/// Human duration for worst-case ETAs ("3d 4h", "2h 05m", "3m 12s", "12s"). +fn fmt_dur(secs: f64) -> String { + if !secs.is_finite() || secs < 1.0 { + return "<1s".to_string(); + } + let s = secs.round() as u64; + let (d, h, m, sec) = (s / 86400, s / 3600 % 24, s / 60 % 60, s % 60); + if d > 0 { + format!("{d}d {h}h") + } else if h > 0 { + format!("{h}h {m:02}m") + } else if m > 0 { + format!("{m}m {sec:02}s") + } else { + format!("{sec}s") + } +} + +/// Worst-case remaining time: every not-yet-tried candidate at the +/// current rate. Empty when the total or the rate is unknown. +fn fmt_worst_case(done: u64, hps: f64, total: Option) -> Option { + let t = total?; + if hps <= 0.0 || done >= t { + return None; + } + Some(format!("worst case left: ~{}", fmt_dur((t - done) as f64 / hps))) +} + +/// Build the [`Attack`] selected by `app.attack_mode` from the page's +/// input fields. Returns `None` (after logging the reason) when an input +/// is empty or fails to parse. +fn selected_attack(app: &mut AppRoot, cx: &mut gpui::App) -> Option { + match app.attack_mode.as_str() { + "bruteforce" => { + let custom = app + .charset_input + .read(cx) + .content() + .trim_end_matches(['\r', '\n']) + .as_bytes() + .to_vec(); + // Union of the checked preset chips + the custom field. + let charset = crate::attack::charset::compose( + app.cs_lower, + app.cs_upper, + app.cs_digits, + app.cs_special, + &custom, + ); + if charset.is_empty() { + app.state.push_log( + "cracker: empty charset — pick a preset chip or type custom chars", + ); + return None; + } + let min_s = app.len_min_input.read(cx).content().trim().to_string(); + let max_s = app.len_max_input.read(cx).content().trim().to_string(); + let min = match min_s.parse::() { + Ok(v) => v, + Err(_) => { + app.state.push_log(format!("cracker: bad min length '{min_s}'")); + return None; + } + }; + let max = match max_s.parse::() { + Ok(v) => v, + Err(_) => { + app.state.push_log(format!("cracker: bad max length '{max_s}'")); + return None; + } + }; + Some(Attack::Bruteforce { charset, min, max, freq_order: app.freq_order }) + } + "rules" => { + let wl = app.wordlist_input.read(cx).content().trim().to_string(); + if wl.is_empty() { + app.state.push_log("cracker: wordlist path is empty"); + return None; + } + let rules = app.rules_input.read(cx).content().trim().to_string(); + if rules.is_empty() { + app.state.push_log("cracker: rules path is empty"); + return None; + } + Some(Attack::Rules { + wordlist: PathBuf::from(wl), + rules: PathBuf::from(rules), + }) + } + "hybrid" => { + let wl = app.wordlist_input.read(cx).content().trim().to_string(); + if wl.is_empty() { + app.state.push_log("cracker: wordlist path is empty"); + return None; + } + let custom = app + .charset_input + .read(cx) + .content() + .trim_end_matches(['\r', '\n']) + .as_bytes() + .to_vec(); + let charset = crate::attack::charset::compose( + app.cs_lower, + app.cs_upper, + app.cs_digits, + app.cs_special, + &custom, + ); + if charset.is_empty() { + app.state.push_log( + "cracker: empty charset — pick a preset chip or type custom chars", + ); + return None; + } + let min_s = app.hyb_min_input.read(cx).content().trim().to_string(); + let max_s = app.hyb_max_input.read(cx).content().trim().to_string(); + let min = match min_s.parse::() { + Ok(v) => v.clamp(1, 4), + Err(_) => { + app.state.push_log(format!("cracker: bad hybrid min '{min_s}'")); + return None; + } + }; + let max = match max_s.parse::() { + Ok(v) => v.clamp(1, 4), + Err(_) => { + app.state.push_log(format!("cracker: bad hybrid max '{max_s}'")); + return None; + } + }; + if min > max { + app.state + .push_log(format!("cracker: hybrid min {min} > max {max}")); + return None; + } + Some(Attack::Hybrid { + wordlist: PathBuf::from(wl), + charset, + min, + max, + }) + } + "rainbow" => { + let path = app.rainbow_input.read(cx).content().trim().to_string(); + if path.is_empty() { + app.state.push_log("cracker: PMK table path is empty"); + return None; + } + Some(Attack::Rainbow(PathBuf::from(path))) + } + _ => { + let path = app.wordlist_input.read(cx).content().trim().to_string(); + if path.is_empty() { + app.state.push_log("cracker: wordlist path is empty"); + return None; + } + Some(Attack::Wordlist(PathBuf::from(path))) + } + } +} + /// Start a crack run on the selected capture. /// -/// Real mode: hands the stored [`crate::crypto::CrackTarget`] (no hc22000 -/// re-parse) to the backend worker; progress and termination arrive as +/// Real mode: builds the selected [`Attack`], validates it (files +/// opened, charset/lengths checked) BEFORE any flag is set, then hands +/// the stored [`crate::crypto::CrackTarget`] (no hc22000 re-parse) to +/// `crate::attack::spawn_crack`; progress and termination arrive as /// CrackProgress/CrackFound/CrackStopped events and land in state via -/// `AppState::apply`. Requires capture stopped (radio exclusive). +/// `AppState::apply`. No radio or service involvement. /// Mock mode: a deterministic generator drives the SAME event sequence. fn start(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { view.update(cx, |app, cx| { - if app.crack_inflight || app.state.cracker.running { + if app.crack_inflight || app.state.cracker.running || app.bench_running { return; } let Some(desc) = app.state.cracker.target.clone() else { @@ -62,19 +236,16 @@ fn start(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { cx.notify(); return; }; - let wordlist = app.wordlist_input.read(cx).content().trim().to_string(); - if wordlist.is_empty() { - app.state.push_log("cracker: wordlist path is empty"); - cx.notify(); - return; - } // Validate everything that can fail BEFORE marking the run active, // so a refused start never leaves stale flags behind. - let real_target = if !app.is_mock { - if app.state.iface_running { - app.state - .push_log("cracker: needs the radio free — stop capture first"); + let real = if !app.is_mock { + let Some(attack) = selected_attack(app, cx) else { + cx.notify(); + return; + }; + if let Err(e) = attack.validate() { + app.state.push_log(format!("ERROR: cracker: {e:#}")); cx.notify(); return; } @@ -84,7 +255,7 @@ fn start(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { return; }; match app.state.crack_target_at(idx) { - Some(t) => Some(t), + Some(t) => Some((t, attack)), None => { app.state.push_log("ERROR: cracker: capture no longer exists"); cx.notify(); @@ -96,36 +267,54 @@ fn start(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { }; app.crack_epoch += 1; // invalidate any stale mock generator ticks + let wordlist = app.wordlist_input.read(cx).content().trim().to_string(); let cr = &mut app.state.cracker; cr.wordlist = Some(wordlist.clone()); cr.found = None; cr.tried = 0; cr.hps = 0.0; + cr.total = None; + // A fresh foreground start supersedes any saved resume position. + cr.resume = None; cr.running = true; app.crack_inflight = true; + // Fresh run: the throughput curve belongs to it, not the last run. + app.state.hps_hist.clear(); cx.notify(); if !app.is_mock { - let Some(target) = real_target else { return }; + let Some((target, attack)) = real else { return }; app.state.push_log(format!( - "cracker: starting on {desc} via {wordlist} [auto backend]" + "cracker: starting on {desc} — {}", + attack.describe() )); - cx.notify(); - match &app.service { - Some(svc) => svc.spawn_crack( - target.describe(), - target, - std::path::PathBuf::from(&wordlist), - app.tx.clone(), - ), - None => { - app.state.cracker.running = false; - app.crack_inflight = false; - app.state - .push_log("ERROR: cracker: no service (start capture first, then stop it)"); - cx.notify(); + // Remember the wordlist path in the MRU list (wordlist-family + // attacks only) so it shows up as a one-click chip later. + let wl_path: Option = match &attack { + Attack::Wordlist(p) => Some(p.display().to_string()), + Attack::Rules { wordlist, .. } | Attack::Hybrid { wordlist, .. } => { + Some(wordlist.display().to_string()) + } + _ => None, + }; + if let Some(wl_path) = wl_path { + crate::store::remember_wordlist(&mut app.profiles, &wl_path); + if let Err(e) = crate::store::save_profiles(&app.profiles) { + app.state.push_log(format!("profiles: save FAILED: {e:#}")); } } + // Track the live attack for the resume session file + // (throttle-saved on progress, finalized on stop). + app.state.cracker.active_attack = Some(attack.clone()); + cx.notify(); + app.crack_stop = Some(crate::attack::spawn_crack( + target.describe(), + target, + attack, + 0, + app.tx.clone(), + false, + )); return; } @@ -152,7 +341,11 @@ fn start(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { } done += (MOCK_HPS / 10.0) as u64 + done / 977 % 8_000; let hps = MOCK_HPS * (0.92 + (done / 331 % 15) as f64 / 100.0); - let _ = tx.send(Event::CrackProgress { done, hps }); + let _ = tx.send(Event::CrackProgress { + done, + hps, + total: Some(WORDLIST_TOTAL), + }); if done >= WORDLIST_TOTAL { let _ = tx.send(Event::CrackFound { password: MOCK_PASSWORD.to_string(), @@ -168,10 +361,11 @@ fn start(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { /// Stop the active run. /// -/// Real mode flips the crack job's stop flag (the wordlist streamer breaks -/// at the next batch and emits CrackStopped{found:false}, which settles -/// the UI). Mock mode just invalidates the generator epoch — no terminator -/// event will arrive, so the running flags are cleared here. +/// Real mode flips the crack job's stop flag (the worker breaks at the +/// next batch and emits CrackStopped{found:false}, which settles the UI +/// and clears `app.crack_stop`). Mock mode just invalidates the +/// generator epoch — no terminator event will arrive, so the running +/// flags are cleared here. fn stop(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { view.update(cx, |app, cx| { let active = app.crack_inflight || app.state.cracker.running; @@ -187,18 +381,615 @@ fn stop(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { cx.notify(); return; } - if let Some(svc) = &app.service { - svc.request_crack_stop(); + if let Some(flag) = &app.crack_stop { + flag.store(true, Ordering::Relaxed); app.state.push_log("cracker: stop requested"); + } + cx.notify(); + }); +} + +/// Start a rainbow PMK-table build for the selected capture's SSID. +/// +/// Validates both paths (wordlist must open, table path must be given) +/// BEFORE marking the build active; progress arrives as +/// RainbowProgress, termination as RainbowBuilt — the latter settles +/// `rainbow_building` and `app.rainbow_stop`. +fn build(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + if app.state.cracker.rainbow_building + || app.crack_inflight + || app.state.cracker.running + || app.bench_running + { + return; + } + let Some(desc) = app.state.cracker.target.clone() else { + app.state.push_log("rainbow: no target selected"); + cx.notify(); + return; + }; + let Some(idx) = app.state.capture_descs().iter().position(|d| *d == desc) else { + app.state.push_log("ERROR: rainbow: capture no longer exists"); + cx.notify(); + return; + }; + let Some(target) = app.state.crack_target_at(idx) else { + app.state.push_log("ERROR: rainbow: capture no longer exists"); + cx.notify(); + return; + }; + let ssid = target.essid().to_string(); + + let wl = app.wordlist_input.read(cx).content().trim().to_string(); + if wl.is_empty() { + app.state.push_log("rainbow: wordlist path is empty"); + cx.notify(); + return; + } + if let Err(e) = std::fs::File::open(&wl) { + app.state + .push_log(format!("ERROR: rainbow: cannot open wordlist {wl}: {e}")); + cx.notify(); + return; + } + let out = app.rainbow_input.read(cx).content().trim().to_string(); + if out.is_empty() { + app.state.push_log("rainbow: PMK table path is empty"); + cx.notify(); + return; + } + + app.state.cracker.rainbow_building = true; + app.state.cracker.rainbow_done = 0; + app.state.cracker.rainbow_hps = 0.0; + app.state.cracker.rainbow_total = None; + app.state.push_log(format!( + "rainbow: building table {out} for ssid \"{ssid}\" from {wl}" + )); + cx.notify(); + app.rainbow_stop = Some(crate::attack::spawn_rainbow_build( + ssid, + PathBuf::from(wl), + PathBuf::from(out), + app.tx.clone(), + )); + }); +} + +/// Stop the running rainbow-table build: flip the job's stop flag; the +/// terminating RainbowBuilt event settles the UI. +fn build_stop(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + if let Some(flag) = &app.rainbow_stop { + flag.store(true, Ordering::Relaxed); + app.state.push_log("rainbow: stop requested"); + cx.notify(); + } + }); +} + +/// Resume the saved run shown in the banner: same capture, same attack, +/// continuing at the saved candidate offset. +fn resume_saved(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + if app.crack_inflight + || app.state.cracker.running + || app.state.cracker.rainbow_building + || app.bench_running + { + return; + } + let Some(r) = app.state.cracker.resume.clone() else { + return; + }; + // Files may have vanished since the run was saved — refuse with a + // visible reason, keep the session file + banner untouched. + if let Err(e) = r.attack.validate() { + app.state + .push_log(format!("ERROR: cracker: saved run no longer valid: {e:#}")); + cx.notify(); + return; + } + let Some(idx) = app + .state + .capture_descs() + .iter() + .position(|d| *d == r.target_desc) + else { + app.state + .push_log("ERROR: cracker: saved run's capture no longer exists"); + cx.notify(); + return; + }; + let Some(target) = app.state.crack_target_at(idx) else { + app.state + .push_log("ERROR: cracker: saved run's capture no longer exists"); + cx.notify(); + return; + }; + + app.crack_epoch += 1; + let cr = &mut app.state.cracker; + cr.found = None; + cr.tried = r.done; + cr.hps = 0.0; + cr.total = r.total; + cr.active_attack = Some(r.attack.clone()); + cr.resume = None; + cr.running = true; + app.crack_inflight = true; + app.state.hps_hist.clear(); + // The new run's throttle-saves supersede the old session file; + // clear eagerly so a crash cannot doubly arm the banner. + if let Err(e) = crate::store::clear_session() { + app.state + .push_log(format!("cracker: session clear failed: {e:#}")); + } + app.state.push_log(format!( + "cracker: resuming saved run — {} at {}{}", + r.attack.describe(), + r.done, + r.total.map(|t| format!("/{t}")).unwrap_or_default() + )); + cx.notify(); + app.crack_stop = Some(crate::attack::spawn_crack( + target.describe(), + target, + r.attack, + r.done, + app.tx.clone(), + false, + )); + }); +} + +/// Delete the saved session file and dismiss the banner. +fn discard_saved(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + if let Err(e) = crate::store::clear_session() { + app.state + .push_log(format!("cracker: session clear failed: {e:#}")); + } + app.state.cracker.resume = None; + app.state.push_log("cracker: saved run discarded"); + cx.notify(); + }); +} + +/// Save the current mode + paths as a named preset in `app.profiles` +/// (name auto-derived as `{mode}:{basename(wordlist)}`; a same-name +/// preset is replaced). Persisted via [`crate::store::save_profiles`]. +fn save_preset(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + let mode = app.attack_mode.clone(); + if mode == "rainbow" { + app.state.push_log("profiles: rainbow presets are not saved"); + cx.notify(); + return; + } + let wordlist = app.wordlist_input.read(cx).content().trim().to_string(); + if wordlist.is_empty() { + app.state.push_log("profiles: wordlist path is empty — nothing to save"); + cx.notify(); + return; + } + let rules = match mode.as_str() { + "rules" => { + let r = app.rules_input.read(cx).content().trim().to_string(); + if r.is_empty() { + app.state.push_log("profiles: rules path is empty — nothing to save"); + cx.notify(); + return; + } + Some(r) + } + _ => None, + }; + let base = std::path::Path::new(&wordlist) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| wordlist.clone()); + let name = format!("{mode}:{base}"); + let profile = crate::store::CrackProfile { + name: name.clone(), + mode, + wordlist, + rules, + }; + app.profiles.profiles.retain(|p| p.name != name); + app.profiles.profiles.push(profile); + match crate::store::save_profiles(&app.profiles) { + Ok(()) => app.state.push_log(format!("profiles: saved preset {name}")), + Err(e) => app.state.push_log(format!("profiles: save FAILED: {e:#}")), + } + cx.notify(); + }); +} + +/// Apply a saved preset: switch the attack mode and prefill the +/// wordlist/rules input fields. +fn apply_preset(profile: crate::store::CrackProfile, view: &Entity, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + app.attack_mode = profile.mode.clone(); + app.attack_select.update(cx, |sel, cx| { + sel.set_selected(Some(profile.mode.clone()), cx); + }); + let wl = profile.wordlist.clone(); + app.wordlist_input.update(cx, |input, cx| { + input.set_content(wl, cx); + }); + if let Some(rules) = &profile.rules { + let r = rules.clone(); + app.rules_input.update(cx, |input, cx| { + input.set_content(r, cx); + }); + } + app.state + .push_log(format!("profiles: applied preset {}", profile.name)); + cx.notify(); + }); +} + +/// Import captures from .cap/.pcap files (via [`crate::pcapin::extract`]) +/// or .hc22000 text files (via [`crate::crypto::parse_hc22000`]). Each +/// extracted capture arrives as a CaptureImported event; the heavy parse +/// runs on a worker thread streaming events like the crack threads do. +/// `import_busy` is cleared at the very end, after all chosen files. +fn import_captures(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + let prompt = cx.prompt_for_paths(gpui::PathPromptOptions { + files: true, + directories: false, + multiple: true, + prompt: None, + }); + view.update(cx, |app, cx| { + app.import_busy = true; + cx.notify(); + }); + let weak = view.downgrade(); + cx.spawn(async move |cx| { + // oneshot recv err OR platform dialog err OR explicit cancel all + // land here as "no file chosen". + let picked: Option> = match prompt.await { + Ok(Ok(paths)) => paths, + _ => None, + }; + let Some(paths) = picked else { + let _ = weak.update(cx, |app, cx| { + app.import_busy = false; + app.state.push_log("import: no file chosen"); + cx.notify(); + }); + return; + }; + // Heavy parsing (multi-GB pcaps) must not block the UI executor: + // stream results from a plain thread like the crack workers do. + let tx = match weak.update(cx, |app, _cx| app.tx.clone()) { + Ok(tx) => tx, + Err(_) => return, // view gone — nothing to report to + }; + // At the very end (after all files) the worker signals completion + // on this channel; the gpui continuation below clears import_busy + // (a bare std thread cannot touch gpui state). + let (done_tx, done_rx) = crossbeam_channel::bounded::<()>(1); + std::thread::Builder::new() + .name("wifilab-import".into()) + .spawn(move || { + for path in paths { + let disp = path.display().to_string(); + let is_hc22000 = disp.contains("22000") + || std::fs::read_to_string(&path) + .map(|s| { + s.lines() + .take(8) + .any(|l| l.starts_with("WPA*01") || l.starts_with("WPA*02")) + }) + .unwrap_or(false); + if is_hc22000 { + match std::fs::read_to_string(&path) { + Ok(text) => { + let mut n = 0usize; + let mut m = 0usize; + for line in text.lines() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let bare = line.strip_prefix("WPA*").unwrap_or(line); + match crate::crypto::parse_hc22000(bare) { + Ok(crate::crypto::CrackTarget::Handshake(h)) => { + let _ = tx.send(Event::CaptureImported( + crate::common::ImportedCapture::Handshake( + Box::new(h), + ), + )); + n += 1; + } + Ok(crate::crypto::CrackTarget::Pmkid(p)) => { + let _ = tx.send(Event::CaptureImported( + crate::common::ImportedCapture::Pmkid(p), + )); + n += 1; + } + Err(_) => m += 1, + } + } + let _ = tx.send(Event::Log(format!( + "import: {disp}: {n} captures ({m} skipped)" + ))); + } + Err(e) => { + let _ = tx.send(Event::Error(format!("import: {disp}: {e}"))); + } + } + } else { + match crate::pcapin::extract(&path) { + Ok(caps) => { + let n = caps.len(); + for cap in caps { + let _ = tx.send(Event::CaptureImported(cap)); + } + let _ = tx.send(Event::Log(format!( + "import: {disp}: {n} captures (0 skipped)" + ))); + } + Err(e) => { + let _ = tx.send(Event::Error(format!("import: {disp}: {e:#}"))); + } + } + } + } + let _ = done_tx.send(()); + }) + .expect("spawn import thread"); + // Wait for completion on the background executor, then clear the + // busy flag on the gpui side. + let bg = cx.background_executor().clone(); + bg.spawn(async move { + let _ = done_rx.recv(); + }) + .await; + let _ = weak.update(cx, |app, cx| { + app.import_busy = false; + cx.notify(); + }); + }) + .detach(); +} + +/// Run a 3 s H/s benchmark (GPU if available, CPU always). Results +/// arrive as one BenchmarkDone event; `bench_running` is cleared on the +/// app drain side. Mock mode fabricates a fixed result after ~1.5 s. +fn benchmark(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + if app.bench_running + || app.crack_inflight + || app.state.cracker.running + || app.state.cracker.rainbow_building + { + return; + } + app.bench_running = true; + app.state.push_log("benchmark: measuring crack speed (3s)…"); + cx.notify(); + if !app.is_mock { + // The worker holds its own Arc; the flag is never flipped by + // the UI, so dropping our copy is safe. + drop(crate::attack::spawn_benchmark(3, app.tx.clone())); + return; + } + // Mock: fabricate a BenchmarkDone after ~1.5 s. No epoch + // invalidation: bench_running already blocks a concurrent second + // click, and a crack started meanwhile does not invalidate a + // machine-speed measurement. + let tx = app.tx.clone(); + cx.spawn(async move |this, cx| { + cx.background_executor() + .timer(Duration::from_millis(1500)) + .await; + let live = this.update(cx, |app, _cx| app.bench_running).unwrap_or(false); + if live { + let _ = tx.send(Event::BenchmarkDone { + gpu_hps: Some(MOCK_HPS), + cpu_hps: 310_000.0, + }); + } + }) + .detach(); + }); +} + +/// Estimate worst-case crack durations from the measured benchmark rate +/// and the current input fields; results go to the activity log as +/// "estimate:" lines (candidate-space math always, times only when a +/// benchmark has run). +fn estimate(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + let hps = match (app.state.bench_gpu, app.state.bench_cpu) { + (Some(g), Some(c)) => Some(g.max(c)), + (Some(g), None) => Some(g), + (None, Some(c)) => Some(c), + (None, None) => None, + }; + let Some(hps) = hps.filter(|h| *h > 0.0) else { + app.state + .push_log("estimate: run Benchmark for times; candidate-space math only"); + cx.notify(); + return; + }; + + // (a) wordlist family: lines × rules (rules mode) at best rate. + let wl = app.wordlist_input.read(cx).content().trim().to_string(); + let wl_space: Option = if wl.is_empty() { + Some(WORDLIST_TOTAL as u128) } else { - app.state.cracker.running = false; - app.crack_inflight = false; - app.state.push_log("cracker: stopped"); + match crate::wordlist::line_count(std::path::Path::new(&wl)) { + Ok(n) => Some(n as u128), + Err(e) => { + app.state + .push_log(format!("estimate: wordlist unreadable: {e:#}")); + None + } + } + }; + if let Some(mut space) = wl_space { + let mut what = format!("wordlist {}", if wl.is_empty() { "(mock-size)" } else { &wl }); + if app.attack_mode == "rules" { + let rp = app.rules_input.read(cx).content().trim().to_string(); + match crate::attack::rule_count(std::path::Path::new(&rp)) { + Ok(r) if r > 0 => { + space = space.saturating_mul(r as u128); + what = format!("{what} × {r} rules"); + } + Ok(_) => {} + Err(e) => { + app.state + .push_log(format!("estimate: rules unreadable: {e:#}")); + space = 0; + } + } + } + if space > 0 { + app.state.push_log(format!( + "estimate: {what}: {space} candidates, worst case ~{} @ {}", + fmt_dur(space as f64 / hps), + fmt_hps(hps) + )); + } + } + + // (b) bruteforce space at best rate. + let custom = app + .charset_input + .read(cx) + .content() + .trim_end_matches(['\r', '\n']) + .as_bytes() + .to_vec(); + let charset = crate::attack::charset::compose( + app.cs_lower, + app.cs_upper, + app.cs_digits, + app.cs_special, + &custom, + ); + if charset.is_empty() { + app.state.push_log("estimate: empty charset — bruteforce space n/a"); + } else { + let min = app + .len_min_input + .read(cx) + .content() + .trim() + .parse::() + .unwrap_or(8); + let max = app + .len_max_input + .read(cx) + .content() + .trim() + .parse::() + .unwrap_or(10); + match crate::attack::BruteForce::new(charset.clone(), min, max, false) { + Ok(bf) => { + let space = bf.space(); + app.state.push_log(format!( + "estimate: bruteforce {min}..={max}: {space} candidates, worst case ~{} @ {}", + fmt_dur(space as f64 / hps), + fmt_hps(hps) + )); + } + Err(e) => app + .state + .push_log(format!("estimate: bruteforce range invalid: {e:#}")), + } + } + + // (c) entropy of the strength-input candidate against the current + // charset union: bits ≈ len × log2(charset size). + let candidate = app.strength_input.read(cx).content().trim().to_string(); + if !candidate.is_empty() && !charset.is_empty() { + let csize = charset.len() as f64; + let bits = candidate.len() as f64 * csize.log2(); + let guess_s = 2f64.powf(bits - 1.0) / hps; + app.state.push_log(format!( + "estimate: {} chars × log2({}) ≈ {bits:.0} bits — avg crack ~{} @ {}", + candidate.len(), + charset.len(), + fmt_dur(guess_s), + fmt_hps(hps) + )); + } else if candidate.is_empty() { + app.state.push_log("estimate: type a candidate for its entropy line"); } cx.notify(); }); } +/// One bruteforce charset preset chip. Toggling flips the app flag; +/// [`crate::attack::charset::compose`] unions the active chips with the +/// custom field at Start. +fn charset_chip( + id: &'static str, + label: &'static str, + active: bool, + view: &Entity, + cx: &gpui::App, + flag: fn(&mut AppRoot) -> &mut bool, +) -> gpui::Stateful { + let theme = cx.theme().clone(); + let hover = theme.accent_bg(); + div() + .id(gpui::SharedString::from(id)) + .px_2() + .py_1() + .rounded_md() + .border_1() + .border_color(theme.border()) + .cursor_pointer() + .text_xs() + .when(active, |el| el.bg(theme.accent_bg())) + .when(!active, |el| el.hover(move |style| style.bg(hover))) + .child(label) + .on_click({ + let view = view.clone(); + move |_, _window, cx| { + view.update(cx, |app, cx| { + let f = flag(app); + *f = !*f; + cx.notify(); + }); + } + }) +} + +/// Throughput curve of the current run: one bar per progress sample, +/// right-aligned (newest at the right edge), height scaled to the run's +/// own maximum so a CPU-scale run doesn't render as a flat line next to +/// GPU-scale history. +fn hps_curve( + hist: &std::collections::VecDeque, + accent: gpui::Hsla, +) -> Option { + if hist.len() < 2 { + return None; + } + const COLUMNS: usize = 40; + const MAX_H: f32 = 14.0; + let max = hist.iter().copied().fold(0.0f64, f64::max).max(1.0); + let mut cols: Vec = Vec::with_capacity(COLUMNS); + let shown: Vec = hist.iter().copied().rev().take(COLUMNS).collect(); + for _ in 0..COLUMNS.saturating_sub(shown.len()) { + cols.push(div().w(px(6.)).h(px(1.))); + } + for h in shown.iter().rev() { + let hpx = (2.0 + MAX_H * (*h as f32 / max as f32)).min(MAX_H + 2.0); + cols.push(div().w(px(6.)).h(px(hpx)).bg(accent)); + } + Some(h_stack().gap_1().items_end().children(cols).into_any_element()) +} + pub fn render( app: &mut AppRoot, view: &Entity, @@ -208,24 +999,267 @@ pub fn render( let theme = cx.theme().clone(); let cracker = &app.state.cracker; let running = cracker.running || app.crack_inflight; - // Real runs stream an unknown-size wordlist: progress fraction is only - // meaningful in the bounded mock run. - let frac = if app.is_mock { - (cracker.tried as f64 / WORDLIST_TOTAL as f64).clamp(0.0, 1.0) + let rainbow_building = cracker.rainbow_building; + // Coverage fraction: mock is bounded by construction; real runs get + // their worst-case total from the worker (wordlist lines, brute + // space, table entries) when countable. + let effective_total = if app.is_mock { + Some(WORDLIST_TOTAL) } else { - 0.0 + cracker.total.filter(|t| *t > 0) }; - // Real mode: cracker needs the radio free — capture must be stopped - // and a service must have run at least once (it owns the cracker's - // stop flag). After the first "Stop capture" this stays permanently - // unblocked: the service is kept alive across sessions. - let crack_blocked = - !app.is_mock && (app.state.iface_running || app.service.is_none()); - let candidates = if app.is_mock { - format!("candidates: {} / {WORDLIST_TOTAL}", cracker.tried) + let frac = effective_total + .map(|t| (cracker.tried as f64 / t as f64).clamp(0.0, 1.0)) + .unwrap_or(0.0); + let candidates = if let Some(t) = effective_total { + format!("candidates: {} / {t}", cracker.tried) } else { format!("candidates: {}", cracker.tried) }; + // Worst-case remaining time (real runs): every untried candidate at + // the current measured rate. + let eta = (!app.is_mock && running) + .then(|| fmt_worst_case(cracker.tried, cracker.hps, cracker.total)) + .flatten(); + + // Per-mode inputs, swapped under the attack-mode dropdown. + let mode_inputs: gpui::AnyElement = match app.attack_mode.as_str() { + "bruteforce" => h_stack() + .gap_2() + .items_center() + .child(charset_chip("cs-lower", "a-z", app.cs_lower, view, cx, |a| &mut a.cs_lower)) + .child(charset_chip("cs-upper", "A-Z", app.cs_upper, view, cx, |a| &mut a.cs_upper)) + .child(charset_chip("cs-digits", "0-9", app.cs_digits, view, cx, |a| &mut a.cs_digits)) + .child(charset_chip("cs-special", "!@#…", app.cs_special, view, cx, |a| &mut a.cs_special)) + .child(charset_chip("cs-freq-order", "freq-order", app.freq_order, view, cx, |a| { + &mut a.freq_order + })) + .child( + div().w(px(160.)).child( + text_field(&app.charset_input, cx) + .placeholder("custom chars") + .full_width(true), + ), + ) + .child( + div().w(px(64.)).child( + text_field(&app.len_min_input, cx) + .placeholder("min") + .full_width(true), + ), + ) + .child( + div().w(px(64.)).child( + text_field(&app.len_max_input, cx) + .placeholder("max") + .full_width(true), + ), + ) + .child(small("chips + custom · min..max len · freq-order: common characters first").muted()) + .into_any_element(), + "rules" => h_stack() + .gap_2() + .items_end() + .child( + div().w(px(320.)).child( + text_field(&app.wordlist_input, cx) + .placeholder("/path/to/wordlist") + .full_width(true), + ), + ) + .child( + div().w(px(320.)).child( + text_field(&app.rules_input, cx) + .placeholder("/path/to/rules (hashcat-subset)") + .full_width(true), + ), + ) + .child(small("word × mutation rules").muted()) + .into_any_element(), + "hybrid" => h_stack() + .gap_2() + .items_center() + .child( + div().w(px(280.)).child( + text_field(&app.wordlist_input, cx) + .placeholder("/path/to/wordlist") + .full_width(true), + ), + ) + .child(charset_chip("cs-lower", "a-z", app.cs_lower, view, cx, |a| &mut a.cs_lower)) + .child(charset_chip("cs-upper", "A-Z", app.cs_upper, view, cx, |a| &mut a.cs_upper)) + .child(charset_chip("cs-digits", "0-9", app.cs_digits, view, cx, |a| &mut a.cs_digits)) + .child(charset_chip("cs-special", "!@#…", app.cs_special, view, cx, |a| &mut a.cs_special)) + .child( + div().w(px(120.)).child( + text_field(&app.charset_input, cx) + .placeholder("custom chars") + .full_width(true), + ), + ) + .child( + div().w(px(56.)).child( + text_field(&app.hyb_min_input, cx) + .placeholder("min") + .full_width(true), + ), + ) + .child( + div().w(px(56.)).child( + text_field(&app.hyb_max_input, cx) + .placeholder("max") + .full_width(true), + ), + ) + .child(small("word + charset suffix len min..max (1..=4)").muted()) + .into_any_element(), + "rainbow" => h_stack() + .gap_2() + .items_end() + .child( + div().w(px(360.)).child( + text_field(&app.rainbow_input, cx) + .placeholder("/path/to/pmk-table") + .full_width(true), + ), + ) + .child( + div().w(px(280.)).child( + text_field(&app.wordlist_input, cx) + .placeholder("wordlist to build from") + .full_width(true), + ), + ) + .child( + button("btn-rainbow-build", "Build table") + .disabled(rainbow_building || running) + .on_click({ + let view = view.clone(); + move |_, window, cx| build(&view, window, cx) + }), + ) + .into_any_element(), + _ => div() + .w(px(360.)) + .child( + text_field(&app.wordlist_input, cx) + .placeholder("/path/to/wordlist") + .full_width(true), + ) + .into_any_element(), + }; + + // Recent cracker activity: surfaces errors, estimates, import and + // benchmark results that would otherwise only be visible on the Log + // page. + let activity: Vec = app + .state + .log + .iter() + .filter(|line| { + line.starts_with("cracker:") + || line.starts_with("rainbow:") + || line.starts_with("estimate:") + || line.starts_with("benchmark:") + || line.starts_with("import:") + || line.starts_with("pmk cache") + || line.starts_with("profiles:") + || line.contains("PASSWORD") + }) + .rev() + .take(5) + .cloned() + .collect::>() + .into_iter() + .rev() + .collect(); + + // Presets + recent wordlists: one-click chips applied to the + // wordlist/rules fields and (for presets) the attack-mode select. + let hover_bg = theme.accent_bg(); + let mut preset_row = h_stack().gap_2().items_center(); + let has_presets = !app.profiles.profiles.is_empty() || !app.profiles.recent_wordlists.is_empty(); + for p in &app.profiles.profiles { + let profile = p.clone(); + preset_row = preset_row.child( + div() + .id(gpui::SharedString::from(format!("preset-{}", p.name))) + .px_2() + .py_1() + .rounded_md() + .border_1() + .border_color(theme.border()) + .cursor_pointer() + .text_xs() + .hover(move |style| style.bg(hover_bg)) + .child(p.name.clone()) + .on_click({ + let view = view.clone(); + move |_, _window, cx| apply_preset(profile.clone(), &view, cx) + }), + ); + } + if !app.profiles.profiles.is_empty() { + preset_row = preset_row.child( + button("btn-preset-save", "Save preset") + .on_click({ + let view = view.clone(); + move |_, window, cx| save_preset(&view, window, cx) + }), + ); + } + let mut recent_row = h_stack().gap_2().items_center(); + for wl in &app.profiles.recent_wordlists { + let wl_path = wl.clone(); + let base = std::path::Path::new(wl) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| wl.clone()); + recent_row = recent_row.child( + div() + .id(gpui::SharedString::from(format!("recent-{wl}"))) + .px_2() + .py_1() + .rounded_md() + .border_1() + .border_color(theme.border()) + .cursor_pointer() + .text_xs() + .hover(move |style| style.bg(hover_bg)) + .child(base) + .on_click({ + let view = view.clone(); + move |_, _window, cx| { + let wl = wl_path.clone(); + view.update(cx, |app, cx| { + app.wordlist_input.update(cx, |input, cx| { + input.set_content(wl, cx); + }); + cx.notify(); + }); + } + }), + ); + } + + // Benchmark card lines (below the Start/Stop row). + let bench_gpu_line = match app.state.bench_gpu { + Some(g) => format!("GPU: {}", fmt_hps(g)), + None => { + if app.state.bench_cpu.is_some() { + "GPU: none (CPU only)".to_string() + } else { + "not measured — run Benchmark".to_string() + } + } + }; + let bench_cpu_line = app + .state + .bench_cpu + .map(|c| format!("CPU: {}", fmt_hps(c))) + .unwrap_or_default(); + let bench_disabled = + app.bench_running || app.crack_inflight || cracker.running || cracker.rainbow_building; let mut page = v_stack() .size_full() @@ -236,22 +1270,44 @@ pub fn render( .items_center() .gap_3() .child(h3("Handshake Cracker")) - .child(small("PBKDF2-SHA1 · WPA/WPA2")), + .child(small("PBKDF2-SHA1 · WPA/WPA2")) + .child(div().flex_1()) + .child( + button("btn-import", "Import .cap/.pcap/.hc22000") + .disabled(app.import_busy) + .on_click({ + let view = view.clone(); + move |_, window, cx| import_captures(&view, window, cx) + }), + ), ) + .when(has_presets, |el| { + el.child(preset_row) + .when( + !app.profiles.recent_wordlists.is_empty() || !app.profiles.profiles.is_empty(), + |el2| el2.child(recent_row), + ) + }) + .when(!has_presets, |el| { + // No saved state yet — still offer one-click saving of the + // current setup. + el.child( + h_stack().gap_2().items_center().child( + button("btn-preset-save", "Save preset") + .on_click({ + let view = view.clone(); + move |_, window, cx| save_preset(&view, window, cx) + }), + ), + ) + }) .child( h_stack() .gap_3() .items_end() .child(div().w(px(360.)).child(app.target_select.clone())) - .child( - div() - .w(px(360.)) - .child( - text_field(&app.wordlist_input, cx) - .placeholder("/path/to/wordlist") - .full_width(true), - ), - ) + .child(div().w(px(200.)).child(app.attack_select.clone())) + .child(mode_inputs) .child(text(backend_label(app.is_mock)).small().muted()), ) .child( @@ -260,7 +1316,7 @@ pub fn render( .items_center() .child( button("btn-crack-start", "Start") - .disabled(running || crack_blocked) + .disabled(running || app.bench_running) .on_click({ let view = view.clone(); move |_, window, cx| start(&view, window, cx) @@ -275,14 +1331,7 @@ pub fn render( move |_, window, cx| stop(&view, window, cx) }), ) - .when(running, |el| el.child(loading_indicator().small())) - .when(crack_blocked, |el| { - el.child(small(if app.state.iface_running { - "stop capture first — cracker needs the radio" - } else { - "start then stop capture to enable the cracker" - })) - }), + .when(running, |el| el.child(loading_indicator().small())), ) .child(gpuikit::elements::separator::separator()) .child( @@ -291,14 +1340,99 @@ pub fn render( .child(small(format!("rate: {}", fmt_hps(if running { cracker.hps } else { 0.0 })))) .child(small(candidates)) .child( - small(if app.is_mock { - format!("{:.1}%", frac * 100.0) - } else { - String::new() + small({ + // Coverage % whenever a total exists; ETA needs a + // live run too. + let pct = effective_total.map(|_| format!("{:.1}%", frac * 100.0)); + match (pct, &eta) { + (Some(p), Some(e)) => format!("{p} · {e}"), + (Some(p), None) => p, + (None, Some(e)) => e.clone(), + (None, None) => String::new(), + } }), ), ) - .child(progress(frac as f32).width(px(520.))); + .child(progress(frac as f32).width(px(520.))) + .children( + hps_curve(&app.state.hps_hist, theme.accent()).map(|curve| { + v_stack() + .gap_1() + .child(small("rate over time (one bar per progress sample)").muted()) + .child(curve) + }), + ) + .child( + // Benchmark card: measured crack speed on this machine. + h_stack() + .gap_3() + .items_center() + .p_3() + .rounded_md() + .border_1() + .border_color(theme.border()) + .child(small("crack speed on this machine")) + .child( + button("btn-benchmark", "Benchmark (3s)") + .disabled(bench_disabled) + .on_click({ + let view = view.clone(); + move |_, window, cx| benchmark(&view, window, cx) + }), + ) + .when(app.bench_running, |el| el.child(loading_indicator().small())) + .child(small(bench_gpu_line).muted()) + .child(small(bench_cpu_line).muted()), + ) + .child( + // Estimator card: worst-case times from the measured rate. + h_stack() + .gap_3() + .items_center() + .p_3() + .rounded_md() + .border_1() + .border_color(theme.border()) + .child(small("candidate strength / time estimate")) + .child( + div().w(px(220.)).child( + text_field(&app.strength_input, cx) + .placeholder("type a candidate password") + .full_width(true), + ), + ) + .child( + button("btn-estimate", "Estimate") + .disabled(app.bench_running) + .on_click({ + let view = view.clone(); + move |_, window, cx| estimate(&view, window, cx) + }), + ) + .child(small("results land in recent activity below").muted()), + ); + + // Recent captures: the newest few crackable targets, so the page shows + // what material exists without opening the dropdown. Newest last in + // state → reversed for display. + let recent_caps: Vec = app + .state + .capture_descs() + .into_iter() + .rev() + .take(4) + .collect(); + if !recent_caps.is_empty() { + page = page.child( + v_stack() + .gap_1() + .child(small("recent captures (all of them are in the target dropdown)").muted()) + .children(recent_caps.into_iter().map(|d| { + text(d).code().small().into_any_element() + })) + .into_any_element(), + ); + } if let Some(found) = &cracker.found { page = page.child( @@ -315,5 +1449,78 @@ pub fn render( ); } + // Interrupted-run resume banner (saved session file matched to a + // loaded capture; hidden while anything runs). + if !running && !rainbow_building && !app.is_mock { + if let Some(r) = &cracker.resume { + let status = match r.total { + Some(t) => format!("{} / {t} tried", r.done), + None => format!("{} tried", r.done), + }; + page = page.child( + h_stack() + .gap_3() + .items_center() + .p_3() + .rounded_md() + .border_1() + .border_color(theme.border()) + .bg(theme.accent_bg()) + .child(small(format!( + "saved run: {} — {} · {status}", + r.target_desc, + r.attack.describe() + ))) + .child( + button("btn-crack-resume", "Resume") + .on_click({ + let view = view.clone(); + move |_, window, cx| resume_saved(&view, window, cx) + }), + ) + .child( + button("btn-crack-discard", "Discard") + .destructive() + .on_click({ + let view = view.clone(); + move |_, window, cx| discard_saved(&view, window, cx) + }), + ), + ); + } + } + + if !activity.is_empty() { + let mut block = v_stack().gap_1(); + for line in activity { + block = block.child(small(line).muted()); + } + page = page.child(block); + } + + if rainbow_building { + page = page.child( + h_stack() + .gap_3() + .items_center() + .child(loading_indicator().small()) + .child(small(format!( + "rainbow build: {} PMKs · {} · {}", + cracker.rainbow_done, + fmt_hps(cracker.rainbow_hps), + fmt_worst_case(cracker.rainbow_done, cracker.rainbow_hps, cracker.rainbow_total) + .unwrap_or_default() + ))) + .child( + button("btn-rainbow-stop", "Stop build") + .destructive() + .on_click({ + let view = view.clone(); + move |_, window, cx| build_stop(&view, window, cx) + }), + ), + ); + } + page } diff --git a/src/ui/log.rs b/src/ui/log.rs index 79f045f..6a2e381 100644 --- a/src/ui/log.rs +++ b/src/ui/log.rs @@ -1,29 +1,33 @@ -//! Log page: scrolling monospace view of the backend event log, newest -//! entries first. +//! Log page: read-only multiline text area over the backend event log +//! (plain text widgets are NOT selectable; the input gives mouse- +//! selection + Ctrl-C for free). A "Copy log" button puts the whole +//! buffer, oldest first, straight on the clipboard. -use gpui::{Context, Entity, ParentElement, Styled, Window}; -use gpuikit::elements::scroll_area::scroll_area; -use gpuikit::elements::typography::{h3, small, text}; +use gpui::{ClipboardItem, Context, Entity, ParentElement, Styled, Window}; +use gpuikit::elements::button::button; +use gpuikit::elements::input::text_area; +use gpuikit::elements::typography::{h3, small}; use gpuikit::layout::{h_stack, v_stack}; -use gpuikit::theme::{ActiveTheme, Themeable}; use crate::ui::app::AppRoot; pub fn render( app: &mut AppRoot, - _view: &Entity, + view: &Entity, _window: &mut Window, cx: &mut Context, ) -> gpui::Div { - let theme = cx.theme().clone(); - - let mut lines_view = v_stack().gap_0p5(); - if app.state.log.is_empty() { - lines_view = lines_view.child(small("log is empty")); - } else { - for line in app.state.log.iter().rev() { - lines_view = lines_view.child(text(line.clone()).code().small()); - } + // Sync the read-only view with the log buffer, oldest first. + let joined = app + .state + .log + .iter() + .cloned() + .collect::>() + .join("\n"); + if app.log_input.read(cx).content() != joined { + app.log_input + .update(cx, |input, cx| input.set_content_silent(joined, cx)); } v_stack() @@ -35,18 +39,29 @@ pub fn render( .items_center() .gap_3() .child(h3("Log")) - .child(small(format!("{} lines (newest first)", app.state.log.len()))), - ) - .child( - scroll_area("log-scroll") - .vertical() - .full_height(true) - .child( - lines_view - .w_full() - .p_2() - .rounded_md() - .bg(theme.surface_secondary()), - ), + .child(small(format!( + "{} lines — click, drag, Ctrl-A/Ctrl-C to copy", + app.state.log.len() + ))) + .child(gpui::div().flex_1()) + .child(button("btn-copy-log", "Copy log").on_click({ + let view = view.clone(); + move |_, _window, cx| { + let joined = view + .read(cx) + .state + .log + .iter() + .cloned() + .collect::>() + .join("\n"); + cx.write_to_clipboard(ClipboardItem::new_string(joined)); + view.update(cx, |app, cx| { + app.state.push_log("log copied to clipboard"); + cx.notify(); + }); + } + })), ) + .child(gpui::div().flex_1().min_h_0().child(text_area(&app.log_input, cx))) } diff --git a/src/ui/mock.rs b/src/ui/mock.rs index d8dc581..bef0801 100644 --- a/src/ui/mock.rs +++ b/src/ui/mock.rs @@ -8,7 +8,8 @@ use std::time::{Duration, Instant}; use crossbeam_channel::Sender; use crate::common::{ - AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture, Security, now_ms, + AccessPoint, Akm, ChannelStat, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture, + ProbeInfo, Security, now_ms, }; /// Salted deterministic PRNG (xorshift64) — no rand crate, values only need @@ -43,9 +44,14 @@ pub const MOCK_CLIENTS: [MacAddr; 4] = [ MacAddr([0x44, 0x55, 0x66, 0x77, 0x88, 0x99]), ]; +/// Locally-administered MACs the mock pairs into one device group (the +/// MAC-randomization storyline: ROT1 visible from start, ROT2 "rotates in"). +pub const MOCK_ROT1: MacAddr = MacAddr([0x02, 0xa0, 0xb1, 0xc2, 0xd3, 0xe4]); +pub const MOCK_ROT2: MacAddr = MacAddr([0x06, 0x5f, 0x4e, 0x3d, 0x2c, 0x1b]); + fn seed_aps() -> Vec { let now = now_ms(); - let ap = |mac: [u8; 6], ssid: &str, channel, security, rssi| AccessPoint { + let ap = |mac: [u8; 6], ssid: &str, channel, security, rssi, akms: Vec| AccessPoint { bssid: MacAddr(mac), ssid: ssid.to_string(), channel, @@ -53,31 +59,96 @@ fn seed_aps() -> Vec { rssi_dbm: rssi, beacons: 200, last_seen_ms: now, + akms, }; vec![ - ap([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], "parafin", 6, Security::Wpa2, -42), - ap([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e], "labnet", 1, Security::Wpa2, -55), - ap([0x02, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e], "coffeeshop", 11, Security::Wpa2, -68), - ap([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb], "corp-wpa3", 36, Security::Wpa3, -61), - ap([0x02, 0xde, 0xad, 0xbe, 0xef, 0x00], "legacy-prn", 3, Security::Wep, -80), - ap([0x02, 0x00, 0x11, 0x22, 0x33, 0x44], "open-wifi", 6, Security::Open, -72), + ap( + [0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], + "parafin", + 6, + Security::Wpa2, + -42, + vec![Akm::Psk], + ), + ap( + [0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e], + "labnet", + 1, + Security::Wpa2, + -55, + vec![Akm::Psk], + ), + ap( + [0x02, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e], + "coffeeshop", + 11, + Security::Wpa2, + -68, + vec![Akm::Psk], + ), + ap( + [0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb], + "corp-wpa3", + 36, + Security::Wpa3, + -61, + vec![Akm::Psk, Akm::Sae], + ), + ap( + [0x02, 0xde, 0xad, 0xbe, 0xef, 0x00], + "legacy-prn", + 3, + Security::Wep, + -80, + Vec::new(), + ), + ap( + [0x02, 0x00, 0x11, 0x22, 0x33, 0x44], + "open-wifi", + 6, + Security::Open, + -72, + Vec::new(), + ), + // Same SSID as `parafin` but OPEN + different BSSID: trips the + // UI's rogue-AP detection so the warning path is visible in mock. + ap( + [0x02, 0x66, 0x66, 0x66, 0x66, 0x66], + "parafin", + 11, + Security::Open, + -77, + Vec::new(), + ), ] } fn seed_clients() -> Vec { let now = now_ms(); - let cl = |mac: MacAddr, ap: MacAddr, rssi| ClientInfo { + let cl = |mac: MacAddr, ap: MacAddr, rssi, connected: bool| ClientInfo { mac, ap: Some(ap), rssi_dbm: rssi, frames: 40, last_seen_ms: now, + connected, + ident_group: None, + ident_conf: None, }; vec![ - cl(MOCK_CLIENTS[0], MOCK_BSSID, -44), - cl(MOCK_CLIENTS[1], MOCK_BSSID, -51), - cl(MOCK_CLIENTS[2], MacAddr([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e]), -60), - cl(MOCK_CLIENTS[3], MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]), -63), + cl(MOCK_CLIENTS[0], MOCK_BSSID, -44, true), + cl(MOCK_CLIENTS[1], MOCK_BSSID, -51, true), + cl(MOCK_CLIENTS[2], MacAddr([0x02, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e]), -60, true), + // Locally-administered (randomized) MAC — the ROT2 milestone below + // pairs it with ROT1 as one physical radio. + cl(MOCK_ROT1, MOCK_BSSID, -48, true), + // Deauth-flagged so the disconnected state is visible in mock mode. + cl( + MOCK_CLIENTS[3], + MacAddr([0x02, 0xff, 0xee, 0xdd, 0xcc, 0xbb]), + -63, + false, + ), ] } @@ -148,7 +219,7 @@ pub fn spawn_mock(tx: Sender) { fn run(tx: Sender) { let _ = tx.send(Event::Log(format!( - "mock: scanning on {MOCK_IFACE} (6 APs, 4 clients)" + "mock: scanning on {MOCK_IFACE} (7 APs, 4 clients)" ))); let mut rng = Rng(0x9e37_79b9_7f4a_7c15); @@ -163,6 +234,21 @@ fn run(tx: Sender) { let started = Instant::now(); let mut stage = 0usize; + let mut tick = 0u64; + // Drifting cumulative per-channel counters for the ChannelStats feed. + let mut chan_frames: [u64; 4] = [120, 980, 340, 60]; + let mut chan_beacons: [u64; 4] = [40, 210, 90, 12]; + // Probe-request feed cycles these (client, ssid) pairs. + const PROBE_FEED: &[(MacAddr, Option<&str>)] = &[ + (MOCK_CLIENTS[0], Some("HOME-WIFI")), + (MOCK_CLIENTS[1], Some("labnet")), + (MOCK_CLIENTS[2], None), + (MOCK_CLIENTS[3], Some("coffeeshop")), + (MOCK_CLIENTS[1], None), + ]; + let mut probe_step = 0usize; + let mut ident_fed = false; + let mut deauth_alert_sent = false; const LOG_LINES: &[&str] = &[ "hop: ch 1 → ch 6", "probe request from 11:22:33:44:55:66 (\"labnet\")", @@ -175,9 +261,73 @@ fn run(tx: Sender) { loop { thread::sleep(Duration::from_millis(200)); + tick += 1; let t = started.elapsed().as_secs_f32(); let now = now_ms(); + // Per-channel activity snapshot every ~2 s (10 ticks). + if tick % 10 == 0 { + let mut stats = Vec::with_capacity(4); + for (i, ch) in [1u8, 6, 11, 36].iter().enumerate() { + chan_frames[i] += 20 + rng.below(180); + chan_beacons[i] += rng.below(6); + stats.push(ChannelStat { + channel: *ch, + frames: chan_frames[i], + beacons: chan_beacons[i], + }); + } + let _ = tx.send(Event::ChannelStats(stats)); + } + + // Probe-request feed every ~3 s (15 ticks). + if tick % 15 == 0 { + let (client, ssid) = PROBE_FEED[probe_step % PROBE_FEED.len()]; + probe_step += 1; + let _ = tx.send(Event::ProbeObserved(ProbeInfo { + client, + ssid: ssid.map(str::to_string), + rssi_dbm: -(40 + rng.below(45) as i8), + at_ms: now, + })); + } + + // MAC-rotation storyline at ~6 s: a new randomized MAC appears and + // the correlator pairs both into device group #1. + if !ident_fed && t >= 6.0 { + ident_fed = true; + let _ = tx.send(Event::ClientIdent { + mac: MOCK_ROT1, + group: 1, + confidence: crate::common::IdentConfidence::Strong, + }); + let _ = tx.send(Event::ClientUpdated(ClientInfo { + mac: MOCK_ROT2, + ap: Some(MOCK_BSSID), + rssi_dbm: -46, + frames: 3, + last_seen_ms: now, + connected: true, + ident_group: None, + ident_conf: None, + })); + let _ = tx.send(Event::ClientIdent { + mac: MOCK_ROT2, + group: 1, + confidence: crate::common::IdentConfidence::Strong, + }); + } + + // One foreign-deauth storm milestone at ~12 s. + if !deauth_alert_sent && t >= 12.0 { + deauth_alert_sent = true; + let _ = tx.send(Event::DeauthAlert { + source: MOCK_BSSID, + target: MacAddr::BROADCAST, + count: 64, + }); + } + // RSSI drift + beacon/frame counters on every tick. for ap in &mut aps { ap.rssi_dbm = (ap.rssi_dbm + (rng.below(5) as i8 - 2)).clamp(-90, -30); diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 0f5ba97..971513b 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -8,7 +8,7 @@ mod app; mod attacks; mod cracker; mod log; -mod mock; +pub(crate) mod mock; mod networks; pub mod state; diff --git a/src/ui/networks.rs b/src/ui/networks.rs index f1a71d7..cd07f18 100644 --- a/src/ui/networks.rs +++ b/src/ui/networks.rs @@ -3,26 +3,45 @@ use gpui::{Context, Entity, IntoElement, ParentElement, Styled, Window, div, px}; use gpuikit::elements::badge::badge; +use gpuikit::elements::button::button; +use gpuikit::elements::progress::progress; use gpuikit::elements::table::{CellAlign, Column, Row, SortDirection, Table, table}; -use gpuikit::elements::typography::{h3, small}; -use gpuikit::layout::v_stack; +use gpuikit::elements::text_field::text_field; +use gpuikit::elements::typography::{h3, small, text}; +use gpuikit::layout::{h_stack, v_stack}; +use gpuikit::theme::{ActiveTheme, Themeable}; -use crate::common::{AccessPoint, ClientInfo, MacAddr, Security}; +use crate::common::{AccessPoint, ClientInfo, MacAddr, ProbeInfo, Security}; use crate::ui::app::AppRoot; +use std::collections::VecDeque; + const COL_BSSID: usize = 0; const COL_SSID: usize = 1; -const COL_CH: usize = 2; -const COL_SEC: usize = 3; -const COL_RSSI: usize = 4; -const COL_BEACONS: usize = 5; -const COL_AGE: usize = 6; +// Column-order documentation; vendor columns are not sortable, so nothing +// references these by value (sort arms only name the sortable consts). +#[allow(dead_code)] +const COL_VENDOR: usize = 2; +const COL_LABEL: usize = 3; +const COL_CH: usize = 4; +const COL_BAND: usize = 5; +const COL_SEC: usize = 6; +const COL_RSSI: usize = 7; +const COL_BEACONS: usize = 8; +const COL_AGE: usize = 9; const CCOL_MAC: usize = 0; -const CCOL_AP: usize = 1; -const CCOL_RSSI: usize = 2; -const CCOL_FRAMES: usize = 3; -const CCOL_AGE: usize = 4; +#[allow(dead_code)] +const CCOL_VENDOR: usize = 1; +const CCOL_STATE: usize = 2; +const CCOL_LABEL: usize = 3; +const CCOL_AP: usize = 4; +const CCOL_RSSI: usize = 5; +const CCOL_FRAMES: usize = 6; +const CCOL_AGE: usize = 7; +// Device-group id (MAC-randomization pairing); not sortable. +#[allow(dead_code)] +const CCOL_ID: usize = 8; /// Human "last seen" age, e.g. `2s`, `5m`, `1h`. `last_seen_ms` comes from /// the UI/service-side process-local clock ([`crate::common::now_ms`]). @@ -37,22 +56,179 @@ pub fn age(last_seen_ms: u64) -> String { } } -fn sec_badge(sec: Security) -> gpuikit::elements::badge::Badge { +/// Band label for display: 2.4 GHz when the channel maps below 3 GHz, +/// else 5 GHz. (6 GHz channel numbers collide with 2.4 GHz in this app — +/// the scanner treats them as cosmetic, so 6 GHz APs may read "2.4".) +pub(crate) fn band(ch: u8) -> &'static str { + match crate::common::freq_of_channel(ch) { + Some(f) if f < 3000 => "2.4", + Some(_) => "5", + None => "?", + } +} + +pub(crate) fn sec_badge_label(label: &str, sec: Security) -> gpuikit::elements::badge::Badge { match sec { - Security::Open => badge(sec.label()).outline(), - Security::Wep => badge(sec.label()).destructive(), - Security::Wpa | Security::Wpa2 => badge(sec.label()), - Security::Wpa3 => badge(sec.label()).secondary(), + Security::Open => badge(label).outline(), + Security::Wep => badge(label).destructive(), + Security::Wpa | Security::Wpa2 => badge(label), + Security::Wpa3 => badge(label).secondary(), + } +} + +fn sec_badge(sec: Security) -> gpuikit::elements::badge::Badge { + sec_badge_label(sec.label(), sec) +} + +/// Refined security label for the badge. The AKM suites of the RSN IE know +/// more than the broad `Security` buckets: a transition AP (PSK+SAE) reads +/// `WPA2/3`, an SAE-only AP reads `WPA3`, an OWE-only AP `OWE`. +pub(crate) fn sec_label(ap: &AccessPoint) -> String { + let has = |k: crate::common::Akm| ap.akms.contains(&k); + if ap.security == Security::Wpa3 && has(crate::common::Akm::Sae) { + let pskish = has(crate::common::Akm::Psk) + || has(crate::common::Akm::PskSha256) + || has(crate::common::Akm::FtPsk); + if !pskish { + return "WPA3".to_string(); + } + } + // OWE ("enhanced open") still carries an RSN IE, so it lands in the + // Wpa2 bucket — only the AKM list reveals it. + if has(crate::common::Akm::Owe) && ap.akms.len() == 1 { + return "OWE".to_string(); } + ap.security.label().to_string() +} + +/// Station liveness badge: `up` while frames are flowing, `down` once the +/// scanner observed a deauth/disassoc hitting this client. +fn conn_badge(cl: &ClientInfo) -> gpuikit::elements::badge::Badge { + if cl.connected { + badge("up").secondary() + } else { + badge("down").destructive() + } +} + +/// Client-table text cell. Disconnected rows are dimmed so the flagged +/// stations visually recede from the live ones. +fn client_cell(cl: &ClientInfo, body: String, cx: &mut gpui::App) -> gpui::AnyElement { + let mut cell = div().child(body); + if !cl.connected { + cell = cell.text_color(cx.theme().fg_muted()); + } + cell.into_any_element() +} + +/// Clients-section subtitle: `N stations`, `N stations (M down)` when the +/// scanner flagged disconnects. +fn client_counts(app: &AppRoot) -> String { + let total = app.state.clients.len(); + let down = app.state.clients.values().filter(|c| !c.connected).count(); + if down == 0 { + format!("{total} stations") + } else { + format!("{total} stations ({down} down)") + } +} + +/// OUI vendor for a MAC; `random` for locally-administered MACs (modern +/// phones/laptops rotate these — look at the ID column for the pairing), +/// `—` for unknown prefixes. +pub(crate) fn vendor_of(mac: &MacAddr) -> &'static str { + if crate::oui::is_locally_administered(mac) { + "random" + } else { + crate::oui::lookup(mac).unwrap_or("—") + } +} + +/// Normalized (trim + lowercase) form matching `state.rogue_ssids` keys. +fn norm_ssid(s: &str) -> String { + s.trim().to_lowercase() +} + +/// Sparkline cell: up to 20 bars from the recent RSSI history of `mac`, +/// right-aligned in recency order (last 20 values), padded to a stable +/// 20-slot width with transparent placeholders. Height maps rssi -95..-30 +/// dBm onto 2..10 px. +pub(crate) fn sparkline( + hist: Option<&VecDeque>, + accent: gpui::Hsla, +) -> gpui::AnyElement { + let mut bars: Vec = Vec::with_capacity(20); + if let Some(hist) = hist { + for &r in hist.iter().rev().take(20) { + let r = r as f32; + let h = ((r + 95.0) / 65.0 * 8.0 + 2.0).clamp(2.0, 10.0); + bars.push(div().w(px(3.)).h(px(h)).bg(accent)); + } + bars.reverse(); + } + while bars.len() < 20 { + bars.insert(0, div().w(px(3.)).h(px(1.))); + } + h_stack() + .items_end() + .gap(px(1.)) + .h(px(10.)) + .children(bars) + .into_any_element() +} + +/// MAC of the row the label editor targets: a selected client wins over +/// the selected AP. +fn label_target(app: &AppRoot) -> Option { + app.selected_client.or(app.selected) +} + +/// Prefill the label input with the current label of `mac` (empty when +/// none) — called whenever a row becomes the label target. +fn prefill_label(app: &AppRoot, mac: MacAddr, cx: &mut Context) { + let cur = app.state.labels.get(&mac).cloned().unwrap_or_default(); + app.label_input + .update(cx, |input, cx| input.set_content(cur, cx)); +} + +/// Save button: write the input as the label of the current target (empty +/// input = clear), then persist the whole map to `~/wifilab/labels.json`. +fn save_label(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { + view.update(cx, |app, cx| { + let Some(mac) = label_target(app) else { + app.state.push_log("label: select an AP or client row first"); + cx.notify(); + return; + }; + let raw = app.label_input.read(cx).content().trim().to_string(); + if raw.is_empty() { + if app.state.labels.remove(&mac).is_some() { + app.state.push_log(format!("label cleared: {mac}")); + } + } else { + app.state.labels.insert(mac, raw.clone()); + app.state.push_log(format!("label set: {mac} = \"{raw}\"")); + } + if let Err(e) = crate::store::save(&app.state.labels) { + app.state.push_log(format!("label save FAILED: {e:#}")); + } + cx.notify(); + }); } fn sorted_aps(app: &AppRoot) -> Vec { let mut rows: Vec = app.state.aps.values().cloned().collect(); if let Some(sort) = app.ap_sort { + let labels = &app.state.labels; let ord = |l: &AccessPoint, r: &AccessPoint| match sort.column { COL_BSSID => l.bssid.cmp(&r.bssid), COL_SSID => l.ssid.cmp(&r.ssid).then_with(|| l.bssid.cmp(&r.bssid)), + COL_LABEL => labels + .get(&l.bssid) + .cmp(&labels.get(&r.bssid)) + .then_with(|| l.bssid.cmp(&r.bssid)), COL_CH => l.channel.cmp(&r.channel), + COL_BAND => band(l.channel).cmp(band(r.channel)), COL_SEC => l.security.label().cmp(r.security.label()), COL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm), COL_BEACONS => l.beacons.cmp(&r.beacons), @@ -70,9 +246,26 @@ fn sorted_aps(app: &AppRoot) -> Vec { fn sorted_clients(app: &AppRoot) -> Vec { let mut rows: Vec = app.state.clients.values().cloned().collect(); if let Some(sort) = app.client_sort { + let labels = &app.state.labels; let ord = |l: &ClientInfo, r: &ClientInfo| match sort.column { CCOL_MAC => l.mac.cmp(&r.mac), - CCOL_AP => l.ap.cmp(&r.ap), + CCOL_STATE => l.connected.cmp(&r.connected), + CCOL_LABEL => labels + .get(&l.mac) + .cmp(&labels.get(&r.mac)) + .then_with(|| l.mac.cmp(&r.mac)), + CCOL_AP => { + // Sort by what the column shows: the AP's SSID (bssid falls + // back behind named entries, ties on raw MAC). + let key = |c: &ClientInfo| { + c.ap + .and_then(|b| app.state.aps.get(&b)) + .filter(|a| !a.ssid.is_empty()) + .map(|a| a.ssid.to_lowercase()) + .unwrap_or_else(|| "\u{10ffff}".into()) + }; + key(l).cmp(&key(r)).then_with(|| l.ap.cmp(&r.ap)) + } CCOL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm), CCOL_FRAMES => l.frames.cmp(&r.frames), CCOL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(), @@ -83,6 +276,11 @@ fn sorted_clients(app: &AppRoot) -> Vec { SortDirection::Descending => ord(l, r).reverse(), }); } + // Disconnected (deauth-flagged) stations sink below every connected + // row regardless of the active sort — the state column answers "what + // is still here", the partition is the answer at a glance. Stable + // sort keeps the user-chosen order within each group. + rows.sort_by_key(|c| !c.connected); rows } @@ -97,7 +295,14 @@ fn ap_table(app: &AppRoot, view: &Entity) -> Table { move |_window, cx| { view.update(cx, |app, cx| { app.selected = Some(bssid); + // Keep the target's AP row for the Attacks card — + // the live record can vanish (host-capture mode + // never re-scans), the snapshot holds. + if let Some(row) = app.state.aps.get(&bssid) { + app.selected_ap = Some(row.clone()); + } app.selected_client = None; + prefill_label(app, bssid, cx); app.state.push_log(format!("target selected: {bssid}")); cx.notify(); }); @@ -106,6 +311,9 @@ fn ap_table(app: &AppRoot, view: &Entity) -> Table { }) .collect::>(); + let rogues = app.state.rogue_ssids.clone(); + let rssi_hist = app.state.rssi_hist.clone(); + table("networks-aps") .column( Column::new("BSSID", |ap: &AccessPoint, _w, _cx| { @@ -114,14 +322,50 @@ fn ap_table(app: &AppRoot, view: &Entity) -> Table { .sortable() .min_width(px(150.)), ) - .column( - Column::new("SSID", |ap: &AccessPoint, _w, _cx| { - div().child(ap.ssid.clone()).into_any_element() + .column({ + let rogues = rogues.clone(); + Column::new("SSID", move |ap: &AccessPoint, _w, _cx| { + let mut cell = h_stack().gap_2().items_center().child(div().child( + if ap.ssid.is_empty() { + "".to_string() + } else { + ap.ssid.clone() + }, + )); + if !ap.ssid.is_empty() && rogues.contains(&norm_ssid(&ap.ssid)) { + cell = cell.child(badge("rogue?").destructive()); + } + // Weak-encryption marker: Open/WEP is a liability everyone + // in range should notice straight away. + if matches!(ap.security, Security::Open | Security::Wep) { + cell = cell.child(badge("weak").destructive()); + } + cell.into_any_element() }) .sortable() .flex(2.0) - .min_width(px(120.)), + .min_width(px(120.)) + }) + .column( + Column::new("VENDOR", |ap: &AccessPoint, _w, _cx| { + div().child(vendor_of(&ap.bssid)).into_any_element() + }) + .flex(1.0) + .min_width(px(90.)), ) + .column({ + // Snapshot per render pass (the table is rebuilt with fresh + // state each time anyway). + let labels = app.state.labels.clone(); + Column::new("LABEL", move |ap: &AccessPoint, _w, _cx| { + div() + .child(labels.get(&ap.bssid).cloned().unwrap_or_default()) + .into_any_element() + }) + .sortable() + .flex(1.0) + .min_width(px(100.)) + }) .column( Column::new("CH", |ap: &AccessPoint, _w, _cx| { div().child(ap.channel.to_string()).into_any_element() @@ -131,23 +375,50 @@ fn ap_table(app: &AppRoot, view: &Entity) -> Table { .end(), ) .column( - Column::new("SEC", |ap: &AccessPoint, _w, _cx| { - sec_badge(ap.security).into_any_element() + Column::new("BAND", |ap: &AccessPoint, _w, _cx| { + div() + .child(format!("{} GHz", band(ap.channel))) + .into_any_element() }) .sortable() - .fixed(px(110.)) - .align(CellAlign::Center), + .fixed(px(80.)) + .end(), ) .column( - Column::new("RSSI", |ap: &AccessPoint, _w, _cx| { - div() - .child(format!("{} dBm", ap.rssi_dbm)) - .into_any_element() +Column::new("SEC", |ap: &AccessPoint, _w, _cx| { + // Fixed-width badge slot: the AKM text starts at the same x in + // every row regardless of badge-label width. + let badge_slot = div() + .w(px(52.)) + .flex_none() + .child(sec_badge_label(&sec_label(ap), ap.security)); + let joined = ap + .akms + .iter() + .map(|a| a.label()) + .collect::>() + .join("+"); + let mut cell = h_stack().gap_1().items_center().child(badge_slot); + if !joined.is_empty() { + cell = cell + .child(div().flex_none().whitespace_nowrap().child(small(joined))) + .justify_start(); + } + cell.into_any_element() + }) + .sortable() + .fixed(px(170.)) + .align(CellAlign::Center), + ) + .column({ + let rssi_hist = rssi_hist.clone(); + Column::new("SIGNAL", move |ap: &AccessPoint, _w, cx| { + sparkline(rssi_hist.get(&ap.bssid), cx.theme().accent()) }) .sortable() .fixed(px(90.)) - .end(), - ) + .align(CellAlign::Center) + }) .column( Column::new("BEACONS", |ap: &AccessPoint, _w, _cx| { div().child(ap.beacons.to_string()).into_any_element() @@ -192,12 +463,37 @@ fn client_table(app: &AppRoot, view: &Entity) -> Table { .selected(app.selected_client == Some(mac)) .on_click(move |_window, cx| { view.update(cx, |app, cx| { - if let Some(ap) = ap { - app.selected = Some(ap); - app.selected_client = Some(mac); - app.state - .push_log(format!("target selected: {ap} (client {mac})")); - cx.notify(); + match ap { + // Mapped client: its AP becomes the target. + Some(ap) => { + app.selected = Some(ap); + if let Some(row) = app.state.aps.get(&ap) { + app.selected_ap = Some(row.clone()); + } + app.selected_client = Some(mac); + prefill_label(app, mac, cx); + app.state + .push_log(format!("target selected: {ap} (client {mac})")); + cx.notify(); + } + // Unmapped client (scanner never resolved the + // association): keep the current target, target + // the client at it for deauth. + None if app.selected.is_some() => { + let target = app.selected.expect("checked above"); + app.selected_client = Some(mac); + prefill_label(app, mac, cx); + app.state.push_log(format!( + "client selected: {mac} (AP unmapped — deauth targets {target})" + )); + cx.notify(); + } + None => { + app.state.push_log(format!( + "client {mac}: AP unknown — pick a target AP row first" + )); + cx.notify(); + } } }); }) @@ -206,51 +502,121 @@ fn client_table(app: &AppRoot, view: &Entity) -> Table { table("networks-clients") .column( - Column::new("MAC", |cl: &ClientInfo, _w, _cx| { - div().child(cl.mac.to_string()).into_any_element() + Column::new("MAC", |cl: &ClientInfo, _w, cx| { + client_cell(cl, cl.mac.to_string(), cx) }) .sortable() .min_width(px(150.)), ) .column( - Column::new("AP", |cl: &ClientInfo, _w, _cx| { - div() - .child( - cl.ap - .map(|ap: MacAddr| ap.to_string()) - .unwrap_or_else(|| "—".into()), - ) - .into_any_element() + Column::new("VENDOR", |cl: &ClientInfo, _w, cx| { + client_cell(cl, vendor_of(&cl.mac).to_string(), cx) + }) + .flex(1.0) + .min_width(px(90.)), + ) + .column( + Column::new("STATE", |cl: &ClientInfo, _w, _cx| { + conn_badge(cl).into_any_element() }) .sortable() - .min_width(px(150.)), + .fixed(px(90.)) + .align(CellAlign::Center), ) + .column({ + let labels = app.state.labels.clone(); + Column::new("LABEL", move |cl: &ClientInfo, _w, cx| { + client_cell(cl, labels.get(&cl.mac).cloned().unwrap_or_default(), cx) + }) + .sortable() + .flex(1.0) + .min_width(px(100.)) + }) + .column({ + // BSSID → SSID resolution: "which network does this client + // belong to" reads as a name, not a MAC. + let ap_names: std::collections::BTreeMap = app + .state + .aps + .iter() + .filter(|(_, a)| !a.ssid.is_empty()) + .map(|(b, a)| (*b, a.ssid.clone())) + .collect(); + Column::new("AP", move |cl: &ClientInfo, _w, cx| { + let Some(bssid) = cl.ap else { + return client_cell(cl, "—".into(), cx); + }; + match ap_names.get(&bssid) { + None => client_cell(cl, bssid.to_string(), cx), + Some(name) => { + let mut cell = div().child(name.clone()); + if !cl.connected { + cell = cell.text_color(cx.theme().fg_muted()); + } + let sub = div() + .text_color(cx.theme().fg_muted()) + .child(small(bssid.to_string())); + v_stack().child(cell).child(sub).into_any_element() + } + } + }) + .sortable() + .min_width(px(150.)) + }) .column( - Column::new("RSSI", |cl: &ClientInfo, _w, _cx| { - div() - .child(format!("{} dBm", cl.rssi_dbm)) - .into_any_element() + Column::new("RSSI", |cl: &ClientInfo, _w, cx| { + client_cell(cl, format!("{} dBm", cl.rssi_dbm), cx) }) .sortable() .fixed(px(90.)) .end(), ) .column( - Column::new("FRAMES", |cl: &ClientInfo, _w, _cx| { - div().child(cl.frames.to_string()).into_any_element() + Column::new("FRAMES", |cl: &ClientInfo, _w, cx| { + client_cell(cl, cl.frames.to_string(), cx) }) .sortable() .fixed(px(90.)) .end(), ) .column( - Column::new("AGE", |cl: &ClientInfo, _w, _cx| { - div().child(age(cl.last_seen_ms)).into_any_element() + Column::new("AGE", |cl: &ClientInfo, _w, cx| { + client_cell(cl, age(cl.last_seen_ms), cx) }) .sortable() .fixed(px(70.)) .end(), ) + .column({ + // Device-group id + member count (`#1~ (2)`: group 1, "~" = + // strong witness, two known MACs — the MAC-randomization + // pairing). Confidence labels per `IdentConfidence::label`. + let counts: std::collections::BTreeMap = app + .state + .ident_groups + .iter() + .map(|(g, ms)| (*g, ms.len())) + .collect(); + Column::new("ID", move |cl: &ClientInfo, _w, cx| { + let Some(gid) = cl.ident_group else { + return client_cell(cl, String::new(), cx); + }; + let conf = cl.ident_conf.map(|c| c.label()).unwrap_or(""); + let n = counts.get(&gid).copied().unwrap_or(1); + let body = if n > 1 { + format!("#{gid}{conf} ({n})") + } else { + format!("#{gid}{conf}") + }; + let mut cell = div().child(body); + if n > 1 { + cell = cell.text_color(cx.theme().accent()); + } + cell.into_any_element() + }) + .fixed(px(90.)) + .align(CellAlign::Center) + }) .rows(rows) .sorted_by(app.client_sort) .on_sort({ @@ -266,7 +632,218 @@ fn client_table(app: &AppRoot, view: &Entity) -> Table { .empty("No client stations observed") } -pub fn render(app: &mut AppRoot, view: &Entity, _window: &mut Window, _cx: &mut Context) -> gpui::Div { +/// Recently observed probe requests, newest first, capped at 300 rows. +fn probe_table(app: &AppRoot) -> Table { + let rows: Vec = app.state.probes.iter().rev().take(300).cloned().collect(); + let rogues = app.state.rogue_ssids.clone(); + + table("networks-probes") + .column( + Column::new("CLIENT", |p: &ProbeInfo, _w, _cx| { + div() + .child(format!("{} ({})", p.client, vendor_of(&p.client))) + .into_any_element() + }) + .min_width(px(190.)), + ) + .column({ + let rogues = rogues.clone(); + Column::new("SSID", move |p: &ProbeInfo, _w, cx| { + match &p.ssid { + Some(s) => { + let mut cell = div().child(s.clone()); + if !s.is_empty() && rogues.contains(&norm_ssid(s)) { + cell = cell.text_color(cx.theme().warning()); + } + cell.into_any_element() + } + None => div().child("").into_any_element(), + } + }) + .flex(2.0) + .min_width(px(120.)) + }) + .column( + Column::new("RSSI", |p: &ProbeInfo, _w, _cx| { + div() + .child(format!("{} dBm", p.rssi_dbm)) + .into_any_element() + }) + .fixed(px(90.)) + .end(), + ) + .column( + Column::new("AGE", |p: &ProbeInfo, _w, _cx| { + div().child(age(p.at_ms)).into_any_element() + }) + .fixed(px(70.)) + .end(), + ) + .rows(rows.into_iter().map(Row::new).collect::>()) + .max_h(px(220.)) + .empty("No probe requests observed") +} + +/// Per-channel activity strip: one cell per observed channel with a small +/// progress bar scaled to the busiest channel. Hidden when idle. Used as +/// the fallback of [`channel_activity`] until the timeline has ≥2 +/// snapshots. +fn channel_strip(app: &AppRoot) -> Option { + let mut stats = app.state.channel_stats.clone(); + if stats.is_empty() { + return None; + } + stats.sort_by_key(|s| s.channel); + let max_frames = stats.iter().map(|s| s.frames).max().unwrap_or(0); + Some( + h_stack() + .gap_3() + .items_center() + .children(stats.into_iter().map(|s| { + let frac = if max_frames < 1 { + 0.0 + } else { + s.frames as f32 / max_frames as f32 + }; + v_stack() + .gap_1() + .child(small(format!("ch{}", s.channel))) + .child(progress(frac).width(px(60.)).height(px(4.))) + .child(small(s.frames.to_string())) + })) + .into_any_element(), + ) +} + +/// Timeline over the static strip: one row per busiest channel (max 8), +/// each row a right-aligned run of per-snapshot frame-delta columns +/// (opacity = relative intensity). A channel hosting ≥4 APs gets a +/// crowded warning — overlapping BSSs eat each other's airtime. +fn channel_timeline(app: &AppRoot, theme: &gpuikit::theme::Theme) -> Option { + let tl = &app.state.chan_timeline; + if tl.len() < 2 { + return None; + } + const COLUMNS: usize = 45; + const CROWD_WARN: usize = 4; + + // Busiest channels by latest cumulative frame count. + let latest = tl.back().expect("len checked"); + let mut busy: Vec = latest.clone(); + busy.sort_by_key(|s| std::cmp::Reverse(s.frames)); + busy.truncate(8); + + // AP count per channel → crowded-channel warning. + let mut crowd: std::collections::HashMap = std::collections::HashMap::new(); + for ap in app.state.aps.values() { + if ap.channel > 0 { + *crowd.entry(ap.channel).or_default() += 1; + } + } + + let accent = theme.accent(); + let rows: Vec = busy + .iter() + .filter_map(|b| { + let ch = b.channel; + // Frame series for this channel across snapshots the scanner + // reported it in (missed snapshots are skipped, minor skew). + let series: Vec = tl + .iter() + .filter_map(|snap| snap.iter().find(|s| s.channel == ch).map(|s| s.frames)) + .collect(); + let deltas: Vec = series + .windows(2) + .map(|w| w[1].saturating_sub(w[0])) + .collect(); + if deltas.is_empty() { + return None; + } + let max = deltas.iter().copied().max().unwrap_or(0).max(1) as f32; + let shown: &[u64] = &deltas[deltas.len().saturating_sub(COLUMNS)..]; + let mut cols: Vec = Vec::with_capacity(COLUMNS); + // Left-pad quiet history so rows align at the newest edge. + for _ in 0..COLUMNS.saturating_sub(shown.len()) { + cols.push(div().w(px(4.)).h(px(12.))); + } + for &d in shown { + let a = 0.15 + 0.85 * (d as f32 / max); + cols.push(div().w(px(4.)).h(px(12.)).bg(accent.opacity(a))); + } + let crowd_n = *crowd.get(&ch).unwrap_or(&0); + let mut label = div().w(px(80.)).flex_none().text_xs(); + let label_text = if crowd_n >= CROWD_WARN { + format!("ch{ch} ⚠{crowd_n} APs") + } else { + format!("ch{ch}") + }; + if crowd_n >= CROWD_WARN { + label = label.text_color(theme.warning()); + } else { + label = label.text_color(theme.fg_muted()); + } + let last_delta = *deltas.last().unwrap_or(&0); + Some( + h_stack() + .gap_2() + .items_center() + .child(label.child(label_text)) + .child(h_stack().items_end().children(cols)) + .child( + div() + .w(px(70.)) + .flex_none() + .text_xs() + .text_color(theme.fg_muted()) + .child(format!("{last_delta} fr")), + ) + .into_any_element(), + ) + }) + .collect(); + if rows.is_empty() { + return None; + } + Some( + v_stack() + .gap_1() + .child(small(format!( + "channel activity — last {} snapshots (one column each), brightest = busiest", + tl.len() + ))) + .children(rows) + .into_any_element(), + ) +} + +/// Channel activity visualization: scrolling timeline once ≥2 snapshots +/// exist, static strip before that, hidden when silent. +fn channel_activity(app: &AppRoot, theme: &gpuikit::theme::Theme) -> Option { + channel_timeline(app, theme).or_else(|| channel_strip(app)) +} + +pub fn render(app: &mut AppRoot, view: &Entity, _window: &mut Window, cx: &mut Context) -> gpui::Div { + // Persistent label editor: applies to the selected row (a selected + // client wins over the selected AP — see [`label_target`]). + let label_bar = label_target(app).map(|mac| { + h_stack() + .items_center() + .gap_2() + .child(small("label for")) + .child(text(mac.to_string()).code().small().into_any_element()) + .child( + div() + .w(px(240.)) + .child(text_field(&app.label_input, cx).placeholder("name this device…")), + ) + .child(button("btn-label-save", "Save").on_click({ + let view = view.clone(); + move |_, window, cx| save_label(&view, window, cx) + })) + .child(small("(empty saves as no label)")) + .into_any_element() + }); + v_stack() .size_full() .gap_3() @@ -281,13 +858,23 @@ pub fn render(app: &mut AppRoot, view: &Entity, _window: &mut Window, _ app.state.aps.len() ))), ) + .children(label_bar) + .children(channel_activity(app, cx.theme())) .child(ap_table(app, view)) .child( gpuikit::layout::h_stack() .items_center() .gap_3() .child(h3("Clients")) - .child(small(format!("{} stations", app.state.clients.len()))), + .child(small(client_counts(app))), ) .child(client_table(app, view)) + .child( + gpuikit::layout::h_stack() + .items_center() + .gap_3() + .child(h3("Probes")) + .child(small(format!("{} observed", app.state.probes.len()))), + ) + .child(probe_table(app)) } diff --git a/src/ui/state.rs b/src/ui/state.rs index 9ce4cde..1735baa 100644 --- a/src/ui/state.rs +++ b/src/ui/state.rs @@ -1,9 +1,12 @@ //! Application state: the UI-side home for everything arriving over the //! service event channel (mock thread or privileged-service reader). -use std::collections::{BTreeMap, VecDeque}; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; -use crate::common::{AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture}; +use crate::common::{ + AccessPoint, ChannelStat, ClientInfo, Event, HandshakeCapture, IdentConfidence, MacAddr, + PmkidCapture, ProbeInfo, Security, +}; use crate::crypto::CrackTarget; /// Ring capacity of the on-screen log. @@ -22,6 +25,39 @@ pub struct CrackerState { pub tried: u64, /// Recovered password, once found. pub found: Option, + /// Rainbow-table build job in flight (RainbowProgress feeds the + /// counters, RainbowBuilt clears the flag). + pub rainbow_building: bool, + /// PMKs written by the running build job. + pub rainbow_done: u64, + /// Build job throughput. + pub rainbow_hps: f64, + /// Worst-case candidate total of the running crack (wordlist lines / + /// brute-force space / table entries), when countable. + pub total: Option, + /// Worst-case size of the table being built (wordlist lines). + pub rainbow_total: Option, + /// The currently running attack, tracked so the UI can persist a + /// resume session ([`crate::store::CrackSession`]) without the + /// worker's cooperation. Cleared when the run settles. + pub active_attack: Option, + /// A saved, interrupted run matched against a loaded capture — + /// shown as a resume banner on the cracker page. + pub resume: Option, +} + +/// Saved-run banner payload (mirror of [`crate::store::CrackSession`] +/// resolved to the capture's current description). +#[derive(Clone)] +pub struct ResumeInfo { + /// Dropdown description of the capture this run belongs to. + pub target_desc: String, + /// Attack definition at the saved candidate offset. + pub attack: crate::attack::Attack, + /// Candidates already tried when the run was saved. + pub done: u64, + /// Worst-case total of the saved run, when countable. + pub total: Option, } /// Everything the window renders. Updated exclusively by @@ -32,6 +68,10 @@ pub struct AppState { pub ifname: String, pub aps: BTreeMap, pub clients: BTreeMap, + /// User-assigned names by MAC (APs and clients share one namespace; + /// a MAC is unique). Persisted to `~/wifilab/labels.json` + /// ([`crate::store`]); UI-side only. + pub labels: BTreeMap, pub handshakes: Vec, pub pmkids: Vec, /// [`capture_descs`]-aligned crack targets: `capture_targets()[i]` is @@ -40,8 +80,59 @@ pub struct AppState { capture_targets: Vec, pub log: VecDeque, pub cracker: CrackerState, + /// Last per-channel frame/beacon counters snapshot + /// ([`Event::ChannelStats`]). + pub channel_stats: Vec, + /// Observed probe requests, newest last. + pub probes: VecDeque, + /// Recent RSSI samples per MAC (APs and clients keyed by their own + /// MAC) — the Networks page renders these as sparklines. + pub rssi_hist: HashMap>, + /// Normalized (trim, lowercase) SSIDs observed on more than one BSSID + /// with differing security — possible rogue APs. + pub rogue_ssids: HashSet, + /// One-shot rogue-AP alert message; taken by the app drain into a toast. + pub rogue_alert: Option, + /// One-shot deauth-storm alert message; taken by the app drain into a + /// toast. + pub deauth_alert: Option, + /// Last benchmark throughput (H/s); `None` = no GPU / not run yet. + pub bench_gpu: Option, + pub bench_cpu: Option, + /// MAC-randomization pairing ([`Event::ClientIdent`]): device-group id + + /// confidence per correlated MAC. Outlives the client row (groups keep + /// their members while any one of them is live). + pub idents: HashMap, + /// Reverse view per group: set of currently-known member MACs (live + /// rows + remembered) — the Networks page shows "N MACs" per device. + pub ident_groups: HashMap>, + /// One-shot pairing alert ("device rotated MAC, paired into group #N"); + /// taken by the app drain into a toast. + pub ident_alert: Option, + /// SSID (normalized) → BSSID → security seen, backing `rogue_ssids`. + seen_ssids: BTreeMap>, + /// ChannelStats time-series, one entry per snapshot, oldest first + /// (~3 min at the scanner's 2 s cadence) — the Networks page renders + /// it as a scrolling per-channel activity timeline. + pub chan_timeline: VecDeque>, + /// Crack H/s samples, one per [`Event::CrackProgress`] of the current + /// run (cleared at run start) — the Cracker page renders it as a + /// throughput curve. + pub hps_hist: VecDeque, } +/// Cap on [`AppState::probes`] (oldest dropped first). +const PROBE_CAP: usize = 2000; + +/// RSSI samples kept per MAC in [`AppState::rssi_hist`]. +const RSSI_CAP: usize = 60; + +/// ChannelStats snapshots kept in [`AppState::chan_timeline`]. +const CHAN_TL_CAP: usize = 90; + +/// H/s samples kept in [`AppState::hps_hist`]. +const HPS_CAP: usize = 240; + impl AppState { pub fn new(ifname: &str) -> Self { AppState { @@ -49,12 +140,42 @@ impl AppState { ifname: ifname.to_string(), aps: BTreeMap::new(), clients: BTreeMap::new(), + labels: BTreeMap::new(), handshakes: Vec::new(), pmkids: Vec::new(), capture_targets: Vec::new(), log: VecDeque::with_capacity(LOG_CAP), cracker: CrackerState::default(), + channel_stats: Vec::new(), + probes: VecDeque::with_capacity(64), + rssi_hist: HashMap::new(), + rogue_ssids: HashSet::new(), + rogue_alert: None, + deauth_alert: None, + bench_gpu: None, + bench_cpu: None, + idents: HashMap::new(), + ident_groups: HashMap::new(), + ident_alert: None, + seen_ssids: BTreeMap::new(), + chan_timeline: VecDeque::with_capacity(CHAN_TL_CAP + 1), + hps_hist: VecDeque::with_capacity(HPS_CAP + 1), + } + } + + /// Append one RSSI sample for `mac` (APs and clients keyed by their + /// own MAC), capping the per-MAC history. + fn note_rssi(&mut self, mac: MacAddr, rssi_dbm: i8) { + let hist = self.rssi_hist.entry(mac).or_default(); + if hist.len() == RSSI_CAP { + hist.pop_front(); } + hist.push_back(rssi_dbm); + } + + /// Normalize an SSID for rogue comparison (trim + lowercase). + fn norm_ssid(ssid: &str) -> String { + ssid.trim().to_lowercase() } /// Crack target described by `capture_descs()[i]` (cloned — the cracker @@ -63,6 +184,18 @@ impl AppState { self.capture_targets.get(i).cloned() } + /// The same capture as a [`crate::store::StoredCapture`] (resume + /// session identity), `capture_descs()`-aligned like + /// [`AppState::crack_target_at`]: handshakes first, then PMKIDs. + pub fn stored_capture_at(&self, i: usize) -> Option { + if i < self.handshakes.len() { + return Some(crate::store::StoredCapture::Handshake(self.handshakes[i].clone())); + } + self.pmkids + .get(i - self.handshakes.len()) + .map(|p| crate::store::StoredCapture::Pmkid(p.clone())) + } + pub fn push_log(&mut self, line: impl Into) { if self.log.len() == LOG_CAP { self.log.pop_front(); @@ -73,8 +206,73 @@ impl AppState { /// Reduce one service event into state. Returns `true` when the set of /// crackable captures changed (callers rebuild dependent widgets). pub fn apply(&mut self, event: Event) -> bool { + let changed = self.reduce(event); + self.sweep_stale_clients(); + changed + } + + /// Backstop mirror of the scanner's 60 s client-expiry: rows learned + /// before a scanner restart (the restart wipes the scanner's internal + /// map, so no ClientLost can ever come for them) would linger as "up" + /// forever without this. Clock-offset between the service and UI + /// epochs (both `now_ms`, different process-local zero points) is a + /// few seconds at most — negligible against a 60 s threshold. + fn sweep_stale_clients(&mut self) { + const UI_CLIENT_EXPIRE_MS: u64 = 60_000; + let now = crate::common::now_ms(); + let swept: Vec = self + .clients + .iter() + .filter(|(_, c)| now.saturating_sub(c.last_seen_ms) > UI_CLIENT_EXPIRE_MS) + .map(|(m, _)| *m) + .collect(); + for m in swept { + self.clients.remove(&m); + self.forget_ident(&m); + } + } + + /// Drop a MAC's pairing record (client row gone). + fn forget_ident(&mut self, mac: &MacAddr) { + if let Some((gid, _)) = self.idents.remove(mac) { + if let Some(set) = self.ident_groups.get_mut(&gid) { + set.remove(mac); + if set.is_empty() { + self.ident_groups.remove(&gid); + } + } + } + } + + fn reduce(&mut self, event: Event) -> bool { match event { Event::ApUpdated(ap) => { + self.note_rssi(ap.bssid, ap.rssi_dbm); + // Rogue detection: the same non-empty SSID advertised by a + // *different* BSSID with *different* security settings is + // the classic evil-twin smell (same security on multi-AP + // deployments is normal). + let norm = Self::norm_ssid(&ap.ssid); + if !norm.is_empty() { + let entry = self.seen_ssids.entry(norm.clone()).or_default(); + if !self.rogue_ssids.contains(&norm) { + let conflict = entry + .iter() + .find(|(b, sec)| **b != ap.bssid && **sec != ap.security); + if let Some((known, sec1)) = conflict { + self.rogue_ssids.insert(norm.clone()); + self.rogue_alert = Some(format!( + "possible rogue AP: \"{}\" on {} ({}) vs {} ({})", + norm, + known, + sec1.label(), + ap.bssid, + ap.security.label() + )); + } + } + entry.insert(ap.bssid, ap.security); + } self.aps.insert(ap.bssid, ap); false } @@ -82,10 +280,49 @@ impl AppState { self.aps.remove(&bssid); false } - Event::ClientUpdated(client) => { + Event::ClientUpdated(mut client) => { + self.note_rssi(client.mac, client.rssi_dbm); + // Overlay the known pairing (the wire fields may lag or be + // absent for clients learned before this process knew the + // group). + if let Some(&(gid, conf)) = self.idents.get(&client.mac) { + client.ident_group = Some(gid); + client.ident_conf = Some(conf); + } self.clients.insert(client.mac, client); false } + Event::ClientLost(mac) => { + self.clients.remove(&mac); + self.forget_ident(&mac); + false + } + Event::ClientIdent { mac, group, confidence } => { + let rotated = self + .ident_groups + .get(&group) + .is_some_and(|ms| ms.iter().any(|m| *m != mac)); + self.idents.insert(mac, (group, confidence)); + self.ident_groups.entry(group).or_default().insert(mac); + // Message names the whole rotation set — the actionable fact + // is "these N MACs are one radio". + let n = self.ident_groups.get(&group).map_or(1, |ms| ms.len()); + let msg = format!( + "device paired: {mac} → group #{group} ({n} MAC{}) [{}]", + if n == 1 { "" } else { "s" }, + confidence.label() + ); + self.push_log(msg.clone()); + if rotated { + self.ident_alert = Some(msg); + } + // Live row gets the badge immediately. + if let Some(c) = self.clients.get_mut(&mac) { + c.ident_group = Some(group); + c.ident_conf = Some(confidence); + } + false + } Event::HandshakeProgress { ap, client, have } => { self.push_log(format!( "4-way {ap} → {client}: {}/4 messages", @@ -114,10 +351,15 @@ impl AppState { self.push_log(format!("deauth: {count} frames → {target} (AP {ap})")); false } - Event::CrackProgress { done, hps } => { + Event::CrackProgress { done, hps, total } => { if self.cracker.running { self.cracker.tried = done; self.cracker.hps = hps; + self.cracker.total = total; + if self.hps_hist.len() == HPS_CAP { + self.hps_hist.pop_front(); + } + self.hps_hist.push_back(hps); } false } @@ -134,6 +376,19 @@ impl AppState { self.cracker.running = false; true // force dependent-widget refresh so the cracker page updates promptly } + Event::RainbowProgress { done, hps, total } => { + if self.cracker.rainbow_building { + self.cracker.rainbow_done = done; + self.cracker.rainbow_hps = hps; + self.cracker.rainbow_total = total; + } + false + } + Event::RainbowBuilt { path, entries } => { + self.push_log(format!("rainbow: table finished: {path} ({entries} PMKs)")); + self.cracker.rainbow_building = false; + false + } Event::Log(line) => { self.push_log(line); false @@ -142,6 +397,57 @@ impl AppState { self.push_log(format!("ERROR: {line}")); false } + Event::ChannelStats(stats) => { + if self.chan_timeline.len() == CHAN_TL_CAP { + self.chan_timeline.pop_front(); + } + self.chan_timeline.push_back(stats.clone()); + self.channel_stats = stats; + false + } + Event::ProbeObserved(probe) => { + self.note_rssi(probe.client, probe.rssi_dbm); + if self.probes.len() == PROBE_CAP { + self.probes.pop_front(); + } + self.probes.push_back(probe); + false + } + Event::BenchmarkDone { gpu_hps, cpu_hps } => { + self.bench_gpu = gpu_hps; + self.bench_cpu = Some(cpu_hps); + self.push_log(format!( + "benchmark: gpu {} H/s, cpu {} H/s", + gpu_hps.map(|h| h.to_string()).unwrap_or_else(|| "none".to_string()), + cpu_hps + )); + false + } + Event::DeauthAlert { source, target, count } => { + let msg = format!("DEAUTH STORM: {source} → {target} x{count}"); + self.push_log(msg.clone()); + self.deauth_alert = Some(msg); + false + } + Event::CaptureImported(cap) => { + match cap { + crate::common::ImportedCapture::Handshake(h) => { + self.push_log(format!( + "imported handshake: {} ({} ⇄ {})", + h.essid, h.ap, h.client + )); + self.capture_targets + .push(CrackTarget::Handshake(h.as_ref().clone())); + self.handshakes.push(*h); + } + crate::common::ImportedCapture::Pmkid(p) => { + self.push_log(format!("imported PMKID: {} ({})", p.essid, p.ap)); + self.capture_targets.push(CrackTarget::Pmkid(p.clone())); + self.pmkids.push(p); + } + } + true + } } } @@ -166,3 +472,40 @@ impl AppState { out } } + +#[cfg(test)] +mod tests { + use super::*; + + fn stat(ch: u8, frames: u64) -> ChannelStat { + ChannelStat { channel: ch, frames, beacons: 0 } + } + + #[test] + fn channel_timeline_keeps_snapshots_and_caps() { + let mut s = AppState::new("wlan0"); + for i in 0..(CHAN_TL_CAP + 5) { + s.apply(Event::ChannelStats(vec![stat(1, i as u64 + 1)])); + } + assert_eq!(s.chan_timeline.len(), CHAN_TL_CAP); + // Oldest dropped: the first surviving snapshot is frames=6. + assert_eq!(s.chan_timeline.front().unwrap()[0].frames, 6); + assert_eq!(s.channel_stats[0].frames, (CHAN_TL_CAP + 5) as u64); + } + + #[test] + fn hps_history_advances_only_while_running() { + let mut s = AppState::new("wlan0"); + s.apply(Event::CrackProgress { done: 10, hps: 100.0, total: None }); + assert!(s.hps_hist.is_empty(), "stopped run must not feed the curve"); + s.cracker.running = true; + s.apply(Event::CrackProgress { done: 20, hps: 200.0, total: Some(50) }); + s.apply(Event::CrackProgress { done: 30, hps: 300.0, total: Some(50) }); + assert_eq!( + s.hps_hist.iter().copied().collect::>(), + vec![200.0, 300.0] + ); + assert_eq!(s.cracker.tried, 30); + assert_eq!(s.cracker.total, Some(50)); + } +}