diff --git a/Cargo.lock b/Cargo.lock index 5dfca0b..13b98f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6886,6 +6886,7 @@ dependencies = [ "pbkdf2 0.13.0", "pollster 0.4.0", "serde", + "serde_json", "sha1", "thiserror 2.0.21", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 2d691a6..e8c9547 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ tracing = "0.1" tracing-subscriber = "0.3" clap = { version = "4", features = ["derive"] } serde = { version = "1", features = ["derive"] } +serde_json = "1" byteorder = "1" [profile.release] diff --git a/docs/USAGE.md b/docs/USAGE.md index e02e1c6..058059a 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -12,12 +12,16 @@ cargo build --release ./target/release/wifilab ``` -Privileges are handled **inside the UI**: when not running as root the -header shows a **"Elevate via polkit"** button — one click pops the -system polkit dialog, and the app restarts itself elevated (same window, -same selected interface). The unprivileged window closes automatically -once the elevated instance is up. Starting a capture while unprivileged -just logs a reminder; nothing fails mid-attack. +Privileges are handled by a **privileged service**: the UI itself never +needs root and never respawns. The first time you click **Start capture** +the app spawns the same binary as a child process with the hidden flag +`--privileged-worker` — directly when already root, otherwise through +`pkexec`, which pops the system polkit dialog **once per capture +session**. All radio work (monitor mode, scanning, deauth, PMKID grab, +handshake capture) happens inside that service; the two halves talk JSON +lines over the child's stdin/stdout and only distilled events cross the +pipe. The GPU cracker needs no privilege and runs as a plain thread in +the UI process. - `--iface ` picks the wireless interface (default: first detected wireless interface, falling back to `wlp14s0`). The header bar's picker @@ -25,17 +29,19 @@ just logs a reminder; nothing fails mid-attack. - `--mock` (or `WIFILAB_MOCK=1`) runs the UI against fabricated events — no device access, for development only. - On startup the tool prints one line: mode, interface, root status. - Not root? The badge shows it and a toast warns once — the UI stays - usable, but every attack will fail with errors in the Log page. + Not root? The badge says *user (service will elevate)* and a toast + notes polkit will ask when capture starts — the UI stays fully usable. + A dismissed polkit dialog just logs an error; click Start again to + retry. **NetworkManager fight:** while NetworkManager is active it pins the card to the connected network's channel — during a scan you will typically see **only that one SSID** (e.g. your connected network) instead of every neighbour. The app detects this at *Start capture*, shows a destructive toast, logs a warning, and offers a **"Stop NM"** button in the header -(one click, uses the elevated session). Restore it afterwards with -`systemctl start NetworkManager`. Everything else on the system is left -untouched. +(the request runs inside the elevated service). Restore it afterwards +with `systemctl start NetworkManager`. Everything else on the system is +left untouched. ## Workflow @@ -62,13 +68,17 @@ untouched. point the wordlist field at e.g. `/usr/share/wordlists/rockyou.txt`, hit **Start**. Live H/s and candidate count stream in. **Stop** flips the job's stop flag and the worker exits at the next batch. -5. Everything the backend does is mirrored on the **Log** page, including - worker errors (permissions, channel-change failures, wordlist open - failures). +5. Everything the service (and the crack thread) does is mirrored on the + **Log** page, including worker errors (permissions, channel-change + failures, wordlist open failures). During a scan a compact + `scan: N rx frames, M beacons -> K APs live (ch C)` heartbeat lands + every 10 s — the evidence line distinguishing RX-silence from parser + drops. -On exit (window close) all workers are stopped and the interface is -restored to managed mode (the `mon` vif is deleted if one was -created). +On exit (window close) the service is told to shut down: it stops all +radio workers, restores the interface to managed mode (deleting the +`mon` vif if one was created), and exits; the UI-side crack +thread is stopped as well. ## Cracking backends diff --git a/src/backend.rs b/src/backend.rs deleted file mode 100644 index 9b81c96..0000000 --- a/src/backend.rs +++ /dev/null @@ -1,355 +0,0 @@ -//! Backend orchestrator: owns the interface mode switch and every worker -//! thread (scanner, deauth, PMKID grab, 4-way capture, cracker). All -//! workers share a single stop flag and report over the UI event channel; -//! the UI stores one `Backend` and drops/shuts it down on window close. -//! -//! Concurrency notes: -//! - The scanner and any attack worker can coexist (deauth while capturing -//! is the whole point). Attack workers open their OWN [`RawSocket`] on -//! the monitor interface and set the channel themselves; concurrent -//! attacks should therefore target the SAME channel — this matches the -//! UI, which implies a single target. -//! - `to_monitor` may create a `mon` vif; the actual monitor ifname -//! is remembered and passed to [`iface::to_managed`] on shutdown -//! (it deletes the vif or flips the interface back, as appropriate). - -use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; -use std::thread::JoinHandle; - -use anyhow::{Context, Result}; -use crossbeam_channel::Sender; - -use crate::common::{Event, MacAddr}; -use crate::crypto::CrackTarget; -use crate::gpu::{self, GpuCracker}; -use crate::rawsock::RawSocket; -use crate::{deauth, handshake, iface, pmkid, scanner, wordlist}; - -fn send(tx: &Sender, ev: Event) { - let _ = tx.send(ev); -} - -fn log(tx: &Sender, msg: impl Into) { - send(tx, Event::Log(msg.into())); -} - -fn log_err(tx: &Sender, msg: impl Into) { - send(tx, Event::Error(msg.into())); -} - -pub struct Backend { - stop: Arc, - handles: Mutex>>, - /// Name of the interface currently in monitor mode (`None` if the - /// mode switch failed at start — nothing to restore then). - mon_ifname: Option, - /// Interface the user selected; restored to managed mode on shutdown - /// when it differs from `mon_ifname`. - orig_ifname: String, - /// Stop flag of the currently running crack job (if any). Kept - /// separate from `stop` so "Stop" on the cracker page doesn't kill - /// the radio workers and `shutdown` can kill both. - crack_stop: Mutex>>, -} - -impl Backend { - /// Switch `ifname` to monitor mode and start the channel-hopping - /// scanner (full 2.4 + 5 GHz hop list). On any failure an - /// [`Event::Error`] is emitted, the interface is put back into managed - /// mode, and `Err` is returned. - pub fn start_scan(ifname: &str, tx: Sender) -> Result { - let mon_ifname = match iface::to_monitor(ifname) { - Ok(name) => name, - Err(e) => { - log_err(&tx, format!("monitor mode on {ifname} failed: {e:#}")); - // Best effort: leave the box the way we found it. - let _ = iface::to_managed(ifname); - return Err(e).context(format!("to_monitor({ifname})")); - } - }; - let be = Backend { - stop: Arc::new(AtomicBool::new(false)), - handles: Mutex::new(Vec::new()), - mon_ifname: Some(mon_ifname.clone()), - orig_ifname: ifname.to_string(), - crack_stop: Mutex::new(None), - }; - log(&tx, format!("monitor mode up on {mon_ifname} (was {ifname})")); - - let cfg = scanner::ScannerConfig { - ifname: mon_ifname, - channels: Vec::new(), // empty = full hop list - dwell_ms: 100, - rssi_floor: -95, - }; - let stop = be.stop.clone(); - let h = std::thread::Builder::new() - .name("wifilab-scanner".into()) - .spawn(move || { - if let Err(e) = scanner::run(cfg, tx.clone(), stop) { - log_err(&tx, format!("scanner stopped: {e:#}")); - } - }) - .context("spawning scanner thread")?; - be.handles.lock().expect("handles poisoned").push(h); - Ok(be) - } - - fn mon(&self) -> String { - self.mon_ifname - .clone() - .unwrap_or_else(|| self.orig_ifname.clone()) - } - - /// Register a worker thread so [`Backend::shutdown`] joins it. The - /// worker closure takes ownership of an event channel clone; on spawn - /// failure the error is reported on the caller's `tx`. - fn spawn( - &self, - name: &str, - tx: &Sender, - what: &str, - f: impl FnOnce(Sender) + Send + 'static, - ) -> bool { - let worker_tx = tx.clone(); - match std::thread::Builder::new() - .name(name.to_string()) - .spawn(move || f(worker_tx)) - { - Ok(h) => { - self.handles.lock().expect("handles poisoned").push(h); - true - } - Err(e) => { - log_err(tx, format!("{what}: spawn failed: {e}")); - false - } - } - } - - /// Ask the running crack job (if any) to stop. Independent of the - /// radio stop flag: killing capture should not need a wordlist stream - /// to die with it. - pub fn request_crack_stop(&self) { - if let Some(flag) = &*self.crack_stop.lock().expect("crack_stop poisoned") { - flag.store(true, Ordering::Relaxed); - } - } - - /// Deauth worker: opens its own raw socket on the monitor interface, - /// tunes it to `channel`, then blasts `count` deauth rounds at - /// `target` (broadcast allowed). Emits DeauthSent progress (via - /// [`deauth::blast`]) and a final summary log. - pub fn deauth( - &self, - ap: MacAddr, - target: MacAddr, - channel: u8, - count: u32, - tx: Sender, - ) { - let mon = self.mon(); - self.spawn("wifilab-deauth", &tx, "deauth", move |tx| { - let sock = match RawSocket::open(&mon) { - Ok(s) => s, - Err(e) => { - log_err(&tx, format!("deauth: raw socket on {mon} failed: {e}")); - return; - } - }; - if let Err(e) = iface::set_channel(&mon, channel) { - // Not fatal: the capture worker is usually already parked - // on the right channel. - log(&tx, format!("deauth: set_channel {channel} failed: {e:#}")); - } - match deauth::blast(&sock, &ap, &target, count, &tx) { - Ok(sent) => log(&tx, format!("deauth: done, {sent} frames → {target}")), - Err(e) => log_err(&tx, format!("deauth: {e:#}")), - } - }); - } - - /// PMKID grab worker: single client-less auth+assoc attempt against - /// `ap`, impersonating the monitor interface's own MAC. Emits - /// PmkidCaptured or a "no PMKID" log line. - pub fn pmkid(&self, ap: MacAddr, channel: u8, essid: String, tx: Sender) { - let mon = self.mon(); - self.spawn("wifilab-pmkid", &tx, "pmkid", move |tx| { - let sta = match iface::mac_of(&mon) { - Ok(m) => m, - Err(e) => { - log_err(&tx, format!("pmkid: own MAC of {mon}: {e:#}")); - return; - } - }; - let sock = match RawSocket::open(&mon) { - Ok(s) => s, - Err(e) => { - log_err(&tx, format!("pmkid: raw socket on {mon} failed: {e}")); - return; - } - }; - if let Err(e) = iface::set_channel(&mon, channel) { - log(&tx, format!("pmkid: set_channel {channel} failed: {e:#}")); - } - match pmkid::grab(&sock, &ap, &sta, &essid, &tx) { - Ok(Some(cap)) => send(&tx, Event::PmkidCaptured(cap)), - Ok(None) => log(&tx, format!("pmkid: no PMKID volunteered by {ap}")), - Err(e) => log_err(&tx, format!("pmkid: {e:#}")), - } - }); - } - - /// 4-way capture worker: tune the monitor interface to `channel`, open - /// a raw socket, and run [`handshake::capture_loop`] (stop flag - /// checked every 250 ms frame poll). [`Event::HandshakeComplete`] is - /// emitted from inside the loop when a crackable pair completes. - pub fn capture_hs(&self, ap: MacAddr, channel: u8, essid: String, tx: Sender) { - let mon = self.mon(); - let stop = self.stop.clone(); - self.spawn("wifilab-capture", &tx, "handshake", move |tx| { - if let Err(e) = iface::set_channel(&mon, channel) { - log_err(&tx, format!("handshake: set_channel {channel} on {mon}: {e:#}")); - return; - } - let sock = match RawSocket::open(&mon) { - Ok(s) => s, - Err(e) => { - log_err(&tx, format!("handshake: raw socket on {mon} failed: {e}")); - return; - } - }; - match handshake::capture_loop(&sock, ap, &essid, &tx, &stop) { - Ok(true) => {} - Ok(false) => log(&tx, format!("handshake: capture ended without a pair ({ap})")), - Err(e) => log_err(&tx, format!("handshake: {e:#}")), - } - }); - } - - /// Crack worker: stream `wordlist` through the GPU cracker (CPU - /// fallback when no adapter) against `target`. Emits CrackProgress, - /// then exactly one terminator: CrackFound + CrackStopped{found:true} - /// on success, CrackStopped{found:false} on stop or wordlist - /// exhaustion. - pub fn crack( - &self, - target_desc: String, - target: CrackTarget, - wordlist: PathBuf, - tx: Sender, - ) { - // Cracking has its own stop flag (cracker-page Stop) but shutdown - // kills it too (see stop_workers/Drop, which set both). - let stop = Arc::new(AtomicBool::new(false)); - *self.crack_stop.lock().expect("crack_stop poisoned") = Some(stop.clone()); - self.spawn("wifilab-crack", &tx, "cracker", move |tx| { - let words = match wordlist::open(&wordlist) { - Ok(w) => w, - Err(e) => { - log_err(&tx, format!("cracker: {e:#}")); - send(&tx, Event::CrackStopped { found: false }); - return; - } - }; - let mut words = words; - let mut progress = { - let tx = tx.clone(); - move |done: u64, hps: f64| send(&tx, Event::CrackProgress { done, hps }) - }; - let found = match GpuCracker::try_new() { - Some(g) => { - log( - &tx, - format!("cracker: GPU backend: {} — cracking {target_desc}", g.device_name()), - ); - g.crack(&target, &mut words, &mut progress, &stop) - } - None => { - log( - &tx, - format!("cracker: no GPU adapter, CPU fallback — cracking {target_desc}"), - ); - gpu::cpu_crack(&target, &mut words, &mut progress, &stop) - } - }; - match found { - Some(password) => { - log(&tx, format!("cracker: PASSWORD found: {password}")); - send(&tx, Event::CrackFound { password }); - send(&tx, Event::CrackStopped { found: true }); - } - None => { - if stop.load(Ordering::Relaxed) { - log(&tx, "cracker: stopped"); - } else { - log(&tx, "cracker: wordlist exhausted, password not found"); - } - send(&tx, Event::CrackStopped { found: false }); - } - } - }); - } - - /// Stop radio work (scanner + attack workers) and restore managed - /// mode, but KEEP the Backend alive so the cracker can still run - /// afterwards: the UI keeps `Some(backend)` after "Stop capture". - /// A still-running crack job is untouched (it has no radio use). - /// Idempotent; a later `start_scan` simply replaces this Backend. - pub fn stop_radio(&self) { - self.stop.store(true, Ordering::Release); - if let Some(mon) = &self.mon_ifname { - if let Err(e) = iface::to_managed(mon) { - eprintln!("wifilab: to_managed({mon}) failed: {e:#}"); - } - } - // Safe to join radio handles here: the UI disables the capture - // toggle while a crack runs, so no unfinished crack thread sits - // in this list. - let handles = std::mem::take(&mut *self.handles.lock().expect("handles poisoned")); - for h in handles { - let _ = h.join(); - } - } - - /// Stop every worker, restore the original interface to managed mode - /// (deleting the `mon` vif if one was created), and join all - /// threads. Idempotent: safe to call more than once / from `Drop`. - pub fn shutdown(self) { - self.stop_workers(); - } - - /// Inner shutdown shared with `Drop` (which cannot move `self`). - fn stop_workers(&self) { - self.stop.store(true, Ordering::Release); - self.request_crack_stop(); - if let Some(mon) = &self.mon_ifname { - if let Err(e) = iface::to_managed(mon) { - eprintln!("wifilab: to_managed({mon}) failed: {e:#}"); - } - } - let handles = std::mem::take(&mut *self.handles.lock().expect("handles poisoned")); - for h in handles { - let _ = h.join(); - } - } -} - -impl Drop for Backend { - /// Panic-safe mirror of [`Backend::shutdown`] — same steps, ignores - /// errors silently as far as possible; never panics itself. - fn drop(&mut self) { - self.stop.store(true, Ordering::Release); - self.request_crack_stop(); - if let Some(mon) = &self.mon_ifname { - let _ = iface::to_managed(mon); - } - if let Ok(mut guard) = self.handles.lock() { - for h in std::mem::take(&mut *guard) { - let _ = h.join(); - } - } - } -} diff --git a/src/common.rs b/src/common.rs index 03ef5d0..d36a616 100644 --- a/src/common.rs +++ b/src/common.rs @@ -1,12 +1,29 @@ //! Shared domain types — the contract between radio, attack, crypto and UI -//! layers. Signatures and field meanings here are FIXED; implementations must -//! conform exactly. All times are `std::time::Instant`, RSSI in dBm. +//! layers, AND the wire format between the UI process and the privileged +//! service (`--privileged-worker` child): every type here (plus [`Cmd`]) +//! serializes through `serde_json` lines. Signatures and field meanings are +//! FIXED; implementations must conform exactly. Times are `last_seen_ms` +//! (millis since the process-local epoch, see [`now_ms`]), RSSI in dBm. use std::fmt; use std::time::Instant; +use serde::{Deserialize, Serialize}; + +/// Process-local epoch: `now_ms` returns elapsed millis since the first +/// deref of this static. Every process has its own epoch — values are only +/// comparable within one process. +#[doc(hidden)] +static EPOCH: std::sync::LazyLock = std::sync::LazyLock::new(Instant::now); + +/// Milliseconds since the process-local epoch; used for `last_seen_ms` +/// timestamps so they cross the UI/service JSON pipe (an `Instant` can't). +pub fn now_ms() -> u64 { + EPOCH.elapsed().as_millis() as u64 +} + /// 6-octet 802.11 MAC address. -#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] pub struct MacAddr(pub [u8; 6]); impl MacAddr { @@ -54,7 +71,7 @@ impl std::str::FromStr for MacAddr { } /// WLAN security suite derived from RSN/WPA IEs (or lack thereof). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Security { Open, Wep, @@ -79,7 +96,7 @@ impl Security { } /// A discovered access point. Live-updated by the scanner. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct AccessPoint { pub bssid: MacAddr, pub ssid: String, @@ -87,22 +104,26 @@ pub struct AccessPoint { pub security: Security, pub rssi_dbm: i8, pub beacons: u64, - pub last_seen: Instant, + /// Millis since the process-local epoch ([`now_ms`]) of the last frame + /// seen from this AP. Age display = `now_ms() - last_seen_ms`. + pub last_seen_ms: u64, } /// A discovered client station. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct ClientInfo { pub mac: MacAddr, /// BSSID of the AP this station is talking to, if determinable. pub ap: Option, pub rssi_dbm: i8, pub frames: u64, - pub last_seen: Instant, + /// Millis since the process-local epoch ([`now_ms`]) of the last frame + /// seen from this station. + pub last_seen_ms: u64, } /// A complete, crackable WPA 4-way handshake capture (M1+M2 minimum). -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct HandshakeCapture { pub ap: MacAddr, pub client: MacAddr, @@ -148,7 +169,7 @@ impl HandshakeCapture { } /// A PMKID capture (clientless attack result). -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct PmkidCapture { pub ap: MacAddr, pub client: MacAddr, // the station we impersonated (our MAC) @@ -156,9 +177,11 @@ pub struct PmkidCapture { pub pmkid: [u8; 16], } -/// Events flowing from worker threads (scanner/capture/attacks/cracker) to -/// the UI over a `crossbeam_channel::Sender`. -#[derive(Clone, Debug)] +/// Events flowing from worker threads to the UI. In the real architecture +/// the privileged service serializes them as `serde_json` lines on the +/// child's stdout; in mock mode a thread pushes them onto a +/// `crossbeam_channel::Sender` directly. +#[derive(Clone, Debug, Serialize, Deserialize)] pub enum Event { ApUpdated(AccessPoint), ApLost(MacAddr), @@ -190,3 +213,198 @@ pub enum Event { /// lab card (keep conservative, driver validates anyway). pub const HOP_CHANNELS_24: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; pub const HOP_CHANNELS_5: &[u8] = &[36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128]; + +/// Commands the UI process sends to the privileged service +/// (`--privileged-worker` child), serialized as one `serde_json` line each +/// on the child's stdin. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum Cmd { + /// Switch `ifname` to monitor mode and start the channel-hopping + /// scanner. `ifname` is saved as the interface to restore on + /// StopScan/Shutdown. + StartScan { ifname: String }, + /// Stop the scanner, restore managed mode. + StopScan, + /// Blast `count` deauth rounds at `target` (broadcast allowed) from + /// `ap`, after tuning to `channel`. + Deauth { + ap: MacAddr, + target: MacAddr, + channel: u8, + count: u32, + }, + /// Clientless PMKID grab against `ap`. + Pmkid { + ap: MacAddr, + channel: u8, + essid: String, + }, + /// Park on `ap`'s channel and track its 4-way handshakes. + CaptureHs { + ap: MacAddr, + channel: u8, + essid: String, + }, + /// Stop NetworkManager/wpa_supplicant so they stop pinning the radio. + StopNetworkManager, + /// Stop all workers, restore the interface, exit the service. + Shutdown, +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ap_obj() -> AccessPoint { + AccessPoint { + bssid: MacAddr([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]), + ssid: "parafin".into(), + channel: 6, + security: Security::Wpa2, + rssi_dbm: -42, + beacons: 7, + last_seen_ms: 123_456, + } + } + + fn client_obj() -> ClientInfo { + ClientInfo { + mac: MacAddr([0x11; 6]), + ap: Some(MacAddr([0xaa; 6])), + rssi_dbm: -55, + frames: 3, + last_seen_ms: 654_321, + } + } + + fn handshake_obj() -> HandshakeCapture { + HandshakeCapture::new( + MacAddr([1; 6]), + MacAddr([2; 6]), + "labnet".into(), + [3u8; 32], + [4u8; 32], + [5u8; 16], + vec![6u8; 99], + 2, + ) + } + + fn pmkid_obj() -> PmkidCapture { + PmkidCapture { + ap: MacAddr([7; 6]), + client: MacAddr([8; 6]), + essid: "corp".into(), + pmkid: [9u8; 16], + } + } + + fn roundtrip(value: &T) -> T + where + T: Serialize + for<'de> Deserialize<'de> + std::fmt::Debug, + { + let json = serde_json::to_string(value).expect("serialize"); + serde_json::from_str(&json).unwrap_or_else(|e| panic!("deserialize {json}: {e}")) + } + + #[test] + fn now_ms_is_monotonic_and_ms_scale() { + let a = now_ms(); + let b = now_ms(); + assert!(b >= a); + // Same-process sanity: first deref happens at most a few hundred ms + // before this test runs (process start); elapsed must stay small. + assert!(a < 120_000, "process-local epoch ms implausibly large: {a}"); + } + + #[test] + fn event_json_roundtrips() { + let cases: Vec = vec![ + Event::ApUpdated(ap_obj()), + Event::ApLost(MacAddr::BROADCAST), + Event::ClientUpdated(client_obj()), + Event::HandshakeProgress { + ap: MacAddr([1; 6]), + client: MacAddr([2; 6]), + have: 0b1011, + }, + Event::HandshakeComplete(Box::new(handshake_obj())), + Event::PmkidCaptured(pmkid_obj()), + Event::DeauthSent { + ap: MacAddr([1; 6]), + target: MacAddr::BROADCAST, + count: 64, + }, + Event::CrackProgress { done: 1000, hps: 1234.5 }, + Event::CrackFound { + password: "hunter2".into(), + }, + Event::CrackStopped { found: true }, + Event::CrackStopped { found: false }, + Event::Log("hello".into()), + Event::Error("boom".into()), + ]; + for ev in &cases { + let json = serde_json::to_string(ev).expect("serialize"); + let back: Event = serde_json::from_str(&json) + .unwrap_or_else(|e| panic!("deserialize {json}: {e}")); + assert_eq!(format!("{ev:?}"), format!("{back:?}")); + } + } + + #[test] + fn handshake_json_roundtrip_is_lossless() { + // PartialEq on the struct itself (not just Debug) — the Box in + // Event::HandshakeComplete must survive the wire. + let ev = Event::HandshakeComplete(Box::new(handshake_obj())); + let json = serde_json::to_string(&ev).expect("serialize"); + let Event::HandshakeComplete(back) = + serde_json::from_str(&json).expect("deserialize") + else { + panic!("variant changed shape: {json}"); + }; + assert_eq!(*back, handshake_obj()); + let pm = Event::PmkidCaptured(pmkid_obj()); + let json = serde_json::to_string(&pm).expect("serialize"); + let Event::PmkidCaptured(back) = serde_json::from_str(&json).expect("deserialize") + else { + panic!("variant changed shape: {json}"); + }; + assert_eq!(back, pmkid_obj()); + } + + #[test] + fn cmd_json_roundtrips() { + let cases: Vec = vec![ + Cmd::StartScan { + ifname: "wlp14s0".into(), + }, + Cmd::StopScan, + Cmd::Deauth { + ap: MacAddr([1; 6]), + target: MacAddr::BROADCAST, + channel: 6, + count: 16, + }, + Cmd::Pmkid { + ap: MacAddr([2; 6]), + channel: 36, + essid: "corp-wpa3".into(), + }, + Cmd::CaptureHs { + ap: MacAddr([3; 6]), + channel: 11, + essid: "coffeeshop".into(), + }, + Cmd::StopNetworkManager, + Cmd::Shutdown, + ]; + for cmd in &cases { + let json = serde_json::to_string(cmd).expect("serialize"); + let back: Cmd = serde_json::from_str(&json) + .unwrap_or_else(|e| panic!("deserialize {json}: {e}")); + assert_eq!(*cmd, back); + } + assert_eq!(roundtrip(&cases[0]), cases[0]); + } +} diff --git a/src/iface.rs b/src/iface.rs index 60a39dc..1167555 100644 --- a/src/iface.rs +++ b/src/iface.rs @@ -191,7 +191,8 @@ pub fn stop_networkmanager() -> Result<()> { .map(|_| ()) } -/// True when `pkexec` (polkit) is available for GUI privilege elevation. +/// True when `pkexec` (polkit) is available to elevate the privileged +/// service child. pub fn pkexec_available() -> bool { Command::new("pkexec") .arg("--version") @@ -202,36 +203,6 @@ pub fn pkexec_available() -> bool { .unwrap_or(false) } -/// Re-exec this binary via polkit (`pkexec`) as root, preserving the desktop -/// session environment so the elevated instance can open its own window. -/// -/// Blocks until `pkexec` returns. A dismissed/cancelled authentication -/// dialog surfaces as a non-zero exit status (126/127). MUST be called off -/// the UI thread. -pub fn relaunch_elevated(extra_args: &[&str]) -> Result { - let exe = std::env::current_exe().context("resolving current_exe for pkexec re-exec")?; - let mut cmd = Command::new("pkexec"); - cmd.arg("env"); - // GUI + session bus env the elevated child needs to open a window and - // talk to the user's services (GPU/DRI inherits via the session). - for var in [ - "WAYLAND_DISPLAY", - "XDG_RUNTIME_DIR", - "DISPLAY", - "DBUS_SESSION_BUS_ADDRESS", - "XAUTHORITY", - ] { - if let Ok(v) = std::env::var(var) { - cmd.arg(format!("{var}={v}")); - } - } - cmd.arg(exe).args(extra_args); - let status = cmd - .status() - .context("spawning pkexec — polkit not installed or no agent running")?; - Ok(status) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/main.rs b/src/main.rs index 6ac1cdd..d9e6049 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,3 @@ -mod backend; mod common; mod crypto; mod deauth; @@ -10,6 +9,7 @@ mod pmkid; mod radiotap; mod rawsock; mod scanner; +mod service; mod ui; mod wordlist; @@ -27,10 +27,19 @@ struct Cli { /// Dev mode: fabricated events, no device access. Same as WIFILAB_MOCK=1. #[arg(long)] mock: bool, + /// Internal: run as the privileged radio service (spawned by the UI, + /// directly or via pkexec). Never returns; JSON lines on stdin/stdout. + #[arg(long, hide = true)] + privileged_worker: bool, } fn main() { let cli = Cli::parse(); + // Privileged service path: no GUI, no extra args needed (pkexec strips + // the environment; everything the service needs comes over the pipe). + if cli.privileged_worker { + service::run_service(); // never returns + } let mock = cli.mock || matches!( std::env::var_os("WIFILAB_MOCK"), @@ -49,9 +58,9 @@ fn main() { if mock { "fabricated events only" } else if iface::is_root() { - "monitor mode + injection available" + "monitor mode + injection available (service runs as child)" } else { - "not root — use the \"Elevate via polkit\" button in the UI header" + "not root — polkit will ask for authentication when you start capture" } ); ui::run_app(cli.iface, cli.mock); diff --git a/src/scanner.rs b/src/scanner.rs index 08b1dd6..4aad5d5 100644 --- a/src/scanner.rs +++ b/src/scanner.rs @@ -7,19 +7,23 @@ use std::collections::BTreeMap; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; +// `Instant` is still used for dwell timing; timestamps going into shared +// types are `u64` millis (`crate::common::now_ms`) so they serialize. use anyhow::{Context, Result}; use crossbeam_channel::Sender; -use crate::common::{AccessPoint, ClientInfo, Event, HOP_CHANNELS_24, HOP_CHANNELS_5, MacAddr}; +use crate::common::{ + AccessPoint, ClientInfo, Event, HOP_CHANNELS_24, HOP_CHANNELS_5, MacAddr, now_ms, +}; use crate::radiotap::RxMeta; use crate::rawsock::RawSocket; use crate::{dot11, iface, radiotap}; -/// APs go stale (ApLost) after this much silence. -const AP_EXPIRE: Duration = Duration::from_secs(30); -/// Clients go stale after this much silence. -const CLIENT_EXPIRE: Duration = Duration::from_secs(60); +/// APs go stale (ApLost) after this much silence (ms — `last_seen_ms`). +const AP_EXPIRE_MS: u64 = 30_000; +/// Clients go stale after this much silence (ms). +const CLIENT_EXPIRE_MS: u64 = 60_000; pub struct ScannerConfig { pub ifname: String, @@ -61,8 +65,9 @@ impl Scanner { } /// Feed one received frame. Radiotap metadata in `meta`, 802.11 bytes in - /// `frame` (already stripped), wall clock in `now` (test-injectable). - fn ingest(&mut self, meta: &RxMeta, frame: &[u8], now: Instant, tx: &Sender) { + /// `frame` (already stripped), clock in `now` ms since the process-local + /// epoch ([`common::now_ms`], test-injectable). + fn ingest(&mut self, meta: &RxMeta, frame: &[u8], now: u64, tx: &Sender) { // AP from beacon / probe-response. if let Some(m) = dot11::parse_beacon_or_probe(frame) { // Trust the DS-parameter IE; fall back to the radiotap carrier @@ -92,7 +97,7 @@ impl Scanner { changed = true; } ap.beacons += 1; - ap.last_seen = now; + ap.last_seen_ms = now; if changed { let _ = tx.send(Event::ApUpdated(ap.clone())); } @@ -108,7 +113,7 @@ impl Scanner { security: m.security, rssi_dbm: meta.rssi_dbm, beacons: 1, - last_seen: now, + last_seen_ms: now, }; self.aps.insert(m.bssid, ap.clone()); let _ = tx.send(Event::ApUpdated(ap)); @@ -133,7 +138,7 @@ impl Scanner { self.note_client(sta, Some(bssid), meta, now, tx); } if let Some(ap) = self.aps.get_mut(&bssid) { - ap.last_seen = now; + ap.last_seen_ms = now; } } } @@ -143,7 +148,7 @@ impl Scanner { sta: MacAddr, ap: Option, meta: &RxMeta, - now: Instant, + now: u64, tx: &Sender, ) { match self.clients.get_mut(&sta) { @@ -160,7 +165,7 @@ impl Scanner { } } c.frames += 1; - c.last_seen = now; + c.last_seen_ms = now; if changed { let _ = tx.send(Event::ClientUpdated(c.clone())); } @@ -174,7 +179,7 @@ impl Scanner { ap, rssi_dbm: meta.rssi_dbm, frames: 1, - last_seen: now, + last_seen_ms: now, }; self.clients.insert(sta, c.clone()); let _ = tx.send(Event::ClientUpdated(c)); @@ -184,11 +189,11 @@ impl Scanner { /// Expire silent entries, emitting ApLost / (clients just drop out — /// contract has no ClientLost event; stale clients stop being updated). - fn expire(&mut self, now: Instant, tx: &Sender) { + fn expire(&mut self, now: u64, tx: &Sender) { let gone: Vec = self .aps .iter() - .filter(|(_, ap)| now.duration_since(ap.last_seen) > AP_EXPIRE) + .filter(|(_, ap)| now.saturating_sub(ap.last_seen_ms) > AP_EXPIRE_MS) .map(|(b, _)| *b) .collect(); for b in gone { @@ -196,10 +201,27 @@ impl Scanner { let _ = tx.send(Event::ApLost(b)); } self.clients - .retain(|_, c| now.duration_since(c.last_seen) <= CLIENT_EXPIRE); + .retain(|_, c| now.saturating_sub(c.last_seen_ms) <= CLIENT_EXPIRE_MS); } } +/// Wall-clock counters for the 10 s `scan: …` diagnostic line — the evidence +/// channel distinguishing RX-silence from parser-drops when "only my own AP +/// shows up" is reported. +#[derive(Default)] +struct ScanStats { + /// Frames returned by `RawSocket::recv` (radiotap included, unparsed). + raw_frames_received: u64, + /// Frames whose radiotap header parsed (`radiotap::strip` returned Some). + radiotap_strip_ok: u64, + /// 802.11 payload parsed as SOME mgmt frame (beacon/probe-req/deauth / + /// probe-response family recognised by dot11). + mgmt_80211_parsed: u64, + /// Beacons/probe-responses that ingested an AP row (created or already + /// known — i.e. recognised AP-producing frames). + beacons_ap_ingested: u64, +} + /// Blocking channel-hop passive scan on an interface the caller already put /// into monitor mode. Returns when `stop` flips true. pub fn run(cfg: ScannerConfig, tx: Sender, stop: Arc) -> Result<()> { @@ -226,9 +248,12 @@ pub fn run(cfg: ScannerConfig, tx: Sender, stop: Arc) -> Resu let mut scanner = Scanner::new(cfg.rssi_floor); let mut buf = vec![0u8; 4096]; let mut ch_idx = 0usize; + let mut stats = ScanStats::default(); + let mut last_stats_log = Instant::now(); while !stop.load(Ordering::Relaxed) { let ch = channels[ch_idx]; + let cur_ch = ch; ch_idx = (ch_idx + 1) % channels.len(); if let Err(e) = iface::set_channel(&cfg.ifname, ch) { let _ = tx.send(Event::Log(format!( @@ -241,8 +266,18 @@ pub fn run(cfg: ScannerConfig, tx: Sender, stop: Arc) -> Resu loop { match sock.recv(&mut buf) { Ok(n) => { - let now = Instant::now(); + stats.raw_frames_received += 1; + let now = now_ms(); if let Some((meta, frame)) = radiotap::strip(&buf[..n]) { + stats.radiotap_strip_ok += 1; + if dot11::parse_beacon_or_probe(frame).is_some() { + stats.mgmt_80211_parsed += 1; + stats.beacons_ap_ingested += 1; + } else if dot11::parse_probe_req(frame).is_some() + || dot11::parse_deauth(frame).is_some() + { + stats.mgmt_80211_parsed += 1; + } scanner.ingest(&meta, frame, now, &tx); } } @@ -266,7 +301,21 @@ pub fn run(cfg: ScannerConfig, tx: Sender, stop: Arc) -> Resu } } - scanner.expire(Instant::now(), &tx); + // 10 s wall-time diagnostic heartbeat: distinguishes RX-silence + // (rx==0) from radiotap/parser drops (rx>0 but beacons==0) when a + // report says "only my own AP shows up". + if last_stats_log.elapsed() >= Duration::from_secs(10) { + last_stats_log = Instant::now(); + let _ = tx.send(Event::Log(format!( + "scan: {} rx frames, {} beacons -> {} APs live (ch {})", + stats.raw_frames_received, + stats.beacons_ap_ingested, + scanner.aps.len(), + cur_ch + ))); + } + + scanner.expire(now_ms(), &tx); } Ok(()) } @@ -346,7 +395,7 @@ mod tests { fn beacon_attached_creates_ap_with_ssid_and_channel() { let (tx, rx) = crossbeam_channel::unbounded(); let mut sc = Scanner::new(-85); - let now = Instant::now(); + let now: u64 = 0; sc.ingest(&meta(-42, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); match rx.try_recv() { Ok(Event::ApUpdated(a)) => { @@ -363,7 +412,7 @@ mod tests { fn beacon_uses_freq_hint_when_no_ds_ie() { let (tx, rx) = crossbeam_channel::unbounded(); let mut sc = Scanner::new(-85); - let now = Instant::now(); + let now: u64 = 0; let mut f = beacon_frame(&ap(), "parafin", 6); f.truncate(f.len() - 3); // drop DS IE sc.ingest(&meta(-40, 2437), &f, now, &tx); @@ -377,7 +426,7 @@ mod tests { fn weak_beacon_not_created_but_update_accepted_later() { let (tx, rx) = crossbeam_channel::unbounded(); let mut sc = Scanner::new(-85); - let now = Instant::now(); + let now: u64 = 0; // -90 < floor: no event, no entry. sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); assert!(rx.try_recv().is_err()); @@ -394,7 +443,7 @@ mod tests { fn rssi_improvement_emits_update_worsening_does_not() { let (tx, rx) = crossbeam_channel::unbounded(); let mut sc = Scanner::new(-85); - let now = Instant::now(); + let now: u64 = 0; sc.ingest(&meta(-70, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); let _ = rx.try_recv(); // creation sc.ingest(&meta(-75, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); @@ -410,7 +459,7 @@ mod tests { fn probe_req_creates_client_and_data_freshens() { let (tx, rx) = crossbeam_channel::unbounded(); let mut sc = Scanner::new(-85); - let now = Instant::now(); + let now: u64 = 0; sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), Some("parafin")), now, &tx); match rx.try_recv() { Ok(Event::ClientUpdated(c)) => { @@ -431,7 +480,7 @@ mod tests { fn multicast_ta_is_ignored() { let (tx, rx) = crossbeam_channel::unbounded(); let mut sc = Scanner::new(-85); - let now = Instant::now(); + let now: u64 = 0; let mcast = MacAddr([0x33, 0x33, 0, 0, 0, 1]); sc.ingest(&meta(-40, 0), &probe_req_frame(&mcast, None), now, &tx); assert!(rx.try_recv().is_err()); @@ -442,14 +491,14 @@ mod tests { fn aging_emits_ap_lost_and_drops_clients() { let (tx, rx) = crossbeam_channel::unbounded(); let mut sc = Scanner::new(-85); - let t0 = Instant::now(); + let t0: u64 = 1_000; sc.ingest(&meta(-40, 0), &beacon_frame(&ap(), "parafin", 6), t0, &tx); sc.ingest(&meta(-40, 0), &probe_req_frame(&sta(), None), t0, &tx); let _ = rx.try_recv(); let _ = rx.try_recv(); // 31 s later: AP expired, client still alive. - let t1 = t0 + Duration::from_secs(31); + let t1 = t0 + 31_000; sc.expire(t1, &tx); match rx.try_recv() { Ok(Event::ApLost(b)) => assert_eq!(b, ap()), @@ -458,7 +507,7 @@ mod tests { assert!(sc.clients.contains_key(&sta())); // 61 s: client gone too. - sc.expire(t0 + Duration::from_secs(61), &tx); + sc.expire(t0 + 61_000, &tx); assert!(sc.clients.is_empty()); } diff --git a/src/service.rs b/src/service.rs new file mode 100644 index 0000000..00fab02 --- /dev/null +++ b/src/service.rs @@ -0,0 +1,697 @@ +//! Privileged service + UI-side client, replacing the old monolithic +//! `Backend`. +//! +//! Architecture: the UI process never needs root. All radio work runs in a +//! privileged SERVICE — the same binary re-spawned as a child with the +//! hidden flag `--privileged-worker` (directly when the UI is already root, +//! via `pkexec` otherwise). The two halves speak JSON lines: `Cmd` on the +//! child's stdin, `Event` on its stdout (stdout is reserved EXCLUSIVELY for +//! events; diagnostics go to stderr). +//! +//! Concurrency notes (service side): +//! - The scanner and any attack worker can coexist (deauth while capturing +//! is the whole point). Attack workers open their OWN [`RawSocket`] on +//! the monitor interface and set the channel themselves; concurrent +//! attacks should therefore target the SAME channel — this matches the +//! UI, which implies a single target. +//! - `to_monitor` may create a `mon` vif; the actual monitor ifname +//! is remembered and passed to [`iface::to_managed`] on stop/shutdown +//! (it deletes the vif or flips the interface back, as appropriate). + +use std::io::{BufRead, BufReader, Write}; +use std::path::PathBuf; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use crossbeam_channel::Sender; + +use crate::common::{Cmd, Event, MacAddr}; +use crate::crypto::CrackTarget; +use crate::gpu::{self, GpuCracker}; +use crate::rawsock::RawSocket; +use crate::{deauth, handshake, iface, pmkid, scanner, wordlist}; + +/// Exact banner the service prints on stdout before any event line. The +/// client prefix-matches lines against this while waiting (pkexec may +/// prepend its own chatter). +pub const READY_LINE: &str = "WIFILAB-SVC-READY"; + +/// How long the client waits for the service's READY banner (the polkit +/// dialog can block on a slow human). +const READY_TIMEOUT: Duration = Duration::from_secs(60); + +fn send(tx: &Sender, ev: Event) { + let _ = tx.send(ev); +} + +fn log(tx: &Sender, msg: impl Into) { + send(tx, Event::Log(msg.into())); +} + +fn log_err(tx: &Sender, msg: impl Into) { + send(tx, Event::Error(msg.into())); +} + +// --------------------------------------------------------------------------- +// Privileged half — runs as the `--privileged-worker` child process. +// --------------------------------------------------------------------------- + +/// Radio-side state owned by the service process. Mirrors the old +/// `Backend` minus the cracker (which moved into the UI process). +struct RadioService { + stop: Arc, + handles: Mutex>>, + /// Name of the interface currently in monitor mode (`None` if the + /// mode switch failed at StartScan — nothing to restore then). + mon_ifname: Option, + /// Interface the UI asked for; restored to managed mode on stop/ + /// shutdown when it differs from `mon_ifname`. + orig_ifname: Option, + /// Event pipe: the forwarder thread owns the receiving end and + /// serializes one JSON line per event onto stdout. + tx: Sender, +} + +impl RadioService { + fn new(tx: Sender) -> Self { + RadioService { + stop: Arc::new(AtomicBool::new(false)), + handles: Mutex::new(Vec::new()), + mon_ifname: None, + orig_ifname: None, + tx, + } + } + + fn mon(&self) -> Option { + self.mon_ifname + .clone() + .or_else(|| self.orig_ifname.clone()) + } + + /// Switch `ifname` to monitor mode and start the channel-hopping + /// scanner (full 2.4 + 5 GHz hop list). On any failure an + /// [`Event::Error`] is emitted, the interface is put back into managed + /// mode (best effort). A previous scan session must be stopped first + /// (or have failed); the stop flag is always fresh here. + fn start_scan(&mut self, ifname: &str) { + self.stop = Arc::new(AtomicBool::new(false)); + self.mon_ifname = None; + self.orig_ifname = Some(ifname.to_string()); + + let mon_ifname = match iface::to_monitor(ifname) { + Ok(name) => name, + Err(e) => { + log_err(&self.tx, format!("monitor mode on {ifname} failed: {e:#}")); + // Best effort: leave the box the way we found it. + let _ = iface::to_managed(ifname); + self.orig_ifname = None; + return; + } + }; + self.mon_ifname = Some(mon_ifname.clone()); + log(&self.tx, format!("monitor mode up on {mon_ifname} (was {ifname})")); + + let cfg = scanner::ScannerConfig { + ifname: mon_ifname, + channels: Vec::new(), // empty = full hop list + dwell_ms: 100, + rssi_floor: -95, + }; + let stop = self.stop.clone(); + let tx = self.tx.clone(); + match std::thread::Builder::new() + .name("wifilab-scanner".into()) + .spawn(move || { + if let Err(e) = scanner::run(cfg, tx.clone(), stop) { + log_err(&tx, format!("scanner stopped: {e:#}")); + } + }) { + Ok(h) => self.handles.lock().expect("handles poisoned").push(h), + Err(e) => { + log_err(&self.tx, format!("scanner: spawn failed: {e}")); + // Leave the UI consistent: nothing runs but the interface + // is in monitor mode — flip it back. + if let Some(mon) = self.mon_ifname.take() { + let _ = iface::to_managed(&mon); + } + } + } + } + + /// Stop the scanner + all attack workers and restore managed mode. + /// The service stays alive for a subsequent StartScan. Idempotent. + fn stop_scan(&mut self) { + self.stop.store(true, Ordering::Release); + let handles = std::mem::take(&mut *self.handles.lock().expect("handles poisoned")); + for h in handles { + let _ = h.join(); + } + if let Some(mon) = self.mon_ifname.take() { + if let Err(e) = iface::to_managed(&mon) { + eprintln!("wifilab-svc: to_managed({mon}) failed: {e:#}"); + } + } + self.orig_ifname = None; + } + + /// Register a worker thread; on spawn failure the error is reported on + /// the event pipe. + fn spawn( + &self, + name: &str, + what: &str, + f: impl FnOnce(Sender) + Send + 'static, + ) -> bool { + let worker_tx = self.tx.clone(); + match std::thread::Builder::new() + .name(name.to_string()) + .spawn(move || f(worker_tx)) + { + Ok(h) => { + self.handles.lock().expect("handles poisoned").push(h); + true + } + Err(e) => { + log_err(&self.tx, format!("{what}: spawn failed: {e}")); + false + } + } + } + + /// Deauth worker: opens its own raw socket on the monitor interface, + /// tunes it to `channel`, then blasts `count` deauth rounds at + /// `target` (broadcast allowed). Emits DeauthSent progress (via + /// [`deauth::blast`]) and a final summary log. + fn deauth(&self, ap: MacAddr, target: MacAddr, channel: u8, count: u32) { + let Some(mon) = self.mon() else { + log_err(&self.tx, "deauth: no scan session — StartScan first"); + return; + }; + self.spawn("wifilab-deauth", "deauth", move |tx| { + let sock = match RawSocket::open(&mon) { + Ok(s) => s, + Err(e) => { + log_err(&tx, format!("deauth: raw socket on {mon} failed: {e}")); + return; + } + }; + if let Err(e) = iface::set_channel(&mon, channel) { + // Not fatal: the capture worker is usually already parked + // on the right channel. + log(&tx, format!("deauth: set_channel {channel} failed: {e:#}")); + } + match deauth::blast(&sock, &ap, &target, count, &tx) { + Ok(sent) => log(&tx, format!("deauth: done, {sent} frames → {target}")), + Err(e) => log_err(&tx, format!("deauth: {e:#}")), + } + }); + } + + /// PMKID grab worker: single client-less auth+assoc attempt against + /// `ap`, impersonating the monitor interface's own MAC. Emits + /// PmkidCaptured or a "no PMKID" log line. + fn pmkid(&self, ap: MacAddr, channel: u8, essid: String) { + let Some(mon) = self.mon() else { + log_err(&self.tx, "pmkid: no scan session — StartScan first"); + return; + }; + self.spawn("wifilab-pmkid", "pmkid", move |tx| { + let sta = match iface::mac_of(&mon) { + Ok(m) => m, + Err(e) => { + log_err(&tx, format!("pmkid: own MAC of {mon}: {e:#}")); + return; + } + }; + let sock = match RawSocket::open(&mon) { + Ok(s) => s, + Err(e) => { + log_err(&tx, format!("pmkid: raw socket on {mon} failed: {e}")); + return; + } + }; + if let Err(e) = iface::set_channel(&mon, channel) { + log(&tx, format!("pmkid: set_channel {channel} failed: {e:#}")); + } + match pmkid::grab(&sock, &ap, &sta, &essid, &tx) { + Ok(Some(cap)) => send(&tx, Event::PmkidCaptured(cap)), + Ok(None) => log(&tx, format!("pmkid: no PMKID volunteered by {ap}")), + Err(e) => log_err(&tx, format!("pmkid: {e:#}")), + } + }); + } + + /// 4-way capture worker: tune the monitor interface to `channel`, open + /// a raw socket, and run [`handshake::capture_loop`] (stop flag + /// checked every 250 ms frame poll). [`Event::HandshakeComplete`] is + /// emitted from inside the loop when a crackable pair completes. + fn capture_hs(&self, ap: MacAddr, channel: u8, essid: String) { + let Some(mon) = self.mon() else { + log_err(&self.tx, "handshake: no scan session — StartScan first"); + return; + }; + let stop = self.stop.clone(); + self.spawn("wifilab-capture", "handshake", move |tx| { + if let Err(e) = iface::set_channel(&mon, channel) { + log_err(&tx, format!("handshake: set_channel {channel} on {mon}: {e:#}")); + return; + } + let sock = match RawSocket::open(&mon) { + Ok(s) => s, + Err(e) => { + log_err(&tx, format!("handshake: raw socket on {mon} failed: {e}")); + return; + } + }; + match handshake::capture_loop(&sock, ap, &essid, &tx, &stop) { + Ok(true) => {} + Ok(false) => log(&tx, format!("handshake: capture ended without a pair ({ap})")), + Err(e) => log_err(&tx, format!("handshake: {e:#}")), + } + }); + } + + fn stop_networkmanager(&self) { + match iface::stop_networkmanager() { + Ok(()) => log(&self.tx, "nm: stopped"), + Err(e) => log(&self.tx, format!("nm: stop failed: {e:#}")), + } + } +} + +/// Service entry point: never returns (process exits from inside). +/// +/// stdout carries exactly one READY banner and then one JSON-serialized +/// [`Event`] per line — nothing else. stderr is free for diagnostics. +pub fn run_service() -> ! { + let code = service_main(); + std::process::exit(code); +} + +fn service_main() -> i32 { + let stdout = std::io::stdout(); + // Buffered writer handed to the forwarder thread; the banner uses the + // same lock discipline by printing through a dedicated line with an + // explicit flush BEFORE the forwarder starts. + { + let mut out = stdout.lock(); + let _ = out.write_all(READY_LINE.as_bytes()); + let _ = out.write_all(b"\n"); + let _ = out.flush(); + } + + // Single writer to stdout: every event — scanner, attacks, errors, + // logs — funnels through this channel and gets serialized by ONE + // forwarder thread, so lines never interleave. + let (tx, rx) = crossbeam_channel::unbounded::(); + let forwarder = std::thread::Builder::new() + .name("wifilab-svc-fwd".into()) + .spawn(move || { + let stdout = std::io::stdout(); + let mut out = std::io::BufWriter::new(stdout.lock()); + // Bounded drain: when the channel closes (main loop out of + // scope) we finish queued events and exit. + while let Ok(ev) = rx.recv() { + match serde_json::to_string(&ev) { + Ok(line) => { + if out.write_all(line.as_bytes()).is_err() + || out.write_all(b"\n").is_err() + || out.flush().is_err() + { + return; // parent gone + } + } + Err(e) => eprintln!("wifilab-svc: event serialization failed: {e}"), + } + } + }) + .expect("spawning service forwarder thread"); + + let mut radio = RadioService::new(tx.clone()); + let stdin = std::io::stdin(); + let mut lines = BufReader::new(stdin.lock()).lines(); + loop { + let line = match lines.next() { + Some(Ok(l)) => l, + Some(Err(e)) => { + eprintln!("wifilab-svc: stdin read failed: {e}"); + break; // treat as EOF + } + None => break, // EOF: parent closed the pipe + }; + if line.trim().is_empty() { + continue; + } + let cmd: Cmd = match serde_json::from_str(&line) { + Ok(c) => c, + Err(e) => { + log_err(&tx, format!("service: bad command line ({}): {e}", &line[..line.len().min(80)])); + continue; + } + }; + match cmd { + Cmd::StartScan { ifname } => radio.start_scan(&ifname), + Cmd::StopScan => radio.stop_scan(), + Cmd::Deauth { + ap, + target, + channel, + count, + } => radio.deauth(ap, target, channel, count), + Cmd::Pmkid { ap, channel, essid } => radio.pmkid(ap, channel, essid), + Cmd::CaptureHs { ap, channel, essid } => radio.capture_hs(ap, channel, essid), + Cmd::StopNetworkManager => radio.stop_networkmanager(), + Cmd::Shutdown => break, + } + } + + // Stop everything, restore the interface, drain the event pipe so the + // last error lines still reach the UI, and exit. + radio.stop_scan(); + drop(radio); + drop(tx); + let _ = forwarder.join(); + 0 +} + +// --------------------------------------------------------------------------- +// UI-side half — owns the child process and the crack thread. +// --------------------------------------------------------------------------- + +/// Client handle for the privileged service. Lives across scan sessions: +/// "Stop capture" only sends [`Cmd::StopScan`]; the child stays up for +/// later scans and for `StopNetworkManager`. The GPU cracker runs as a +/// plain thread in the UI process (no privilege needed) and is tracked +/// here for its stop flag only. +pub struct ServiceClient { + stdin: Arc>, + reader: Option>, + child: Child, + /// Stop flag of the currently running crack job (if any). Radio + /// workers live in the service; this is a pure UI-process thread. + pub crack_stop: Mutex>>, +} + +/// Child argv: same binary, hidden worker flag. Root → spawn directly; +/// non-root → wrap in pkexec (polkit prompt appears once per session). +fn spawn_service_child() -> Result { + let exe = std::env::current_exe().context("resolving current_exe for service spawn")?; + if iface::is_root() { + Command::new(exe) + .arg("--privileged-worker") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .context("spawning privileged service") + } else { + if !iface::pkexec_available() { + bail!("pkexec not available — cannot elevate the privileged service"); + } + Command::new("pkexec") + .arg(exe) + .arg("--privileged-worker") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .context("spawning pkexec — polkit not installed or no agent running") + } +} + +impl ServiceClient { + /// Spawn the privileged service and start the channel-hopping scanner + /// on `ifname`. All service events land on `tx`. A pkexec refusal / + /// missing READY / immediate child death surfaces as `Err` (never a + /// panic); later events flow asynchronously. + pub fn start(ifname: &str, tx: Sender) -> Result { + let mut child = spawn_service_child()?; + let stdin = child + .stdin + .take() + .context("service child stdin not piped")?; + let stdout = child + .stdout + .take() + .context("service child stdout not piped")?; + + let (ready_tx, ready_rx) = crossbeam_channel::bounded::>(1); + let reader = std::thread::Builder::new() + .name("wifilab-svc-reader".into()) + .spawn(move || { + let mut lines = BufReader::new(stdout).lines(); + let mut ready = false; + let deadline = Instant::now() + READY_TIMEOUT; + // READY phase: prefix-match so pkexec chatter on stdout + // can't trip us; hard cap at READY_TIMEOUT. + while Instant::now() < deadline { + match lines.next() { + Some(Ok(line)) if !ready => { + if line.starts_with(READY_LINE) { + ready = true; + let _ = ready_tx.try_send(Ok(())); + break; + } + // Pre-ready garbage (pkexec notes etc.): ignore. + } + Some(Ok(_)) => break, + Some(Err(e)) => { + let _ = ready_tx.try_send(Err(anyhow::anyhow!( + "service stdout read failed: {e}" + ))); + return; + } + None => { + let _ = ready_tx.try_send(Err(anyhow::anyhow!( + "service exited before READY (polkit dismissed or spawn failed)" + ))); + return; + } + } + } + if !ready { + let _ = ready_tx.try_send(Err(anyhow::anyhow!( + "service READY banner not seen within {} s", + READY_TIMEOUT.as_secs() + ))); + return; + } + // Event phase: one JSON event per stdout line, until EOF. + for line in lines { + let line = match line { + Ok(l) => l, + Err(e) => { + send(&tx, Event::Error(format!("service stdout read failed: {e}"))); + break; + } + }; + if line.trim().is_empty() { + continue; + } + match serde_json::from_str::(&line) { + Ok(ev) => send(&tx, ev), + Err(e) => send( + &tx, + Event::Error(format!( + "service: bad event line ({}): {e}", + &line[..line.len().min(80)] + )), + ), + } + } + // EOF: child died. UI uses this pair to un-flip flags. + send(&tx, Event::Log("service exited".to_string())); + send(&tx, Event::Error("service terminated".to_string())); + }) + .context("spawning service reader thread")?; + + // Wait for READY here (bounded), so spawn/config failures surface + // synchronously instead of as a late async surprise. + match ready_rx.recv_timeout(READY_TIMEOUT) { + Ok(Ok(())) => {} + Ok(Err(e)) => { + let _ = child.kill(); + let _ = child.wait(); + let _ = reader.join(); + return Err(e); + } + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + let _ = reader.join(); + bail!("service READY banner wait timed out"); + } + } + + let client = ServiceClient { + stdin: Arc::new(Mutex::new(stdin)), + reader: Some(reader), + child, + crack_stop: Mutex::new(None), + }; + client.cmd(&Cmd::StartScan { + ifname: ifname.to_string(), + }); + Ok(client) + } + + /// Ship one command line to the service. BrokenPipe (service already + /// dead) is ignored — the reader thread reported the death. + pub fn cmd(&self, c: &Cmd) { + let Ok(line) = serde_json::to_string(c) else { + return; + }; + let mut guard = self.stdin.lock().expect("service stdin poisoned"); + let _ = guard.write_all(line.as_bytes()); + let _ = guard.write_all(b"\n"); + let _ = guard.flush(); + } + + /// Stop the scan session (scanner + attack workers) but KEEP the + /// service alive for later scans and for `StopNetworkManager`. + pub fn stop_scan(&self) { + self.cmd(&Cmd::StopScan); + } + + /// Ask the running crack job (if any) to stop. UI-side flag only — + /// the service is not involved in cracking. + pub fn request_crack_stop(&self) { + if let Some(flag) = &*self.crack_stop.lock().expect("crack_stop poisoned") { + flag.store(true, Ordering::Relaxed); + } + } + + /// Crack worker: stream `wordlist` through the GPU cracker (CPU + /// fallback when no adapter) against `target` — as a plain thread in + /// the UI process (GPU + wordlist need no root). Emits CrackProgress, + /// then exactly one terminator: CrackFound + CrackStopped{found:true} + /// on success, CrackStopped{found:false} on stop or wordlist + /// exhaustion. + pub fn spawn_crack( + &self, + target_desc: String, + target: CrackTarget, + wordlist: PathBuf, + tx: Sender, + ) { + let stop = Arc::new(AtomicBool::new(false)); + *self.crack_stop.lock().expect("crack_stop poisoned") = Some(stop.clone()); + let err_tx = tx.clone(); + let result = std::thread::Builder::new() + .name("wifilab-crack".into()) + .spawn(move || { + let words = match wordlist::open(&wordlist) { + Ok(w) => w, + Err(e) => { + log_err(&tx, format!("cracker: {e:#}")); + send(&tx, Event::CrackStopped { found: false }); + return; + } + }; + let mut words = words; + let mut progress = { + let tx = tx.clone(); + move |done: u64, hps: f64| send(&tx, Event::CrackProgress { done, hps }) + }; + let found = match GpuCracker::try_new() { + Some(g) => { + log( + &tx, + format!( + "cracker: GPU backend: {} — cracking {target_desc}", + g.device_name() + ), + ); + g.crack(&target, &mut words, &mut progress, &stop) + } + None => { + log( + &tx, + format!( + "cracker: no GPU adapter, CPU fallback — cracking {target_desc}" + ), + ); + gpu::cpu_crack(&target, &mut words, &mut progress, &stop) + } + }; + match found { + Some(password) => { + log(&tx, format!("cracker: PASSWORD found: {password}")); + send(&tx, Event::CrackFound { password }); + send(&tx, Event::CrackStopped { found: true }); + } + None => { + if stop.load(Ordering::Relaxed) { + log(&tx, "cracker: stopped"); + } else { + log(&tx, "cracker: wordlist exhausted, password not found"); + } + send(&tx, Event::CrackStopped { found: false }); + } + } + }); + if let Err(e) = result { + send(&err_tx, Event::Error(format!("cracker: spawn failed: {e}"))); + send(&err_tx, Event::CrackStopped { found: false }); + } + } + + /// Tear down: tell the service to stop everything + exit, give it a + /// grace period, then kill and reap. Also stops any UI-side crack job + /// and joins the reader thread. + pub fn shutdown(mut self) { + self.request_crack_stop(); + self.cmd(&Cmd::Shutdown); + // 2 s grace for the service to restore managed mode + exit. + let deadline = Instant::now() + Duration::from_secs(2); + loop { + match self.child.try_wait() { + Ok(Some(_)) => break, + Ok(None) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(25)); + } + Ok(None) => { + let _ = self.child.kill(); + break; + } + Err(_) => break, + } + } + let _ = self.child.wait(); + if let Some(reader) = self.reader.take() { + let _ = reader.join(); + } + } +} + +impl Drop for ServiceClient { + /// Panic-safe mirror of [`ServiceClient::shutdown`]: the service gets + /// a chance to restore the interface even if the UI dies. + fn drop(&mut self) { + self.request_crack_stop(); + self.cmd(&Cmd::Shutdown); + let deadline = Instant::now() + Duration::from_secs(2); + loop { + match self.child.try_wait() { + Ok(Some(_)) => break, + Ok(None) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(25)); + } + Ok(None) => { + let _ = self.child.kill(); + break; + } + Err(_) => break, + } + } + let _ = self.child.wait(); + if let Some(reader) = self.reader.take() { + let _ = reader.join(); + } + } +} diff --git a/src/ui/app.rs b/src/ui/app.rs index 4114ac2..596c3d4 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -1,10 +1,8 @@ //! Root view: nav rail, header bar (interface picker, privilege badge, //! monitor/capture toggle), page content, status line, and the background -//! task that polls the backend event channel. +//! task that polls the service event channel. use std::collections::BTreeMap; -use std::sync::Arc; -use std::sync::atomic::{AtomicU8, Ordering}; use std::time::Duration; use crossbeam_channel::{Receiver, Sender}; @@ -22,11 +20,11 @@ use gpuikit::input::InputState; use gpuikit::layout::{h_stack, v_stack}; use gpuikit::theme::{ActiveTheme, Themeable}; -use crate::backend::Backend; -use crate::common::{Event, MacAddr}; +use crate::common::{Cmd, Event, MacAddr}; +use crate::service::ServiceClient; use crate::ui::{attacks, cracker, log as log_view, networks, state::AppState}; -/// How often the UI drains the backend event channel. +/// How often the UI drains the service event channel. const EVENT_POLL: Duration = Duration::from_millis(100); /// Left nav destinations. @@ -53,16 +51,19 @@ impl Page { pub struct AppRoot { pub state: AppState, - /// Backend event channel (mock thread today, real backend later). + /// Service event channel (mock thread or service reader thread). pub rx: Receiver, /// 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. pub is_root: bool, - /// Real radio/attack/cracker orchestrator. `None` in mock mode or - /// before the first "Start capture". - pub backend: Option, + /// 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. + 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). @@ -81,10 +82,6 @@ pub struct AppRoot { /// Toast queued by the event loop (no Window there) — shown on the /// next render pass. pub pending_toast: Option, - /// Elevate-via-polkit handshake: Some while a pkexec re-exec is in - /// flight. 0 = waiting on the polkit dialog, 1 = elevated instance - /// launched (quit this one), 2 = declined/failed (message was logged). - pub elevation: Option>, /// NetworkManager seen active when capture started (fights channels). pub nm_active: bool, /// Used to invalidate stale cracker simulation ticks after Stop/re-Start. @@ -150,7 +147,7 @@ impl AppRoot { tx, page: Page::Networks, is_root: crate::iface::is_root(), - backend: None, + service: None, is_mock, selected: None, selected_client: None, @@ -159,7 +156,6 @@ impl AppRoot { attacking_pmkid: false, crack_inflight: false, pending_toast: None, - elevation: None, nm_active: false, crack_epoch: 0, ap_sort: None, @@ -178,32 +174,28 @@ impl AppRoot { "wifilab UI started (mock backend)".to_string() } else { format!( - "wifilab UI started (REAL backend, iface {selected_iface}) — Start capture to bring up monitor mode" + "wifilab UI started (REAL backend, iface {selected_iface}) — Start capture spawns the privileged service (polkit) and brings up monitor mode" ) }); cx.on_release(|this, _cx| { - // Window closed → root view released → stop every worker and - // restore the interface to managed mode. - if let Some(be) = this.backend.take() { - be.shutdown(); + // Window closed → root view released → shut the service down + // (it stops workers, restores managed mode, exits) and stop + // any UI-side crack job. + if let Some(svc) = this.service.take() { + svc.shutdown(); } }) .detach(); if !this.is_root && !this.is_mock { - if crate::iface::pkexec_available() { - cx.toast("not root — click \"Elevate via polkit\" in the header to gain privileges") - .show(window, cx); - } else { - cx.toast("not root and polkit (pkexec) unavailable — monitor mode and injection will fail") - .show(window, cx); - } + cx.toast("not root — polkit will ask for authentication when you start capture") + .show(window, cx); } - // Poll the backend event channel: wait on the background executor, + // Poll the service event channel: wait on the background executor, // then reduce everything queued into state on the main thread. The - // backend threads never touch gpui types. + // service reader thread never touches gpui types. cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(EVENT_POLL).await; @@ -222,10 +214,11 @@ impl AppRoot { /// Header "Start/Stop capture" behaviour. /// - /// Real mode: lazily create the [`Backend`] (monitor-mode switch + - /// scanner thread) on the channel-selected interface; Stop shuts it - /// down and restores managed mode. Mock mode: pure UI flips (the mock - /// generator runs independently). + /// Real mode: lazily spawn the privileged service (polkit-elevated + /// when needed) which switches the interface to monitor mode and runs + /// the scanner; Stop only ends the scan session — the service stays + /// alive for the cracker page and later scans. Mock mode: pure UI + /// flips (the mock generator runs independently). pub fn toggle_monitor(&mut self, cx: &mut Context) { if self.is_mock { self.state.iface_running = !self.state.iface_running; @@ -239,29 +232,16 @@ impl AppRoot { return; } if self.state.iface_running { - // STOP: release the radio but KEEP the Backend alive — the - // cracker needs it (cracking has no radio use). `stop_radio` - // restores managed mode and joins the radio workers only. - if let Some(be) = &self.backend { - self.state.push_log("ui: stopping capture, restoring managed mode…"); - cx.notify(); - be.stop_radio(); + // STOP: end the scan session but KEEP the service alive — the + // cracker needs it, and a later Start reuses it. + if let Some(svc) = &self.service { self.state - .push_log("ui: capture stopped, interface restored (cracker stays available)"); + .push_log("ui: stopping capture, service restores managed mode…"); + svc.stop_scan(); } self.state.iface_running = false; cx.notify(); } else { - if !self.is_root { - self.state.push_log( - "ui: capture REFUSED — no root privileges. Elevate via polkit first.".to_string(), - ); - self.pending_toast = Some( - "ELEVATION REQUIRED: click \"Elevate via polkit\" in the header before starting capture".into(), - ); - cx.notify(); - return; - } // NetworkManager fight: pin-to-connected-channel makes ONLY the // associated network (e.g. parafin) visible during the hop. if crate::iface::networkmanager_active() { @@ -275,15 +255,22 @@ impl AppRoot { "NetworkManager is active — only your connected network may be visible; stop it from the header".into(), ); } - // A Backend kept alive for the cracker from a previous capture - // would tear down our new monitor mode in its `Drop` (it - // restores managed mode). Drop it BEFORE the fresh - // `start_scan` switches the interface up in monitor mode. - self.backend = None; let ifname = self.state.ifname.clone(); - match Backend::start_scan(&ifname, self.tx.clone()) { - Ok(be) => { - self.backend = Some(be); + if let Some(svc) = &self.service { + // Service already up (from an earlier session): just ask + // for a fresh scan session. + svc.cmd(&Cmd::StartScan { + ifname: ifname.clone(), + }); + self.state.iface_running = true; + self.state + .push_log(format!("ui: capture started on {ifname}")); + cx.notify(); + return; + } + match ServiceClient::start(&ifname, self.tx.clone()) { + Ok(svc) => { + self.service = Some(svc); self.state.iface_running = true; self.state .push_log(format!("ui: capture started on {ifname}")); @@ -291,88 +278,35 @@ 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()); } } cx.notify(); } } - /// Stop NetworkManager (root) so it stops pinning the radio to the - /// connected network's channel. + /// Stop NetworkManager via the privileged service so it stops pinning + /// the radio to the connected network's channel. pub fn stop_nm(&mut self, cx: &mut Context) { - match crate::iface::stop_networkmanager() { - Ok(()) => { - self.nm_active = false; + match &self.service { + Some(svc) => { + svc.cmd(&Cmd::StopNetworkManager); + self.state + .push_log("ui: asking service to stop NetworkManager…"); + } + None => { self.state.push_log( - "ui: NetworkManager stopped — channel hopping is now exclusive; restart it later with `systemctl start NetworkManager`" - .to_string(), + "ui: NM stop needs the privileged service — Start capture first".to_string(), ); - self.pending_toast = - Some("NetworkManager stopped — all networks become visible as the hopper cycles".into()); - } - Err(e) => { - self.state - .push_log(format!("ERROR stopping NetworkManager: {e:#}")); } } cx.notify(); } - /// Re-exec this app as root via polkit (pkexec). The polkit dialog is - /// fully OS-driven; on success the elevated instance opens its own - /// window and this one closes itself. - pub fn elevate(&mut self, cx: &mut Context) { - if self.is_root || self.is_mock || self.elevation.is_some() { - return; - } - if self.backend.is_some() { - self.state.push_log("ui: stop capture before elevating"); - cx.notify(); - return; - } - let flag = Arc::new(AtomicU8::new(0)); - self.elevation = Some(flag.clone()); - let ifname = self.state.ifname.clone(); - let tx = self.tx.clone(); - self.state.push_log(format!( - "ui: requesting administrative privileges via polkit (restarting elevated on {ifname})…" - )); - cx.notify(); - std::thread::spawn(move || { - match crate::iface::relaunch_elevated(&["--iface", ifname.as_str()]) { - Ok(st) if st.success() => flag.store(1, Ordering::SeqCst), - Ok(st) => { - flag.store(2, Ordering::SeqCst); - let _ = tx.send(Event::Log(format!( - "ui: elevation dialog dismissed or failed (pkexec exit {st})" - ))); - } - Err(e) => { - flag.store(2, Ordering::SeqCst); - let _ = tx.send(Event::Error(format!("polkit elevation failed: {e:#}"))); - } - } - }); - } - /// Drain every queued event, track handshake progress, refresh widgets /// derived from the capture set. fn drain_events(&mut self, cx: &mut Context) { - // Elevation handshake: success → the new elevated window is up, - // close this one; failure → allow retry (message already queued). - if let Some(flag) = &self.elevation { - match flag.load(Ordering::SeqCst) { - 1 => { - self.state - .push_log("ui: elevated instance started — closing this window"); - self.elevation = None; - cx.quit(); - return; - } - 2 => self.elevation = None, - _ => {} - } - } let mut changed = false; let mut captures_changed = false; while let Ok(event) = self.rx.try_recv() { @@ -388,8 +322,20 @@ impl AppRoot { Event::PmkidCaptured(_) => { self.attacking_pmkid = false; } + // Service child died (EOF seen by the reader thread): + // un-flip every running flag and drop the client so the + // next Start spawns a fresh, alive service. + Event::Error(line) if line == "service terminated" => { + self.attacking_handshake = false; + self.attacking_pmkid = false; + self.state.iface_running = false; + self.crack_inflight = false; + if let Some(svc) = self.service.take() { + svc.shutdown(); // reaps the corpse, restores iface + } + } // Any worker error, or a terminal log from an attack - // worker (prefixed by backend.rs; scanner logs are + // worker (prefixed by the service; scanner logs are // excluded), un-spins attack buttons so the UI is never // stuck "working…". Event::Error(_) => { @@ -404,6 +350,16 @@ impl AppRoot { self.attacking_handshake = false; self.attacking_pmkid = false; } + // Service-side NM result: `nm: stopped` / `nm: stop failed …`. + 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(), + ); + } + } Event::CrackStopped { .. } => { self.crack_inflight = false; } @@ -493,29 +449,9 @@ impl AppRoot { } else if self.is_mock { badge("not root (mock)").secondary() } else { - badge("not root — elevate to attack").destructive() + badge("user (service will elevate)").secondary() }; - let elevate_btn = (!self.is_root && !self.is_mock && crate::iface::pkexec_available()) - .then(|| { - let waiting = self.elevation.is_some(); - button( - "elevate-btn", - if waiting { - "waiting for polkit…" - } else { - "Elevate via polkit" - }, - ) - .disabled(waiting) - .on_click({ - let view = view.clone(); - move |_, _window, cx| { - view.update(cx, |app, cx| app.elevate(cx)); - } - }) - }); - let toggle = button( "monitor-toggle", if running { @@ -538,7 +474,7 @@ impl AppRoot { let nm_badge = (self.nm_active && !self.is_mock) .then(|| badge("NM active — channels pinned").destructive()); - let nm_btn = (self.nm_active && self.is_root && !self.is_mock).then(|| { + let nm_btn = (self.nm_active && !self.is_mock).then(|| { button("stop-nm", "Stop NM").on_click({ let view = view.clone(); move |_, _window, cx| { @@ -558,7 +494,6 @@ impl AppRoot { .bg(theme.surface()) .child(div().text_lg().font_weight(FontWeight::BOLD).child("wifilab")) .child(privilege) - .children(elevate_btn) .child(div().w(px(220.)).child(self.iface_select.clone())) .children(nm_badge) .children(nm_btn) diff --git a/src/ui/attacks.rs b/src/ui/attacks.rs index aaa6ec8..f94f2c2 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::{Event, HandshakeCapture, MacAddr, PmkidCapture}; +use crate::common::{Cmd, Event, HandshakeCapture, MacAddr, PmkidCapture}; use crate::ui::app::AppRoot; use crate::ui::mock; @@ -135,8 +135,8 @@ fn capture_handshake(view: &Entity, _window: &mut Window, cx: &mut gpui app.state.push_log(format!( "handshake capture on {essid} ({ap}, ch {channel})…" )); - if let Some(be) = &app.backend { - be.capture_hs(ap, channel, essid, app.tx.clone()); + if let Some(svc) = &app.service { + svc.cmd(&Cmd::CaptureHs { ap, channel, essid }); } cx.notify(); return; @@ -222,8 +222,8 @@ fn pmkid_attack(view: &Entity, _window: &mut Window, cx: &mut gpui::App }; app.state .push_log(format!("pmkid attack on {essid} ({ap}, ch {channel})…")); - if let Some(be) = &app.backend { - be.pmkid(ap, channel, essid, app.tx.clone()); + if let Some(svc) = &app.service { + svc.cmd(&Cmd::Pmkid { ap, channel, essid }); } cx.notify(); return; @@ -282,9 +282,9 @@ fn deauth(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { cx.notify(); return; } - let Some(be) = &app.backend else { + let Some(svc) = &app.service else { app.state - .push_log("deauth: start capture first (the backend owns the radio)"); + .push_log("deauth: start capture first (the service owns the radio)"); cx.notify(); return; }; @@ -310,7 +310,12 @@ fn deauth(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { app.state.push_log(format!( "deauth: {count} rounds → {target} (AP {ap}, ch {channel})" )); - be.deauth(ap, target, channel, count, app.tx.clone()); + svc.cmd(&Cmd::Deauth { + ap, + target, + channel, + count, + }); cx.notify(); return; } @@ -396,8 +401,8 @@ pub fn render( let no_target = app.selected.is_none(); // Real mode without a running capture has no radio: block the buttons // (a matching hint sits next to them). - let no_backend = !app.is_mock && !app.state.iface_running; - let blocked = no_target || no_backend; + let not_running = !app.is_mock && !app.state.iface_running; + let blocked = no_target || not_running; let hs_running = app.attacking_handshake; let pm_running = app.attacking_pmkid; @@ -437,7 +442,7 @@ pub fn render( .when(hs_running || pm_running, |el| { el.child(loading_indicator().small()).child(small("working…")) }) - .when(no_backend, |el| { + .when(not_running, |el| { el.child(small("start capture first to enable attacks")) }); diff --git a/src/ui/cracker.rs b/src/ui/cracker.rs index b7a5006..95dc305 100644 --- a/src/ui/cracker.rs +++ b/src/ui/cracker.rs @@ -111,8 +111,8 @@ fn start(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { "cracker: starting on {desc} via {wordlist} [auto backend]" )); cx.notify(); - match &app.backend { - Some(be) => be.crack( + match &app.service { + Some(svc) => svc.spawn_crack( target.describe(), target, std::path::PathBuf::from(&wordlist), @@ -122,7 +122,7 @@ fn start(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { app.state.cracker.running = false; app.crack_inflight = false; app.state - .push_log("ERROR: cracker: no backend (start capture first, then stop it)"); + .push_log("ERROR: cracker: no service (start capture first, then stop it)"); cx.notify(); } } @@ -187,8 +187,8 @@ fn stop(view: &Entity, _window: &mut Window, cx: &mut gpui::App) { cx.notify(); return; } - if let Some(be) = &app.backend { - be.request_crack_stop(); + if let Some(svc) = &app.service { + svc.request_crack_stop(); app.state.push_log("cracker: stop requested"); } else { app.state.cracker.running = false; @@ -215,10 +215,12 @@ pub fn render( } else { 0.0 }; - // Real mode: cracker needs the radio — capture must be stopped and a - // backend must exist. + // 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.backend.is_none()); + !app.is_mock && (app.state.iface_running || app.service.is_none()); let candidates = if app.is_mock { format!("candidates: {} / {WORDLIST_TOTAL}", cracker.tried) } else { diff --git a/src/ui/mock.rs b/src/ui/mock.rs index d6c5b55..d8dc581 100644 --- a/src/ui/mock.rs +++ b/src/ui/mock.rs @@ -8,7 +8,7 @@ use std::time::{Duration, Instant}; use crossbeam_channel::Sender; use crate::common::{ - AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture, Security, + AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture, Security, now_ms, }; /// Salted deterministic PRNG (xorshift64) — no rand crate, values only need @@ -44,7 +44,7 @@ pub const MOCK_CLIENTS: [MacAddr; 4] = [ ]; fn seed_aps() -> Vec { - let now = Instant::now(); + let now = now_ms(); let ap = |mac: [u8; 6], ssid: &str, channel, security, rssi| AccessPoint { bssid: MacAddr(mac), ssid: ssid.to_string(), @@ -52,7 +52,7 @@ fn seed_aps() -> Vec { security, rssi_dbm: rssi, beacons: 200, - last_seen: now, + last_seen_ms: now, }; vec![ ap([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], "parafin", 6, Security::Wpa2, -42), @@ -65,13 +65,13 @@ fn seed_aps() -> Vec { } fn seed_clients() -> Vec { - let now = Instant::now(); + let now = now_ms(); let cl = |mac: MacAddr, ap: MacAddr, rssi| ClientInfo { mac, ap: Some(ap), rssi_dbm: rssi, frames: 40, - last_seen: now, + last_seen_ms: now, }; vec![ cl(MOCK_CLIENTS[0], MOCK_BSSID, -44), @@ -176,19 +176,19 @@ fn run(tx: Sender) { loop { thread::sleep(Duration::from_millis(200)); let t = started.elapsed().as_secs_f32(); - let now = Instant::now(); + let now = now_ms(); // 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); ap.beacons += rng.below(3); - ap.last_seen = now; + ap.last_seen_ms = now; let _ = tx.send(Event::ApUpdated(ap.clone())); } for cl in &mut clients { cl.rssi_dbm = (cl.rssi_dbm + (rng.below(3) as i8 - 1)).clamp(-90, -30); cl.frames += rng.below(12); - cl.last_seen = now; + cl.last_seen_ms = now; let _ = tx.send(Event::ClientUpdated(cl.clone())); } diff --git a/src/ui/mod.rs b/src/ui/mod.rs index adbf1d3..0f5ba97 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -1,9 +1,8 @@ //! GPUI + gpuikit shell for wifilab. //! -//! `run_app` opens the window and wires the backend event channel. Today the -//! producer is the mock generator in [`mock`]; when the real -//! radiotap/dot11/scanner/attack/cracker threads land they take over the -//! `Sender` side and the UI changes nowhere else. +//! `run_app` opens the window and wires the service event channel: the mock +//! generator in [`mock`] (mock mode) or the privileged-service reader thread +//! feed the `Sender` side; the UI itself never needs root. mod app; mod attacks; @@ -23,8 +22,9 @@ use gpuikit::theme::{GlobalTheme, Theme}; /// Launch the UI. Blocks until the window closes. /// /// `mock_flag` is the CLI `--mock` switch; combined with the legacy -/// `WIFILAB_MOCK` env var. The REAL backend is the default: `Backend` is -/// created lazily on the first "Start capture" click. +/// `WIFILAB_MOCK` env var. The REAL service is the default: the +/// [`crate::service::ServiceClient`] spawns lazily on the first +/// "Start capture" click (polkit-elevated child process). pub fn run_app(iface: Option, mock_flag: bool) { let (tx, rx) = crossbeam_channel::unbounded(); diff --git a/src/ui/networks.rs b/src/ui/networks.rs index c4eb7aa..f1a71d7 100644 --- a/src/ui/networks.rs +++ b/src/ui/networks.rs @@ -1,8 +1,6 @@ //! Networks page: sortable AP table, clients table, row-click target //! selection. -use std::time::Instant; - use gpui::{Context, Entity, IntoElement, ParentElement, Styled, Window, div, px}; use gpuikit::elements::badge::badge; use gpuikit::elements::table::{CellAlign, Column, Row, SortDirection, Table, table}; @@ -26,9 +24,10 @@ const CCOL_RSSI: usize = 2; const CCOL_FRAMES: usize = 3; const CCOL_AGE: usize = 4; -/// Human "last seen" age, e.g. `2s`, `5m`, `1h`. -pub fn age(last_seen: Instant) -> String { - let s = last_seen.elapsed().as_secs(); +/// 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`]). +pub fn age(last_seen_ms: u64) -> String { + let s = crate::common::now_ms().saturating_sub(last_seen_ms) / 1000; if s < 60 { format!("{s}s") } else if s < 3600 { @@ -57,7 +56,7 @@ fn sorted_aps(app: &AppRoot) -> Vec { 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), - COL_AGE => l.last_seen.cmp(&r.last_seen).reverse(), // newest = 0s first + COL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(), // newest = 0s first _ => std::cmp::Ordering::Equal, }; rows.sort_by(|l, r| match sort.direction { @@ -76,7 +75,7 @@ fn sorted_clients(app: &AppRoot) -> Vec { CCOL_AP => 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.cmp(&r.last_seen).reverse(), + CCOL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(), _ => std::cmp::Ordering::Equal, }; rows.sort_by(|l, r| match sort.direction { @@ -159,7 +158,7 @@ fn ap_table(app: &AppRoot, view: &Entity) -> Table { ) .column( Column::new("AGE", |ap: &AccessPoint, _w, _cx| { - div().child(age(ap.last_seen)).into_any_element() + div().child(age(ap.last_seen_ms)).into_any_element() }) .sortable() .fixed(px(70.)) @@ -246,7 +245,7 @@ fn client_table(app: &AppRoot, view: &Entity) -> Table { ) .column( Column::new("AGE", |cl: &ClientInfo, _w, _cx| { - div().child(age(cl.last_seen)).into_any_element() + div().child(age(cl.last_seen_ms)).into_any_element() }) .sortable() .fixed(px(70.)) diff --git a/src/ui/state.rs b/src/ui/state.rs index 070e1cb..9ce4cde 100644 --- a/src/ui/state.rs +++ b/src/ui/state.rs @@ -1,5 +1,5 @@ //! Application state: the UI-side home for everything arriving over the -//! backend event channel. Backend swap-in keeps this type untouched. +//! service event channel (mock thread or privileged-service reader). use std::collections::{BTreeMap, VecDeque}; @@ -25,7 +25,7 @@ pub struct CrackerState { } /// Everything the window renders. Updated exclusively by -/// [`AppState::apply`] so a real backend can reuse the reduction logic. +/// [`AppState::apply`] so a real service can reuse the reduction logic. pub struct AppState { /// Whether the interface is (pretending to be) capturing in monitor mode. pub iface_running: bool, @@ -70,7 +70,7 @@ impl AppState { self.log.push_back(line.into()); } - /// Reduce one backend event into state. Returns `true` when the set of + /// 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 { match event {