UI+service split: pkexec on-demand service, no app respawn; cracker unprivileged; scan RX-stats heartbeat
Browse files at this commite3ca548a8895cdd2dc554951b09dc29cc1f0478eParent: 50b168616 changed files +1182 -640
- Cargo.lock +1 -0
- Cargo.toml +1 -0
- docs/USAGE.md +27 -17
- src/backend.rs +0 -355
- src/common.rs +231 -13
- src/iface.rs +2 -31
- src/main.rs +12 -3
- src/scanner.rs +76 -27
- src/service.rs +697 -0
- src/ui/app.rs +84 -149
- src/ui/attacks.rs +16 -11
- src/ui/cracker.rs +10 -8
- src/ui/mock.rs +8 -8
- src/ui/mod.rs +6 -6
- src/ui/networks.rs +8 -9
- src/ui/state.rs +3 -3
Cargo.lockmodified+1 -0
| @@ -6886,6 +6886,7 @@ dependencies = [ | ||
| 6886 | 6886 | "pbkdf2 0.13.0", |
| 6887 | 6887 | "pollster 0.4.0", |
| 6888 | 6888 | "serde", |
| 6889 | + "serde_json", | |
| 6889 | 6890 | "sha1", |
| 6890 | 6891 | "thiserror 2.0.21", |
| 6891 | 6892 | "tracing", |
Cargo.tomlmodified+1 -0
| @@ -29,6 +29,7 @@ tracing = "0.1" | ||
| 29 | 29 | tracing-subscriber = "0.3" |
| 30 | 30 | clap = { version = "4", features = ["derive"] } |
| 31 | 31 | serde = { version = "1", features = ["derive"] } |
| 32 | +serde_json = "1" | |
| 32 | 33 | byteorder = "1" |
| 33 | 34 | |
| 34 | 35 | [profile.release] |
docs/USAGE.mdmodified+27 -17
| @@ -12,12 +12,16 @@ cargo build --release | ||
| 12 | 12 | ./target/release/wifilab |
| 13 | 13 | ``` |
| 14 | 14 | |
| 15 | -Privileges are handled **inside the UI**: when not running as root the | |
| 16 | -header shows a **"Elevate via polkit"** button — one click pops the | |
| 17 | -system polkit dialog, and the app restarts itself elevated (same window, | |
| 18 | -same selected interface). The unprivileged window closes automatically | |
| 19 | -once the elevated instance is up. Starting a capture while unprivileged | |
| 20 | -just logs a reminder; nothing fails mid-attack. | |
| 15 | +Privileges are handled by a **privileged service**: the UI itself never | |
| 16 | +needs root and never respawns. The first time you click **Start capture** | |
| 17 | +the app spawns the same binary as a child process with the hidden flag | |
| 18 | +`--privileged-worker` — directly when already root, otherwise through | |
| 19 | +`pkexec`, which pops the system polkit dialog **once per capture | |
| 20 | +session**. All radio work (monitor mode, scanning, deauth, PMKID grab, | |
| 21 | +handshake capture) happens inside that service; the two halves talk JSON | |
| 22 | +lines over the child's stdin/stdout and only distilled events cross the | |
| 23 | +pipe. The GPU cracker needs no privilege and runs as a plain thread in | |
| 24 | +the UI process. | |
| 21 | 25 | |
| 22 | 26 | - `--iface <name>` picks the wireless interface (default: first detected |
| 23 | 27 | wireless interface, falling back to `wlp14s0`). The header bar's picker |
| @@ -25,17 +29,19 @@ just logs a reminder; nothing fails mid-attack. | ||
| 25 | 29 | - `--mock` (or `WIFILAB_MOCK=1`) runs the UI against fabricated events — |
| 26 | 30 | no device access, for development only. |
| 27 | 31 | - On startup the tool prints one line: mode, interface, root status. |
| 28 | - Not root? The badge shows it and a toast warns once — the UI stays | |
| 29 | - usable, but every attack will fail with errors in the Log page. | |
| 32 | + Not root? The badge says *user (service will elevate)* and a toast | |
| 33 | + notes polkit will ask when capture starts — the UI stays fully usable. | |
| 34 | + A dismissed polkit dialog just logs an error; click Start again to | |
| 35 | + retry. | |
| 30 | 36 | |
| 31 | 37 | **NetworkManager fight:** while NetworkManager is active it pins the card |
| 32 | 38 | to the connected network's channel — during a scan you will typically see |
| 33 | 39 | **only that one SSID** (e.g. your connected network) instead of every |
| 34 | 40 | neighbour. The app detects this at *Start capture*, shows a destructive |
| 35 | 41 | toast, logs a warning, and offers a **"Stop NM"** button in the header |
| 36 | -(one click, uses the elevated session). Restore it afterwards with | |
| 37 | -`systemctl start NetworkManager`. Everything else on the system is left | |
| 38 | -untouched. | |
| 42 | +(the request runs inside the elevated service). Restore it afterwards | |
| 43 | +with `systemctl start NetworkManager`. Everything else on the system is | |
| 44 | +left untouched. | |
| 39 | 45 | |
| 40 | 46 | ## Workflow |
| 41 | 47 | |
| @@ -62,13 +68,17 @@ untouched. | ||
| 62 | 68 | point the wordlist field at e.g. `/usr/share/wordlists/rockyou.txt`, |
| 63 | 69 | hit **Start**. Live H/s and candidate count stream in. **Stop** flips |
| 64 | 70 | the job's stop flag and the worker exits at the next batch. |
| 65 | -5. Everything the backend does is mirrored on the **Log** page, including | |
| 66 | - worker errors (permissions, channel-change failures, wordlist open | |
| 67 | - failures). | |
| 71 | +5. Everything the service (and the crack thread) does is mirrored on the | |
| 72 | + **Log** page, including worker errors (permissions, channel-change | |
| 73 | + failures, wordlist open failures). During a scan a compact | |
| 74 | + `scan: N rx frames, M beacons -> K APs live (ch C)` heartbeat lands | |
| 75 | + every 10 s — the evidence line distinguishing RX-silence from parser | |
| 76 | + drops. | |
| 68 | 77 | |
| 69 | -On exit (window close) all workers are stopped and the interface is | |
| 70 | -restored to managed mode (the `<iface>mon` vif is deleted if one was | |
| 71 | -created). | |
| 78 | +On exit (window close) the service is told to shut down: it stops all | |
| 79 | +radio workers, restores the interface to managed mode (deleting the | |
| 80 | +`<iface>mon` vif if one was created), and exits; the UI-side crack | |
| 81 | +thread is stopped as well. | |
| 72 | 82 | |
| 73 | 83 | ## Cracking backends |
| 74 | 84 |
src/backend.rsdeleted+0 -355
| @@ -1,355 +0,0 @@ | ||
| 1 | -//! Backend orchestrator: owns the interface mode switch and every worker | |
| 2 | -//! thread (scanner, deauth, PMKID grab, 4-way capture, cracker). All | |
| 3 | -//! workers share a single stop flag and report over the UI event channel; | |
| 4 | -//! the UI stores one `Backend` and drops/shuts it down on window close. | |
| 5 | -//! | |
| 6 | -//! Concurrency notes: | |
| 7 | -//! - The scanner and any attack worker can coexist (deauth while capturing | |
| 8 | -//! is the whole point). Attack workers open their OWN [`RawSocket`] on | |
| 9 | -//! the monitor interface and set the channel themselves; concurrent | |
| 10 | -//! attacks should therefore target the SAME channel — this matches the | |
| 11 | -//! UI, which implies a single target. | |
| 12 | -//! - `to_monitor` may create a `<orig>mon` vif; the actual monitor ifname | |
| 13 | -//! is remembered and passed to [`iface::to_managed`] on shutdown | |
| 14 | -//! (it deletes the vif or flips the interface back, as appropriate). | |
| 15 | - | |
| 16 | -use std::path::PathBuf; | |
| 17 | -use std::sync::atomic::{AtomicBool, Ordering}; | |
| 18 | -use std::sync::{Arc, Mutex}; | |
| 19 | -use std::thread::JoinHandle; | |
| 20 | - | |
| 21 | -use anyhow::{Context, Result}; | |
| 22 | -use crossbeam_channel::Sender; | |
| 23 | - | |
| 24 | -use crate::common::{Event, MacAddr}; | |
| 25 | -use crate::crypto::CrackTarget; | |
| 26 | -use crate::gpu::{self, GpuCracker}; | |
| 27 | -use crate::rawsock::RawSocket; | |
| 28 | -use crate::{deauth, handshake, iface, pmkid, scanner, wordlist}; | |
| 29 | - | |
| 30 | -fn send(tx: &Sender<Event>, ev: Event) { | |
| 31 | - let _ = tx.send(ev); | |
| 32 | -} | |
| 33 | - | |
| 34 | -fn log(tx: &Sender<Event>, msg: impl Into<String>) { | |
| 35 | - send(tx, Event::Log(msg.into())); | |
| 36 | -} | |
| 37 | - | |
| 38 | -fn log_err(tx: &Sender<Event>, msg: impl Into<String>) { | |
| 39 | - send(tx, Event::Error(msg.into())); | |
| 40 | -} | |
| 41 | - | |
| 42 | -pub struct Backend { | |
| 43 | - stop: Arc<AtomicBool>, | |
| 44 | - handles: Mutex<Vec<JoinHandle<()>>>, | |
| 45 | - /// Name of the interface currently in monitor mode (`None` if the | |
| 46 | - /// mode switch failed at start — nothing to restore then). | |
| 47 | - mon_ifname: Option<String>, | |
| 48 | - /// Interface the user selected; restored to managed mode on shutdown | |
| 49 | - /// when it differs from `mon_ifname`. | |
| 50 | - orig_ifname: String, | |
| 51 | - /// Stop flag of the currently running crack job (if any). Kept | |
| 52 | - /// separate from `stop` so "Stop" on the cracker page doesn't kill | |
| 53 | - /// the radio workers and `shutdown` can kill both. | |
| 54 | - crack_stop: Mutex<Option<Arc<AtomicBool>>>, | |
| 55 | -} | |
| 56 | - | |
| 57 | -impl Backend { | |
| 58 | - /// Switch `ifname` to monitor mode and start the channel-hopping | |
| 59 | - /// scanner (full 2.4 + 5 GHz hop list). On any failure an | |
| 60 | - /// [`Event::Error`] is emitted, the interface is put back into managed | |
| 61 | - /// mode, and `Err` is returned. | |
| 62 | - pub fn start_scan(ifname: &str, tx: Sender<Event>) -> Result<Self> { | |
| 63 | - let mon_ifname = match iface::to_monitor(ifname) { | |
| 64 | - Ok(name) => name, | |
| 65 | - Err(e) => { | |
| 66 | - log_err(&tx, format!("monitor mode on {ifname} failed: {e:#}")); | |
| 67 | - // Best effort: leave the box the way we found it. | |
| 68 | - let _ = iface::to_managed(ifname); | |
| 69 | - return Err(e).context(format!("to_monitor({ifname})")); | |
| 70 | - } | |
| 71 | - }; | |
| 72 | - let be = Backend { | |
| 73 | - stop: Arc::new(AtomicBool::new(false)), | |
| 74 | - handles: Mutex::new(Vec::new()), | |
| 75 | - mon_ifname: Some(mon_ifname.clone()), | |
| 76 | - orig_ifname: ifname.to_string(), | |
| 77 | - crack_stop: Mutex::new(None), | |
| 78 | - }; | |
| 79 | - log(&tx, format!("monitor mode up on {mon_ifname} (was {ifname})")); | |
| 80 | - | |
| 81 | - let cfg = scanner::ScannerConfig { | |
| 82 | - ifname: mon_ifname, | |
| 83 | - channels: Vec::new(), // empty = full hop list | |
| 84 | - dwell_ms: 100, | |
| 85 | - rssi_floor: -95, | |
| 86 | - }; | |
| 87 | - let stop = be.stop.clone(); | |
| 88 | - let h = std::thread::Builder::new() | |
| 89 | - .name("wifilab-scanner".into()) | |
| 90 | - .spawn(move || { | |
| 91 | - if let Err(e) = scanner::run(cfg, tx.clone(), stop) { | |
| 92 | - log_err(&tx, format!("scanner stopped: {e:#}")); | |
| 93 | - } | |
| 94 | - }) | |
| 95 | - .context("spawning scanner thread")?; | |
| 96 | - be.handles.lock().expect("handles poisoned").push(h); | |
| 97 | - Ok(be) | |
| 98 | - } | |
| 99 | - | |
| 100 | - fn mon(&self) -> String { | |
| 101 | - self.mon_ifname | |
| 102 | - .clone() | |
| 103 | - .unwrap_or_else(|| self.orig_ifname.clone()) | |
| 104 | - } | |
| 105 | - | |
| 106 | - /// Register a worker thread so [`Backend::shutdown`] joins it. The | |
| 107 | - /// worker closure takes ownership of an event channel clone; on spawn | |
| 108 | - /// failure the error is reported on the caller's `tx`. | |
| 109 | - fn spawn( | |
| 110 | - &self, | |
| 111 | - name: &str, | |
| 112 | - tx: &Sender<Event>, | |
| 113 | - what: &str, | |
| 114 | - f: impl FnOnce(Sender<Event>) + Send + 'static, | |
| 115 | - ) -> bool { | |
| 116 | - let worker_tx = tx.clone(); | |
| 117 | - match std::thread::Builder::new() | |
| 118 | - .name(name.to_string()) | |
| 119 | - .spawn(move || f(worker_tx)) | |
| 120 | - { | |
| 121 | - Ok(h) => { | |
| 122 | - self.handles.lock().expect("handles poisoned").push(h); | |
| 123 | - true | |
| 124 | - } | |
| 125 | - Err(e) => { | |
| 126 | - log_err(tx, format!("{what}: spawn failed: {e}")); | |
| 127 | - false | |
| 128 | - } | |
| 129 | - } | |
| 130 | - } | |
| 131 | - | |
| 132 | - /// Ask the running crack job (if any) to stop. Independent of the | |
| 133 | - /// radio stop flag: killing capture should not need a wordlist stream | |
| 134 | - /// to die with it. | |
| 135 | - pub fn request_crack_stop(&self) { | |
| 136 | - if let Some(flag) = &*self.crack_stop.lock().expect("crack_stop poisoned") { | |
| 137 | - flag.store(true, Ordering::Relaxed); | |
| 138 | - } | |
| 139 | - } | |
| 140 | - | |
| 141 | - /// Deauth worker: opens its own raw socket on the monitor interface, | |
| 142 | - /// tunes it to `channel`, then blasts `count` deauth rounds at | |
| 143 | - /// `target` (broadcast allowed). Emits DeauthSent progress (via | |
| 144 | - /// [`deauth::blast`]) and a final summary log. | |
| 145 | - pub fn deauth( | |
| 146 | - &self, | |
| 147 | - ap: MacAddr, | |
| 148 | - target: MacAddr, | |
| 149 | - channel: u8, | |
| 150 | - count: u32, | |
| 151 | - tx: Sender<Event>, | |
| 152 | - ) { | |
| 153 | - let mon = self.mon(); | |
| 154 | - self.spawn("wifilab-deauth", &tx, "deauth", move |tx| { | |
| 155 | - let sock = match RawSocket::open(&mon) { | |
| 156 | - Ok(s) => s, | |
| 157 | - Err(e) => { | |
| 158 | - log_err(&tx, format!("deauth: raw socket on {mon} failed: {e}")); | |
| 159 | - return; | |
| 160 | - } | |
| 161 | - }; | |
| 162 | - if let Err(e) = iface::set_channel(&mon, channel) { | |
| 163 | - // Not fatal: the capture worker is usually already parked | |
| 164 | - // on the right channel. | |
| 165 | - log(&tx, format!("deauth: set_channel {channel} failed: {e:#}")); | |
| 166 | - } | |
| 167 | - match deauth::blast(&sock, &ap, &target, count, &tx) { | |
| 168 | - Ok(sent) => log(&tx, format!("deauth: done, {sent} frames → {target}")), | |
| 169 | - Err(e) => log_err(&tx, format!("deauth: {e:#}")), | |
| 170 | - } | |
| 171 | - }); | |
| 172 | - } | |
| 173 | - | |
| 174 | - /// PMKID grab worker: single client-less auth+assoc attempt against | |
| 175 | - /// `ap`, impersonating the monitor interface's own MAC. Emits | |
| 176 | - /// PmkidCaptured or a "no PMKID" log line. | |
| 177 | - pub fn pmkid(&self, ap: MacAddr, channel: u8, essid: String, tx: Sender<Event>) { | |
| 178 | - let mon = self.mon(); | |
| 179 | - self.spawn("wifilab-pmkid", &tx, "pmkid", move |tx| { | |
| 180 | - let sta = match iface::mac_of(&mon) { | |
| 181 | - Ok(m) => m, | |
| 182 | - Err(e) => { | |
| 183 | - log_err(&tx, format!("pmkid: own MAC of {mon}: {e:#}")); | |
| 184 | - return; | |
| 185 | - } | |
| 186 | - }; | |
| 187 | - let sock = match RawSocket::open(&mon) { | |
| 188 | - Ok(s) => s, | |
| 189 | - Err(e) => { | |
| 190 | - log_err(&tx, format!("pmkid: raw socket on {mon} failed: {e}")); | |
| 191 | - return; | |
| 192 | - } | |
| 193 | - }; | |
| 194 | - if let Err(e) = iface::set_channel(&mon, channel) { | |
| 195 | - log(&tx, format!("pmkid: set_channel {channel} failed: {e:#}")); | |
| 196 | - } | |
| 197 | - match pmkid::grab(&sock, &ap, &sta, &essid, &tx) { | |
| 198 | - Ok(Some(cap)) => send(&tx, Event::PmkidCaptured(cap)), | |
| 199 | - Ok(None) => log(&tx, format!("pmkid: no PMKID volunteered by {ap}")), | |
| 200 | - Err(e) => log_err(&tx, format!("pmkid: {e:#}")), | |
| 201 | - } | |
| 202 | - }); | |
| 203 | - } | |
| 204 | - | |
| 205 | - /// 4-way capture worker: tune the monitor interface to `channel`, open | |
| 206 | - /// a raw socket, and run [`handshake::capture_loop`] (stop flag | |
| 207 | - /// checked every 250 ms frame poll). [`Event::HandshakeComplete`] is | |
| 208 | - /// emitted from inside the loop when a crackable pair completes. | |
| 209 | - pub fn capture_hs(&self, ap: MacAddr, channel: u8, essid: String, tx: Sender<Event>) { | |
| 210 | - let mon = self.mon(); | |
| 211 | - let stop = self.stop.clone(); | |
| 212 | - self.spawn("wifilab-capture", &tx, "handshake", move |tx| { | |
| 213 | - if let Err(e) = iface::set_channel(&mon, channel) { | |
| 214 | - log_err(&tx, format!("handshake: set_channel {channel} on {mon}: {e:#}")); | |
| 215 | - return; | |
| 216 | - } | |
| 217 | - let sock = match RawSocket::open(&mon) { | |
| 218 | - Ok(s) => s, | |
| 219 | - Err(e) => { | |
| 220 | - log_err(&tx, format!("handshake: raw socket on {mon} failed: {e}")); | |
| 221 | - return; | |
| 222 | - } | |
| 223 | - }; | |
| 224 | - match handshake::capture_loop(&sock, ap, &essid, &tx, &stop) { | |
| 225 | - Ok(true) => {} | |
| 226 | - Ok(false) => log(&tx, format!("handshake: capture ended without a pair ({ap})")), | |
| 227 | - Err(e) => log_err(&tx, format!("handshake: {e:#}")), | |
| 228 | - } | |
| 229 | - }); | |
| 230 | - } | |
| 231 | - | |
| 232 | - /// Crack worker: stream `wordlist` through the GPU cracker (CPU | |
| 233 | - /// fallback when no adapter) against `target`. Emits CrackProgress, | |
| 234 | - /// then exactly one terminator: CrackFound + CrackStopped{found:true} | |
| 235 | - /// on success, CrackStopped{found:false} on stop or wordlist | |
| 236 | - /// exhaustion. | |
| 237 | - pub fn crack( | |
| 238 | - &self, | |
| 239 | - target_desc: String, | |
| 240 | - target: CrackTarget, | |
| 241 | - wordlist: PathBuf, | |
| 242 | - tx: Sender<Event>, | |
| 243 | - ) { | |
| 244 | - // Cracking has its own stop flag (cracker-page Stop) but shutdown | |
| 245 | - // kills it too (see stop_workers/Drop, which set both). | |
| 246 | - let stop = Arc::new(AtomicBool::new(false)); | |
| 247 | - *self.crack_stop.lock().expect("crack_stop poisoned") = Some(stop.clone()); | |
| 248 | - self.spawn("wifilab-crack", &tx, "cracker", move |tx| { | |
| 249 | - let words = match wordlist::open(&wordlist) { | |
| 250 | - Ok(w) => w, | |
| 251 | - Err(e) => { | |
| 252 | - log_err(&tx, format!("cracker: {e:#}")); | |
| 253 | - send(&tx, Event::CrackStopped { found: false }); | |
| 254 | - return; | |
| 255 | - } | |
| 256 | - }; | |
| 257 | - let mut words = words; | |
| 258 | - let mut progress = { | |
| 259 | - let tx = tx.clone(); | |
| 260 | - move |done: u64, hps: f64| send(&tx, Event::CrackProgress { done, hps }) | |
| 261 | - }; | |
| 262 | - let found = match GpuCracker::try_new() { | |
| 263 | - Some(g) => { | |
| 264 | - log( | |
| 265 | - &tx, | |
| 266 | - format!("cracker: GPU backend: {} — cracking {target_desc}", g.device_name()), | |
| 267 | - ); | |
| 268 | - g.crack(&target, &mut words, &mut progress, &stop) | |
| 269 | - } | |
| 270 | - None => { | |
| 271 | - log( | |
| 272 | - &tx, | |
| 273 | - format!("cracker: no GPU adapter, CPU fallback — cracking {target_desc}"), | |
| 274 | - ); | |
| 275 | - gpu::cpu_crack(&target, &mut words, &mut progress, &stop) | |
| 276 | - } | |
| 277 | - }; | |
| 278 | - match found { | |
| 279 | - Some(password) => { | |
| 280 | - log(&tx, format!("cracker: PASSWORD found: {password}")); | |
| 281 | - send(&tx, Event::CrackFound { password }); | |
| 282 | - send(&tx, Event::CrackStopped { found: true }); | |
| 283 | - } | |
| 284 | - None => { | |
| 285 | - if stop.load(Ordering::Relaxed) { | |
| 286 | - log(&tx, "cracker: stopped"); | |
| 287 | - } else { | |
| 288 | - log(&tx, "cracker: wordlist exhausted, password not found"); | |
| 289 | - } | |
| 290 | - send(&tx, Event::CrackStopped { found: false }); | |
| 291 | - } | |
| 292 | - } | |
| 293 | - }); | |
| 294 | - } | |
| 295 | - | |
| 296 | - /// Stop radio work (scanner + attack workers) and restore managed | |
| 297 | - /// mode, but KEEP the Backend alive so the cracker can still run | |
| 298 | - /// afterwards: the UI keeps `Some(backend)` after "Stop capture". | |
| 299 | - /// A still-running crack job is untouched (it has no radio use). | |
| 300 | - /// Idempotent; a later `start_scan` simply replaces this Backend. | |
| 301 | - pub fn stop_radio(&self) { | |
| 302 | - self.stop.store(true, Ordering::Release); | |
| 303 | - if let Some(mon) = &self.mon_ifname { | |
| 304 | - if let Err(e) = iface::to_managed(mon) { | |
| 305 | - eprintln!("wifilab: to_managed({mon}) failed: {e:#}"); | |
| 306 | - } | |
| 307 | - } | |
| 308 | - // Safe to join radio handles here: the UI disables the capture | |
| 309 | - // toggle while a crack runs, so no unfinished crack thread sits | |
| 310 | - // in this list. | |
| 311 | - let handles = std::mem::take(&mut *self.handles.lock().expect("handles poisoned")); | |
| 312 | - for h in handles { | |
| 313 | - let _ = h.join(); | |
| 314 | - } | |
| 315 | - } | |
| 316 | - | |
| 317 | - /// Stop every worker, restore the original interface to managed mode | |
| 318 | - /// (deleting the `<orig>mon` vif if one was created), and join all | |
| 319 | - /// threads. Idempotent: safe to call more than once / from `Drop`. | |
| 320 | - pub fn shutdown(self) { | |
| 321 | - self.stop_workers(); | |
| 322 | - } | |
| 323 | - | |
| 324 | - /// Inner shutdown shared with `Drop` (which cannot move `self`). | |
| 325 | - fn stop_workers(&self) { | |
| 326 | - self.stop.store(true, Ordering::Release); | |
| 327 | - self.request_crack_stop(); | |
| 328 | - if let Some(mon) = &self.mon_ifname { | |
| 329 | - if let Err(e) = iface::to_managed(mon) { | |
| 330 | - eprintln!("wifilab: to_managed({mon}) failed: {e:#}"); | |
| 331 | - } | |
| 332 | - } | |
| 333 | - let handles = std::mem::take(&mut *self.handles.lock().expect("handles poisoned")); | |
| 334 | - for h in handles { | |
| 335 | - let _ = h.join(); | |
| 336 | - } | |
| 337 | - } | |
| 338 | -} | |
| 339 | - | |
| 340 | -impl Drop for Backend { | |
| 341 | - /// Panic-safe mirror of [`Backend::shutdown`] — same steps, ignores | |
| 342 | - /// errors silently as far as possible; never panics itself. | |
| 343 | - fn drop(&mut self) { | |
| 344 | - self.stop.store(true, Ordering::Release); | |
| 345 | - self.request_crack_stop(); | |
| 346 | - if let Some(mon) = &self.mon_ifname { | |
| 347 | - let _ = iface::to_managed(mon); | |
| 348 | - } | |
| 349 | - if let Ok(mut guard) = self.handles.lock() { | |
| 350 | - for h in std::mem::take(&mut *guard) { | |
| 351 | - let _ = h.join(); | |
| 352 | - } | |
| 353 | - } | |
| 354 | - } | |
| 355 | -} |
src/common.rsmodified+231 -13
| @@ -1,12 +1,29 @@ | ||
| 1 | 1 | //! Shared domain types — the contract between radio, attack, crypto and UI |
| 2 | -//! layers. Signatures and field meanings here are FIXED; implementations must | |
| 3 | -//! conform exactly. All times are `std::time::Instant`, RSSI in dBm. | |
| 2 | +//! layers, AND the wire format between the UI process and the privileged | |
| 3 | +//! service (`--privileged-worker` child): every type here (plus [`Cmd`]) | |
| 4 | +//! serializes through `serde_json` lines. Signatures and field meanings are | |
| 5 | +//! FIXED; implementations must conform exactly. Times are `last_seen_ms` | |
| 6 | +//! (millis since the process-local epoch, see [`now_ms`]), RSSI in dBm. | |
| 4 | 7 | |
| 5 | 8 | use std::fmt; |
| 6 | 9 | use std::time::Instant; |
| 7 | 10 | |
| 11 | +use serde::{Deserialize, Serialize}; | |
| 12 | + | |
| 13 | +/// Process-local epoch: `now_ms` returns elapsed millis since the first | |
| 14 | +/// deref of this static. Every process has its own epoch — values are only | |
| 15 | +/// comparable within one process. | |
| 16 | +#[doc(hidden)] | |
| 17 | +static EPOCH: std::sync::LazyLock<Instant> = std::sync::LazyLock::new(Instant::now); | |
| 18 | + | |
| 19 | +/// Milliseconds since the process-local epoch; used for `last_seen_ms` | |
| 20 | +/// timestamps so they cross the UI/service JSON pipe (an `Instant` can't). | |
| 21 | +pub fn now_ms() -> u64 { | |
| 22 | + EPOCH.elapsed().as_millis() as u64 | |
| 23 | +} | |
| 24 | + | |
| 8 | 25 | /// 6-octet 802.11 MAC address. |
| 9 | -#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] | |
| 26 | +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)] | |
| 10 | 27 | pub struct MacAddr(pub [u8; 6]); |
| 11 | 28 | |
| 12 | 29 | impl MacAddr { |
| @@ -54,7 +71,7 @@ impl std::str::FromStr for MacAddr { | ||
| 54 | 71 | } |
| 55 | 72 | |
| 56 | 73 | /// WLAN security suite derived from RSN/WPA IEs (or lack thereof). |
| 57 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 74 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] | |
| 58 | 75 | pub enum Security { |
| 59 | 76 | Open, |
| 60 | 77 | Wep, |
| @@ -79,7 +96,7 @@ impl Security { | ||
| 79 | 96 | } |
| 80 | 97 | |
| 81 | 98 | /// A discovered access point. Live-updated by the scanner. |
| 82 | -#[derive(Clone, Debug)] | |
| 99 | +#[derive(Clone, Debug, Serialize, Deserialize)] | |
| 83 | 100 | pub struct AccessPoint { |
| 84 | 101 | pub bssid: MacAddr, |
| 85 | 102 | pub ssid: String, |
| @@ -87,22 +104,26 @@ pub struct AccessPoint { | ||
| 87 | 104 | pub security: Security, |
| 88 | 105 | pub rssi_dbm: i8, |
| 89 | 106 | pub beacons: u64, |
| 90 | - pub last_seen: Instant, | |
| 107 | + /// Millis since the process-local epoch ([`now_ms`]) of the last frame | |
| 108 | + /// seen from this AP. Age display = `now_ms() - last_seen_ms`. | |
| 109 | + pub last_seen_ms: u64, | |
| 91 | 110 | } |
| 92 | 111 | |
| 93 | 112 | /// A discovered client station. |
| 94 | -#[derive(Clone, Debug)] | |
| 113 | +#[derive(Clone, Debug, Serialize, Deserialize)] | |
| 95 | 114 | pub struct ClientInfo { |
| 96 | 115 | pub mac: MacAddr, |
| 97 | 116 | /// BSSID of the AP this station is talking to, if determinable. |
| 98 | 117 | pub ap: Option<MacAddr>, |
| 99 | 118 | pub rssi_dbm: i8, |
| 100 | 119 | pub frames: u64, |
| 101 | - pub last_seen: Instant, | |
| 120 | + /// Millis since the process-local epoch ([`now_ms`]) of the last frame | |
| 121 | + /// seen from this station. | |
| 122 | + pub last_seen_ms: u64, | |
| 102 | 123 | } |
| 103 | 124 | |
| 104 | 125 | /// A complete, crackable WPA 4-way handshake capture (M1+M2 minimum). |
| 105 | -#[derive(Clone, Debug)] | |
| 126 | +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] | |
| 106 | 127 | pub struct HandshakeCapture { |
| 107 | 128 | pub ap: MacAddr, |
| 108 | 129 | pub client: MacAddr, |
| @@ -148,7 +169,7 @@ impl HandshakeCapture { | ||
| 148 | 169 | } |
| 149 | 170 | |
| 150 | 171 | /// A PMKID capture (clientless attack result). |
| 151 | -#[derive(Clone, Debug)] | |
| 172 | +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] | |
| 152 | 173 | pub struct PmkidCapture { |
| 153 | 174 | pub ap: MacAddr, |
| 154 | 175 | pub client: MacAddr, // the station we impersonated (our MAC) |
| @@ -156,9 +177,11 @@ pub struct PmkidCapture { | ||
| 156 | 177 | pub pmkid: [u8; 16], |
| 157 | 178 | } |
| 158 | 179 | |
| 159 | -/// Events flowing from worker threads (scanner/capture/attacks/cracker) to | |
| 160 | -/// the UI over a `crossbeam_channel::Sender<Event>`. | |
| 161 | -#[derive(Clone, Debug)] | |
| 180 | +/// Events flowing from worker threads to the UI. In the real architecture | |
| 181 | +/// the privileged service serializes them as `serde_json` lines on the | |
| 182 | +/// child's stdout; in mock mode a thread pushes them onto a | |
| 183 | +/// `crossbeam_channel::Sender<Event>` directly. | |
| 184 | +#[derive(Clone, Debug, Serialize, Deserialize)] | |
| 162 | 185 | pub enum Event { |
| 163 | 186 | ApUpdated(AccessPoint), |
| 164 | 187 | ApLost(MacAddr), |
| @@ -190,3 +213,198 @@ pub enum Event { | ||
| 190 | 213 | /// lab card (keep conservative, driver validates anyway). |
| 191 | 214 | pub const HOP_CHANNELS_24: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; |
| 192 | 215 | pub const HOP_CHANNELS_5: &[u8] = &[36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128]; |
| 216 | + | |
| 217 | +/// Commands the UI process sends to the privileged service | |
| 218 | +/// (`--privileged-worker` child), serialized as one `serde_json` line each | |
| 219 | +/// on the child's stdin. | |
| 220 | +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] | |
| 221 | +pub enum Cmd { | |
| 222 | + /// Switch `ifname` to monitor mode and start the channel-hopping | |
| 223 | + /// scanner. `ifname` is saved as the interface to restore on | |
| 224 | + /// StopScan/Shutdown. | |
| 225 | + StartScan { ifname: String }, | |
| 226 | + /// Stop the scanner, restore managed mode. | |
| 227 | + StopScan, | |
| 228 | + /// Blast `count` deauth rounds at `target` (broadcast allowed) from | |
| 229 | + /// `ap`, after tuning to `channel`. | |
| 230 | + Deauth { | |
| 231 | + ap: MacAddr, | |
| 232 | + target: MacAddr, | |
| 233 | + channel: u8, | |
| 234 | + count: u32, | |
| 235 | + }, | |
| 236 | + /// Clientless PMKID grab against `ap`. | |
| 237 | + Pmkid { | |
| 238 | + ap: MacAddr, | |
| 239 | + channel: u8, | |
| 240 | + essid: String, | |
| 241 | + }, | |
| 242 | + /// Park on `ap`'s channel and track its 4-way handshakes. | |
| 243 | + CaptureHs { | |
| 244 | + ap: MacAddr, | |
| 245 | + channel: u8, | |
| 246 | + essid: String, | |
| 247 | + }, | |
| 248 | + /// Stop NetworkManager/wpa_supplicant so they stop pinning the radio. | |
| 249 | + StopNetworkManager, | |
| 250 | + /// Stop all workers, restore the interface, exit the service. | |
| 251 | + Shutdown, | |
| 252 | +} | |
| 253 | + | |
| 254 | +#[cfg(test)] | |
| 255 | +mod tests { | |
| 256 | + use super::*; | |
| 257 | + | |
| 258 | + fn ap_obj() -> AccessPoint { | |
| 259 | + AccessPoint { | |
| 260 | + bssid: MacAddr([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]), | |
| 261 | + ssid: "parafin".into(), | |
| 262 | + channel: 6, | |
| 263 | + security: Security::Wpa2, | |
| 264 | + rssi_dbm: -42, | |
| 265 | + beacons: 7, | |
| 266 | + last_seen_ms: 123_456, | |
| 267 | + } | |
| 268 | + } | |
| 269 | + | |
| 270 | + fn client_obj() -> ClientInfo { | |
| 271 | + ClientInfo { | |
| 272 | + mac: MacAddr([0x11; 6]), | |
| 273 | + ap: Some(MacAddr([0xaa; 6])), | |
| 274 | + rssi_dbm: -55, | |
| 275 | + frames: 3, | |
| 276 | + last_seen_ms: 654_321, | |
| 277 | + } | |
| 278 | + } | |
| 279 | + | |
| 280 | + fn handshake_obj() -> HandshakeCapture { | |
| 281 | + HandshakeCapture::new( | |
| 282 | + MacAddr([1; 6]), | |
| 283 | + MacAddr([2; 6]), | |
| 284 | + "labnet".into(), | |
| 285 | + [3u8; 32], | |
| 286 | + [4u8; 32], | |
| 287 | + [5u8; 16], | |
| 288 | + vec![6u8; 99], | |
| 289 | + 2, | |
| 290 | + ) | |
| 291 | + } | |
| 292 | + | |
| 293 | + fn pmkid_obj() -> PmkidCapture { | |
| 294 | + PmkidCapture { | |
| 295 | + ap: MacAddr([7; 6]), | |
| 296 | + client: MacAddr([8; 6]), | |
| 297 | + essid: "corp".into(), | |
| 298 | + pmkid: [9u8; 16], | |
| 299 | + } | |
| 300 | + } | |
| 301 | + | |
| 302 | + fn roundtrip<T>(value: &T) -> T | |
| 303 | + where | |
| 304 | + T: Serialize + for<'de> Deserialize<'de> + std::fmt::Debug, | |
| 305 | + { | |
| 306 | + let json = serde_json::to_string(value).expect("serialize"); | |
| 307 | + serde_json::from_str(&json).unwrap_or_else(|e| panic!("deserialize {json}: {e}")) | |
| 308 | + } | |
| 309 | + | |
| 310 | + #[test] | |
| 311 | + fn now_ms_is_monotonic_and_ms_scale() { | |
| 312 | + let a = now_ms(); | |
| 313 | + let b = now_ms(); | |
| 314 | + assert!(b >= a); | |
| 315 | + // Same-process sanity: first deref happens at most a few hundred ms | |
| 316 | + // before this test runs (process start); elapsed must stay small. | |
| 317 | + assert!(a < 120_000, "process-local epoch ms implausibly large: {a}"); | |
| 318 | + } | |
| 319 | + | |
| 320 | + #[test] | |
| 321 | + fn event_json_roundtrips() { | |
| 322 | + let cases: Vec<Event> = vec![ | |
| 323 | + Event::ApUpdated(ap_obj()), | |
| 324 | + Event::ApLost(MacAddr::BROADCAST), | |
| 325 | + Event::ClientUpdated(client_obj()), | |
| 326 | + Event::HandshakeProgress { | |
| 327 | + ap: MacAddr([1; 6]), | |
| 328 | + client: MacAddr([2; 6]), | |
| 329 | + have: 0b1011, | |
| 330 | + }, | |
| 331 | + Event::HandshakeComplete(Box::new(handshake_obj())), | |
| 332 | + Event::PmkidCaptured(pmkid_obj()), | |
| 333 | + Event::DeauthSent { | |
| 334 | + ap: MacAddr([1; 6]), | |
| 335 | + target: MacAddr::BROADCAST, | |
| 336 | + count: 64, | |
| 337 | + }, | |
| 338 | + Event::CrackProgress { done: 1000, hps: 1234.5 }, | |
| 339 | + Event::CrackFound { | |
| 340 | + password: "hunter2".into(), | |
| 341 | + }, | |
| 342 | + Event::CrackStopped { found: true }, | |
| 343 | + Event::CrackStopped { found: false }, | |
| 344 | + Event::Log("hello".into()), | |
| 345 | + Event::Error("boom".into()), | |
| 346 | + ]; | |
| 347 | + for ev in &cases { | |
| 348 | + let json = serde_json::to_string(ev).expect("serialize"); | |
| 349 | + let back: Event = serde_json::from_str(&json) | |
| 350 | + .unwrap_or_else(|e| panic!("deserialize {json}: {e}")); | |
| 351 | + assert_eq!(format!("{ev:?}"), format!("{back:?}")); | |
| 352 | + } | |
| 353 | + } | |
| 354 | + | |
| 355 | + #[test] | |
| 356 | + fn handshake_json_roundtrip_is_lossless() { | |
| 357 | + // PartialEq on the struct itself (not just Debug) — the Box in | |
| 358 | + // Event::HandshakeComplete must survive the wire. | |
| 359 | + let ev = Event::HandshakeComplete(Box::new(handshake_obj())); | |
| 360 | + let json = serde_json::to_string(&ev).expect("serialize"); | |
| 361 | + let Event::HandshakeComplete(back) = | |
| 362 | + serde_json::from_str(&json).expect("deserialize") | |
| 363 | + else { | |
| 364 | + panic!("variant changed shape: {json}"); | |
| 365 | + }; | |
| 366 | + assert_eq!(*back, handshake_obj()); | |
| 367 | + let pm = Event::PmkidCaptured(pmkid_obj()); | |
| 368 | + let json = serde_json::to_string(&pm).expect("serialize"); | |
| 369 | + let Event::PmkidCaptured(back) = serde_json::from_str(&json).expect("deserialize") | |
| 370 | + else { | |
| 371 | + panic!("variant changed shape: {json}"); | |
| 372 | + }; | |
| 373 | + assert_eq!(back, pmkid_obj()); | |
| 374 | + } | |
| 375 | + | |
| 376 | + #[test] | |
| 377 | + fn cmd_json_roundtrips() { | |
| 378 | + let cases: Vec<Cmd> = vec![ | |
| 379 | + Cmd::StartScan { | |
| 380 | + ifname: "wlp14s0".into(), | |
| 381 | + }, | |
| 382 | + Cmd::StopScan, | |
| 383 | + Cmd::Deauth { | |
| 384 | + ap: MacAddr([1; 6]), | |
| 385 | + target: MacAddr::BROADCAST, | |
| 386 | + channel: 6, | |
| 387 | + count: 16, | |
| 388 | + }, | |
| 389 | + Cmd::Pmkid { | |
| 390 | + ap: MacAddr([2; 6]), | |
| 391 | + channel: 36, | |
| 392 | + essid: "corp-wpa3".into(), | |
| 393 | + }, | |
| 394 | + Cmd::CaptureHs { | |
| 395 | + ap: MacAddr([3; 6]), | |
| 396 | + channel: 11, | |
| 397 | + essid: "coffeeshop".into(), | |
| 398 | + }, | |
| 399 | + Cmd::StopNetworkManager, | |
| 400 | + Cmd::Shutdown, | |
| 401 | + ]; | |
| 402 | + for cmd in &cases { | |
| 403 | + let json = serde_json::to_string(cmd).expect("serialize"); | |
| 404 | + let back: Cmd = serde_json::from_str(&json) | |
| 405 | + .unwrap_or_else(|e| panic!("deserialize {json}: {e}")); | |
| 406 | + assert_eq!(*cmd, back); | |
| 407 | + } | |
| 408 | + assert_eq!(roundtrip(&cases[0]), cases[0]); | |
| 409 | + } | |
| 410 | +} |
src/iface.rsmodified+2 -31
| @@ -191,7 +191,8 @@ pub fn stop_networkmanager() -> Result<()> { | ||
| 191 | 191 | .map(|_| ()) |
| 192 | 192 | } |
| 193 | 193 | |
| 194 | -/// True when `pkexec` (polkit) is available for GUI privilege elevation. | |
| 194 | +/// True when `pkexec` (polkit) is available to elevate the privileged | |
| 195 | +/// service child. | |
| 195 | 196 | pub fn pkexec_available() -> bool { |
| 196 | 197 | Command::new("pkexec") |
| 197 | 198 | .arg("--version") |
| @@ -202,36 +203,6 @@ pub fn pkexec_available() -> bool { | ||
| 202 | 203 | .unwrap_or(false) |
| 203 | 204 | } |
| 204 | 205 | |
| 205 | -/// Re-exec this binary via polkit (`pkexec`) as root, preserving the desktop | |
| 206 | -/// session environment so the elevated instance can open its own window. | |
| 207 | -/// | |
| 208 | -/// Blocks until `pkexec` returns. A dismissed/cancelled authentication | |
| 209 | -/// dialog surfaces as a non-zero exit status (126/127). MUST be called off | |
| 210 | -/// the UI thread. | |
| 211 | -pub fn relaunch_elevated(extra_args: &[&str]) -> Result<std::process::ExitStatus> { | |
| 212 | - let exe = std::env::current_exe().context("resolving current_exe for pkexec re-exec")?; | |
| 213 | - let mut cmd = Command::new("pkexec"); | |
| 214 | - cmd.arg("env"); | |
| 215 | - // GUI + session bus env the elevated child needs to open a window and | |
| 216 | - // talk to the user's services (GPU/DRI inherits via the session). | |
| 217 | - for var in [ | |
| 218 | - "WAYLAND_DISPLAY", | |
| 219 | - "XDG_RUNTIME_DIR", | |
| 220 | - "DISPLAY", | |
| 221 | - "DBUS_SESSION_BUS_ADDRESS", | |
| 222 | - "XAUTHORITY", | |
| 223 | - ] { | |
| 224 | - if let Ok(v) = std::env::var(var) { | |
| 225 | - cmd.arg(format!("{var}={v}")); | |
| 226 | - } | |
| 227 | - } | |
| 228 | - cmd.arg(exe).args(extra_args); | |
| 229 | - let status = cmd | |
| 230 | - .status() | |
| 231 | - .context("spawning pkexec — polkit not installed or no agent running")?; | |
| 232 | - Ok(status) | |
| 233 | -} | |
| 234 | - | |
| 235 | 206 | #[cfg(test)] |
| 236 | 207 | mod tests { |
| 237 | 208 | use super::*; |
src/main.rsmodified+12 -3
| @@ -1,4 +1,3 @@ | ||
| 1 | -mod backend; | |
| 2 | 1 | mod common; |
| 3 | 2 | mod crypto; |
| 4 | 3 | mod deauth; |
| @@ -10,6 +9,7 @@ mod pmkid; | ||
| 10 | 9 | mod radiotap; |
| 11 | 10 | mod rawsock; |
| 12 | 11 | mod scanner; |
| 12 | +mod service; | |
| 13 | 13 | mod ui; |
| 14 | 14 | mod wordlist; |
| 15 | 15 | |
| @@ -27,10 +27,19 @@ struct Cli { | ||
| 27 | 27 | /// Dev mode: fabricated events, no device access. Same as WIFILAB_MOCK=1. |
| 28 | 28 | #[arg(long)] |
| 29 | 29 | mock: bool, |
| 30 | + /// Internal: run as the privileged radio service (spawned by the UI, | |
| 31 | + /// directly or via pkexec). Never returns; JSON lines on stdin/stdout. | |
| 32 | + #[arg(long, hide = true)] | |
| 33 | + privileged_worker: bool, | |
| 30 | 34 | } |
| 31 | 35 | |
| 32 | 36 | fn main() { |
| 33 | 37 | let cli = Cli::parse(); |
| 38 | + // Privileged service path: no GUI, no extra args needed (pkexec strips | |
| 39 | + // the environment; everything the service needs comes over the pipe). | |
| 40 | + if cli.privileged_worker { | |
| 41 | + service::run_service(); // never returns | |
| 42 | + } | |
| 34 | 43 | let mock = cli.mock |
| 35 | 44 | || matches!( |
| 36 | 45 | std::env::var_os("WIFILAB_MOCK"), |
| @@ -49,9 +58,9 @@ fn main() { | ||
| 49 | 58 | if mock { |
| 50 | 59 | "fabricated events only" |
| 51 | 60 | } else if iface::is_root() { |
| 52 | - "monitor mode + injection available" | |
| 61 | + "monitor mode + injection available (service runs as child)" | |
| 53 | 62 | } else { |
| 54 | - "not root — use the \"Elevate via polkit\" button in the UI header" | |
| 63 | + "not root — polkit will ask for authentication when you start capture" | |
| 55 | 64 | } |
| 56 | 65 | ); |
| 57 | 66 | ui::run_app(cli.iface, cli.mock); |
src/scanner.rsmodified+76 -27
| @@ -7,19 +7,23 @@ use std::collections::BTreeMap; | ||
| 7 | 7 | use std::sync::Arc; |
| 8 | 8 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 9 | 9 | use std::time::{Duration, Instant}; |
| 10 | +// `Instant` is still used for dwell timing; timestamps going into shared | |
| 11 | +// types are `u64` millis (`crate::common::now_ms`) so they serialize. | |
| 10 | 12 | |
| 11 | 13 | use anyhow::{Context, Result}; |
| 12 | 14 | use crossbeam_channel::Sender; |
| 13 | 15 | |
| 14 | -use crate::common::{AccessPoint, ClientInfo, Event, HOP_CHANNELS_24, HOP_CHANNELS_5, MacAddr}; | |
| 16 | +use crate::common::{ | |
| 17 | + AccessPoint, ClientInfo, Event, HOP_CHANNELS_24, HOP_CHANNELS_5, MacAddr, now_ms, | |
| 18 | +}; | |
| 15 | 19 | use crate::radiotap::RxMeta; |
| 16 | 20 | use crate::rawsock::RawSocket; |
| 17 | 21 | use crate::{dot11, iface, radiotap}; |
| 18 | 22 | |
| 19 | -/// APs go stale (ApLost) after this much silence. | |
| 20 | -const AP_EXPIRE: Duration = Duration::from_secs(30); | |
| 21 | -/// Clients go stale after this much silence. | |
| 22 | -const CLIENT_EXPIRE: Duration = Duration::from_secs(60); | |
| 23 | +/// APs go stale (ApLost) after this much silence (ms — `last_seen_ms`). | |
| 24 | +const AP_EXPIRE_MS: u64 = 30_000; | |
| 25 | +/// Clients go stale after this much silence (ms). | |
| 26 | +const CLIENT_EXPIRE_MS: u64 = 60_000; | |
| 23 | 27 | |
| 24 | 28 | pub struct ScannerConfig { |
| 25 | 29 | pub ifname: String, |
| @@ -61,8 +65,9 @@ impl Scanner { | ||
| 61 | 65 | } |
| 62 | 66 | |
| 63 | 67 | /// Feed one received frame. Radiotap metadata in `meta`, 802.11 bytes in |
| 64 | - /// `frame` (already stripped), wall clock in `now` (test-injectable). | |
| 65 | - fn ingest(&mut self, meta: &RxMeta, frame: &[u8], now: Instant, tx: &Sender<Event>) { | |
| 68 | + /// `frame` (already stripped), clock in `now` ms since the process-local | |
| 69 | + /// epoch ([`common::now_ms`], test-injectable). | |
| 70 | + fn ingest(&mut self, meta: &RxMeta, frame: &[u8], now: u64, tx: &Sender<Event>) { | |
| 66 | 71 | // AP from beacon / probe-response. |
| 67 | 72 | if let Some(m) = dot11::parse_beacon_or_probe(frame) { |
| 68 | 73 | // Trust the DS-parameter IE; fall back to the radiotap carrier |
| @@ -92,7 +97,7 @@ impl Scanner { | ||
| 92 | 97 | changed = true; |
| 93 | 98 | } |
| 94 | 99 | ap.beacons += 1; |
| 95 | - ap.last_seen = now; | |
| 100 | + ap.last_seen_ms = now; | |
| 96 | 101 | if changed { |
| 97 | 102 | let _ = tx.send(Event::ApUpdated(ap.clone())); |
| 98 | 103 | } |
| @@ -108,7 +113,7 @@ impl Scanner { | ||
| 108 | 113 | security: m.security, |
| 109 | 114 | rssi_dbm: meta.rssi_dbm, |
| 110 | 115 | beacons: 1, |
| 111 | - last_seen: now, | |
| 116 | + last_seen_ms: now, | |
| 112 | 117 | }; |
| 113 | 118 | self.aps.insert(m.bssid, ap.clone()); |
| 114 | 119 | let _ = tx.send(Event::ApUpdated(ap)); |
| @@ -133,7 +138,7 @@ impl Scanner { | ||
| 133 | 138 | self.note_client(sta, Some(bssid), meta, now, tx); |
| 134 | 139 | } |
| 135 | 140 | if let Some(ap) = self.aps.get_mut(&bssid) { |
| 136 | - ap.last_seen = now; | |
| 141 | + ap.last_seen_ms = now; | |
| 137 | 142 | } |
| 138 | 143 | } |
| 139 | 144 | } |
| @@ -143,7 +148,7 @@ impl Scanner { | ||
| 143 | 148 | sta: MacAddr, |
| 144 | 149 | ap: Option<MacAddr>, |
| 145 | 150 | meta: &RxMeta, |
| 146 | - now: Instant, | |
| 151 | + now: u64, | |
| 147 | 152 | tx: &Sender<Event>, |
| 148 | 153 | ) { |
| 149 | 154 | match self.clients.get_mut(&sta) { |
| @@ -160,7 +165,7 @@ impl Scanner { | ||
| 160 | 165 | } |
| 161 | 166 | } |
| 162 | 167 | c.frames += 1; |
| 163 | - c.last_seen = now; | |
| 168 | + c.last_seen_ms = now; | |
| 164 | 169 | if changed { |
| 165 | 170 | let _ = tx.send(Event::ClientUpdated(c.clone())); |
| 166 | 171 | } |
| @@ -174,7 +179,7 @@ impl Scanner { | ||
| 174 | 179 | ap, |
| 175 | 180 | rssi_dbm: meta.rssi_dbm, |
| 176 | 181 | frames: 1, |
| 177 | - last_seen: now, | |
| 182 | + last_seen_ms: now, | |
| 178 | 183 | }; |
| 179 | 184 | self.clients.insert(sta, c.clone()); |
| 180 | 185 | let _ = tx.send(Event::ClientUpdated(c)); |
| @@ -184,11 +189,11 @@ impl Scanner { | ||
| 184 | 189 | |
| 185 | 190 | /// Expire silent entries, emitting ApLost / (clients just drop out — |
| 186 | 191 | /// contract has no ClientLost event; stale clients stop being updated). |
| 187 | - fn expire(&mut self, now: Instant, tx: &Sender<Event>) { | |
| 192 | + fn expire(&mut self, now: u64, tx: &Sender<Event>) { | |
| 188 | 193 | let gone: Vec<MacAddr> = self |
| 189 | 194 | .aps |
| 190 | 195 | .iter() |
| 191 | - .filter(|(_, ap)| now.duration_since(ap.last_seen) > AP_EXPIRE) | |
| 196 | + .filter(|(_, ap)| now.saturating_sub(ap.last_seen_ms) > AP_EXPIRE_MS) | |
| 192 | 197 | .map(|(b, _)| *b) |
| 193 | 198 | .collect(); |
| 194 | 199 | for b in gone { |
| @@ -196,10 +201,27 @@ impl Scanner { | ||
| 196 | 201 | let _ = tx.send(Event::ApLost(b)); |
| 197 | 202 | } |
| 198 | 203 | self.clients |
| 199 | - .retain(|_, c| now.duration_since(c.last_seen) <= CLIENT_EXPIRE); | |
| 204 | + .retain(|_, c| now.saturating_sub(c.last_seen_ms) <= CLIENT_EXPIRE_MS); | |
| 200 | 205 | } |
| 201 | 206 | } |
| 202 | 207 | |
| 208 | +/// Wall-clock counters for the 10 s `scan: …` diagnostic line — the evidence | |
| 209 | +/// channel distinguishing RX-silence from parser-drops when "only my own AP | |
| 210 | +/// shows up" is reported. | |
| 211 | +#[derive(Default)] | |
| 212 | +struct ScanStats { | |
| 213 | + /// Frames returned by `RawSocket::recv` (radiotap included, unparsed). | |
| 214 | + raw_frames_received: u64, | |
| 215 | + /// Frames whose radiotap header parsed (`radiotap::strip` returned Some). | |
| 216 | + radiotap_strip_ok: u64, | |
| 217 | + /// 802.11 payload parsed as SOME mgmt frame (beacon/probe-req/deauth / | |
| 218 | + /// probe-response family recognised by dot11). | |
| 219 | + mgmt_80211_parsed: u64, | |
| 220 | + /// Beacons/probe-responses that ingested an AP row (created or already | |
| 221 | + /// known — i.e. recognised AP-producing frames). | |
| 222 | + beacons_ap_ingested: u64, | |
| 223 | +} | |
| 224 | + | |
| 203 | 225 | /// Blocking channel-hop passive scan on an interface the caller already put |
| 204 | 226 | /// into monitor mode. Returns when `stop` flips true. |
| 205 | 227 | pub fn run(cfg: ScannerConfig, tx: Sender<Event>, stop: Arc<AtomicBool>) -> Result<()> { |
| @@ -226,9 +248,12 @@ pub fn run(cfg: ScannerConfig, tx: Sender<Event>, stop: Arc<AtomicBool>) -> Resu | ||
| 226 | 248 | let mut scanner = Scanner::new(cfg.rssi_floor); |
| 227 | 249 | let mut buf = vec![0u8; 4096]; |
| 228 | 250 | let mut ch_idx = 0usize; |
| 251 | + let mut stats = ScanStats::default(); | |
| 252 | + let mut last_stats_log = Instant::now(); | |
| 229 | 253 | |
| 230 | 254 | while !stop.load(Ordering::Relaxed) { |
| 231 | 255 | let ch = channels[ch_idx]; |
| 256 | + let cur_ch = ch; | |
| 232 | 257 | ch_idx = (ch_idx + 1) % channels.len(); |
| 233 | 258 | if let Err(e) = iface::set_channel(&cfg.ifname, ch) { |
| 234 | 259 | let _ = tx.send(Event::Log(format!( |
| @@ -241,8 +266,18 @@ pub fn run(cfg: ScannerConfig, tx: Sender<Event>, stop: Arc<AtomicBool>) -> Resu | ||
| 241 | 266 | loop { |
| 242 | 267 | match sock.recv(&mut buf) { |
| 243 | 268 | Ok(n) => { |
| 244 | - let now = Instant::now(); | |
| 269 | + stats.raw_frames_received += 1; | |
| 270 | + let now = now_ms(); | |
| 245 | 271 | if let Some((meta, frame)) = radiotap::strip(&buf[..n]) { |
| 272 | + stats.radiotap_strip_ok += 1; | |
| 273 | + if dot11::parse_beacon_or_probe(frame).is_some() { | |
| 274 | + stats.mgmt_80211_parsed += 1; | |
| 275 | + stats.beacons_ap_ingested += 1; | |
| 276 | + } else if dot11::parse_probe_req(frame).is_some() | |
| 277 | + || dot11::parse_deauth(frame).is_some() | |
| 278 | + { | |
| 279 | + stats.mgmt_80211_parsed += 1; | |
| 280 | + } | |
| 246 | 281 | scanner.ingest(&meta, frame, now, &tx); |
| 247 | 282 | } |
| 248 | 283 | } |
| @@ -266,7 +301,21 @@ pub fn run(cfg: ScannerConfig, tx: Sender<Event>, stop: Arc<AtomicBool>) -> Resu | ||
| 266 | 301 | } |
| 267 | 302 | } |
| 268 | 303 | |
| 269 | - scanner.expire(Instant::now(), &tx); | |
| 304 | + // 10 s wall-time diagnostic heartbeat: distinguishes RX-silence | |
| 305 | + // (rx==0) from radiotap/parser drops (rx>0 but beacons==0) when a | |
| 306 | + // report says "only my own AP shows up". | |
| 307 | + if last_stats_log.elapsed() >= Duration::from_secs(10) { | |
| 308 | + last_stats_log = Instant::now(); | |
| 309 | + let _ = tx.send(Event::Log(format!( | |
| 310 | + "scan: {} rx frames, {} beacons -> {} APs live (ch {})", | |
| 311 | + stats.raw_frames_received, | |
| 312 | + stats.beacons_ap_ingested, | |
| 313 | + scanner.aps.len(), | |
| 314 | + cur_ch | |
| 315 | + ))); | |
| 316 | + } | |
| 317 | + | |
| 318 | + scanner.expire(now_ms(), &tx); | |
| 270 | 319 | } |
| 271 | 320 | Ok(()) |
| 272 | 321 | } |
| @@ -346,7 +395,7 @@ mod tests { | ||
| 346 | 395 | fn beacon_attached_creates_ap_with_ssid_and_channel() { |
| 347 | 396 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 348 | 397 | let mut sc = Scanner::new(-85); |
| 349 | - let now = Instant::now(); | |
| 398 | + let now: u64 = 0; | |
| 350 | 399 | sc.ingest(&meta(-42, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); |
| 351 | 400 | match rx.try_recv() { |
| 352 | 401 | Ok(Event::ApUpdated(a)) => { |
| @@ -363,7 +412,7 @@ mod tests { | ||
| 363 | 412 | fn beacon_uses_freq_hint_when_no_ds_ie() { |
| 364 | 413 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 365 | 414 | let mut sc = Scanner::new(-85); |
| 366 | - let now = Instant::now(); | |
| 415 | + let now: u64 = 0; | |
| 367 | 416 | let mut f = beacon_frame(&ap(), "parafin", 6); |
| 368 | 417 | f.truncate(f.len() - 3); // drop DS IE |
| 369 | 418 | sc.ingest(&meta(-40, 2437), &f, now, &tx); |
| @@ -377,7 +426,7 @@ mod tests { | ||
| 377 | 426 | fn weak_beacon_not_created_but_update_accepted_later() { |
| 378 | 427 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 379 | 428 | let mut sc = Scanner::new(-85); |
| 380 | - let now = Instant::now(); | |
| 429 | + let now: u64 = 0; | |
| 381 | 430 | // -90 < floor: no event, no entry. |
| 382 | 431 | sc.ingest(&meta(-90, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); |
| 383 | 432 | assert!(rx.try_recv().is_err()); |
| @@ -394,7 +443,7 @@ mod tests { | ||
| 394 | 443 | fn rssi_improvement_emits_update_worsening_does_not() { |
| 395 | 444 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 396 | 445 | let mut sc = Scanner::new(-85); |
| 397 | - let now = Instant::now(); | |
| 446 | + let now: u64 = 0; | |
| 398 | 447 | sc.ingest(&meta(-70, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); |
| 399 | 448 | let _ = rx.try_recv(); // creation |
| 400 | 449 | sc.ingest(&meta(-75, 0), &beacon_frame(&ap(), "parafin", 6), now, &tx); |
| @@ -410,7 +459,7 @@ mod tests { | ||
| 410 | 459 | fn probe_req_creates_client_and_data_freshens() { |
| 411 | 460 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 412 | 461 | let mut sc = Scanner::new(-85); |
| 413 | - let now = Instant::now(); | |
| 462 | + let now: u64 = 0; | |
| 414 | 463 | sc.ingest(&meta(-55, 0), &probe_req_frame(&sta(), Some("parafin")), now, &tx); |
| 415 | 464 | match rx.try_recv() { |
| 416 | 465 | Ok(Event::ClientUpdated(c)) => { |
| @@ -431,7 +480,7 @@ mod tests { | ||
| 431 | 480 | fn multicast_ta_is_ignored() { |
| 432 | 481 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 433 | 482 | let mut sc = Scanner::new(-85); |
| 434 | - let now = Instant::now(); | |
| 483 | + let now: u64 = 0; | |
| 435 | 484 | let mcast = MacAddr([0x33, 0x33, 0, 0, 0, 1]); |
| 436 | 485 | sc.ingest(&meta(-40, 0), &probe_req_frame(&mcast, None), now, &tx); |
| 437 | 486 | assert!(rx.try_recv().is_err()); |
| @@ -442,14 +491,14 @@ mod tests { | ||
| 442 | 491 | fn aging_emits_ap_lost_and_drops_clients() { |
| 443 | 492 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 444 | 493 | let mut sc = Scanner::new(-85); |
| 445 | - let t0 = Instant::now(); | |
| 494 | + let t0: u64 = 1_000; | |
| 446 | 495 | sc.ingest(&meta(-40, 0), &beacon_frame(&ap(), "parafin", 6), t0, &tx); |
| 447 | 496 | sc.ingest(&meta(-40, 0), &probe_req_frame(&sta(), None), t0, &tx); |
| 448 | 497 | let _ = rx.try_recv(); |
| 449 | 498 | let _ = rx.try_recv(); |
| 450 | 499 | |
| 451 | 500 | // 31 s later: AP expired, client still alive. |
| 452 | - let t1 = t0 + Duration::from_secs(31); | |
| 501 | + let t1 = t0 + 31_000; | |
| 453 | 502 | sc.expire(t1, &tx); |
| 454 | 503 | match rx.try_recv() { |
| 455 | 504 | Ok(Event::ApLost(b)) => assert_eq!(b, ap()), |
| @@ -458,7 +507,7 @@ mod tests { | ||
| 458 | 507 | assert!(sc.clients.contains_key(&sta())); |
| 459 | 508 | |
| 460 | 509 | // 61 s: client gone too. |
| 461 | - sc.expire(t0 + Duration::from_secs(61), &tx); | |
| 510 | + sc.expire(t0 + 61_000, &tx); | |
| 462 | 511 | assert!(sc.clients.is_empty()); |
| 463 | 512 | } |
| 464 | 513 |
src/service.rsadded+697 -0
| @@ -0,0 +1,697 @@ | ||
| 1 | +//! Privileged service + UI-side client, replacing the old monolithic | |
| 2 | +//! `Backend`. | |
| 3 | +//! | |
| 4 | +//! Architecture: the UI process never needs root. All radio work runs in a | |
| 5 | +//! privileged SERVICE — the same binary re-spawned as a child with the | |
| 6 | +//! hidden flag `--privileged-worker` (directly when the UI is already root, | |
| 7 | +//! via `pkexec` otherwise). The two halves speak JSON lines: `Cmd` on the | |
| 8 | +//! child's stdin, `Event` on its stdout (stdout is reserved EXCLUSIVELY for | |
| 9 | +//! events; diagnostics go to stderr). | |
| 10 | +//! | |
| 11 | +//! Concurrency notes (service side): | |
| 12 | +//! - The scanner and any attack worker can coexist (deauth while capturing | |
| 13 | +//! is the whole point). Attack workers open their OWN [`RawSocket`] on | |
| 14 | +//! the monitor interface and set the channel themselves; concurrent | |
| 15 | +//! attacks should therefore target the SAME channel — this matches the | |
| 16 | +//! UI, which implies a single target. | |
| 17 | +//! - `to_monitor` may create a `<orig>mon` vif; the actual monitor ifname | |
| 18 | +//! is remembered and passed to [`iface::to_managed`] on stop/shutdown | |
| 19 | +//! (it deletes the vif or flips the interface back, as appropriate). | |
| 20 | + | |
| 21 | +use std::io::{BufRead, BufReader, Write}; | |
| 22 | +use std::path::PathBuf; | |
| 23 | +use std::process::{Child, ChildStdin, Command, Stdio}; | |
| 24 | +use std::sync::atomic::{AtomicBool, Ordering}; | |
| 25 | +use std::sync::{Arc, Mutex}; | |
| 26 | +use std::thread::JoinHandle; | |
| 27 | +use std::time::{Duration, Instant}; | |
| 28 | + | |
| 29 | +use anyhow::{Context, Result, bail}; | |
| 30 | +use crossbeam_channel::Sender; | |
| 31 | + | |
| 32 | +use crate::common::{Cmd, Event, MacAddr}; | |
| 33 | +use crate::crypto::CrackTarget; | |
| 34 | +use crate::gpu::{self, GpuCracker}; | |
| 35 | +use crate::rawsock::RawSocket; | |
| 36 | +use crate::{deauth, handshake, iface, pmkid, scanner, wordlist}; | |
| 37 | + | |
| 38 | +/// Exact banner the service prints on stdout before any event line. The | |
| 39 | +/// client prefix-matches lines against this while waiting (pkexec may | |
| 40 | +/// prepend its own chatter). | |
| 41 | +pub const READY_LINE: &str = "WIFILAB-SVC-READY"; | |
| 42 | + | |
| 43 | +/// How long the client waits for the service's READY banner (the polkit | |
| 44 | +/// dialog can block on a slow human). | |
| 45 | +const READY_TIMEOUT: Duration = Duration::from_secs(60); | |
| 46 | + | |
| 47 | +fn send(tx: &Sender<Event>, ev: Event) { | |
| 48 | + let _ = tx.send(ev); | |
| 49 | +} | |
| 50 | + | |
| 51 | +fn log(tx: &Sender<Event>, msg: impl Into<String>) { | |
| 52 | + send(tx, Event::Log(msg.into())); | |
| 53 | +} | |
| 54 | + | |
| 55 | +fn log_err(tx: &Sender<Event>, msg: impl Into<String>) { | |
| 56 | + send(tx, Event::Error(msg.into())); | |
| 57 | +} | |
| 58 | + | |
| 59 | +// --------------------------------------------------------------------------- | |
| 60 | +// Privileged half — runs as the `--privileged-worker` child process. | |
| 61 | +// --------------------------------------------------------------------------- | |
| 62 | + | |
| 63 | +/// Radio-side state owned by the service process. Mirrors the old | |
| 64 | +/// `Backend` minus the cracker (which moved into the UI process). | |
| 65 | +struct RadioService { | |
| 66 | + stop: Arc<AtomicBool>, | |
| 67 | + handles: Mutex<Vec<JoinHandle<()>>>, | |
| 68 | + /// Name of the interface currently in monitor mode (`None` if the | |
| 69 | + /// mode switch failed at StartScan — nothing to restore then). | |
| 70 | + mon_ifname: Option<String>, | |
| 71 | + /// Interface the UI asked for; restored to managed mode on stop/ | |
| 72 | + /// shutdown when it differs from `mon_ifname`. | |
| 73 | + orig_ifname: Option<String>, | |
| 74 | + /// Event pipe: the forwarder thread owns the receiving end and | |
| 75 | + /// serializes one JSON line per event onto stdout. | |
| 76 | + tx: Sender<Event>, | |
| 77 | +} | |
| 78 | + | |
| 79 | +impl RadioService { | |
| 80 | + fn new(tx: Sender<Event>) -> Self { | |
| 81 | + RadioService { | |
| 82 | + stop: Arc::new(AtomicBool::new(false)), | |
| 83 | + handles: Mutex::new(Vec::new()), | |
| 84 | + mon_ifname: None, | |
| 85 | + orig_ifname: None, | |
| 86 | + tx, | |
| 87 | + } | |
| 88 | + } | |
| 89 | + | |
| 90 | + fn mon(&self) -> Option<String> { | |
| 91 | + self.mon_ifname | |
| 92 | + .clone() | |
| 93 | + .or_else(|| self.orig_ifname.clone()) | |
| 94 | + } | |
| 95 | + | |
| 96 | + /// Switch `ifname` to monitor mode and start the channel-hopping | |
| 97 | + /// scanner (full 2.4 + 5 GHz hop list). On any failure an | |
| 98 | + /// [`Event::Error`] is emitted, the interface is put back into managed | |
| 99 | + /// mode (best effort). A previous scan session must be stopped first | |
| 100 | + /// (or have failed); the stop flag is always fresh here. | |
| 101 | + fn start_scan(&mut self, ifname: &str) { | |
| 102 | + self.stop = Arc::new(AtomicBool::new(false)); | |
| 103 | + self.mon_ifname = None; | |
| 104 | + self.orig_ifname = Some(ifname.to_string()); | |
| 105 | + | |
| 106 | + let mon_ifname = match iface::to_monitor(ifname) { | |
| 107 | + Ok(name) => name, | |
| 108 | + Err(e) => { | |
| 109 | + log_err(&self.tx, format!("monitor mode on {ifname} failed: {e:#}")); | |
| 110 | + // Best effort: leave the box the way we found it. | |
| 111 | + let _ = iface::to_managed(ifname); | |
| 112 | + self.orig_ifname = None; | |
| 113 | + return; | |
| 114 | + } | |
| 115 | + }; | |
| 116 | + self.mon_ifname = Some(mon_ifname.clone()); | |
| 117 | + log(&self.tx, format!("monitor mode up on {mon_ifname} (was {ifname})")); | |
| 118 | + | |
| 119 | + let cfg = scanner::ScannerConfig { | |
| 120 | + ifname: mon_ifname, | |
| 121 | + channels: Vec::new(), // empty = full hop list | |
| 122 | + dwell_ms: 100, | |
| 123 | + rssi_floor: -95, | |
| 124 | + }; | |
| 125 | + let stop = self.stop.clone(); | |
| 126 | + let tx = self.tx.clone(); | |
| 127 | + match std::thread::Builder::new() | |
| 128 | + .name("wifilab-scanner".into()) | |
| 129 | + .spawn(move || { | |
| 130 | + if let Err(e) = scanner::run(cfg, tx.clone(), stop) { | |
| 131 | + log_err(&tx, format!("scanner stopped: {e:#}")); | |
| 132 | + } | |
| 133 | + }) { | |
| 134 | + Ok(h) => self.handles.lock().expect("handles poisoned").push(h), | |
| 135 | + Err(e) => { | |
| 136 | + log_err(&self.tx, format!("scanner: spawn failed: {e}")); | |
| 137 | + // Leave the UI consistent: nothing runs but the interface | |
| 138 | + // is in monitor mode — flip it back. | |
| 139 | + if let Some(mon) = self.mon_ifname.take() { | |
| 140 | + let _ = iface::to_managed(&mon); | |
| 141 | + } | |
| 142 | + } | |
| 143 | + } | |
| 144 | + } | |
| 145 | + | |
| 146 | + /// Stop the scanner + all attack workers and restore managed mode. | |
| 147 | + /// The service stays alive for a subsequent StartScan. Idempotent. | |
| 148 | + fn stop_scan(&mut self) { | |
| 149 | + self.stop.store(true, Ordering::Release); | |
| 150 | + let handles = std::mem::take(&mut *self.handles.lock().expect("handles poisoned")); | |
| 151 | + for h in handles { | |
| 152 | + let _ = h.join(); | |
| 153 | + } | |
| 154 | + if let Some(mon) = self.mon_ifname.take() { | |
| 155 | + if let Err(e) = iface::to_managed(&mon) { | |
| 156 | + eprintln!("wifilab-svc: to_managed({mon}) failed: {e:#}"); | |
| 157 | + } | |
| 158 | + } | |
| 159 | + self.orig_ifname = None; | |
| 160 | + } | |
| 161 | + | |
| 162 | + /// Register a worker thread; on spawn failure the error is reported on | |
| 163 | + /// the event pipe. | |
| 164 | + fn spawn( | |
| 165 | + &self, | |
| 166 | + name: &str, | |
| 167 | + what: &str, | |
| 168 | + f: impl FnOnce(Sender<Event>) + Send + 'static, | |
| 169 | + ) -> bool { | |
| 170 | + let worker_tx = self.tx.clone(); | |
| 171 | + match std::thread::Builder::new() | |
| 172 | + .name(name.to_string()) | |
| 173 | + .spawn(move || f(worker_tx)) | |
| 174 | + { | |
| 175 | + Ok(h) => { | |
| 176 | + self.handles.lock().expect("handles poisoned").push(h); | |
| 177 | + true | |
| 178 | + } | |
| 179 | + Err(e) => { | |
| 180 | + log_err(&self.tx, format!("{what}: spawn failed: {e}")); | |
| 181 | + false | |
| 182 | + } | |
| 183 | + } | |
| 184 | + } | |
| 185 | + | |
| 186 | + /// Deauth worker: opens its own raw socket on the monitor interface, | |
| 187 | + /// tunes it to `channel`, then blasts `count` deauth rounds at | |
| 188 | + /// `target` (broadcast allowed). Emits DeauthSent progress (via | |
| 189 | + /// [`deauth::blast`]) and a final summary log. | |
| 190 | + fn deauth(&self, ap: MacAddr, target: MacAddr, channel: u8, count: u32) { | |
| 191 | + let Some(mon) = self.mon() else { | |
| 192 | + log_err(&self.tx, "deauth: no scan session — StartScan first"); | |
| 193 | + return; | |
| 194 | + }; | |
| 195 | + self.spawn("wifilab-deauth", "deauth", move |tx| { | |
| 196 | + let sock = match RawSocket::open(&mon) { | |
| 197 | + Ok(s) => s, | |
| 198 | + Err(e) => { | |
| 199 | + log_err(&tx, format!("deauth: raw socket on {mon} failed: {e}")); | |
| 200 | + return; | |
| 201 | + } | |
| 202 | + }; | |
| 203 | + if let Err(e) = iface::set_channel(&mon, channel) { | |
| 204 | + // Not fatal: the capture worker is usually already parked | |
| 205 | + // on the right channel. | |
| 206 | + log(&tx, format!("deauth: set_channel {channel} failed: {e:#}")); | |
| 207 | + } | |
| 208 | + match deauth::blast(&sock, &ap, &target, count, &tx) { | |
| 209 | + Ok(sent) => log(&tx, format!("deauth: done, {sent} frames → {target}")), | |
| 210 | + Err(e) => log_err(&tx, format!("deauth: {e:#}")), | |
| 211 | + } | |
| 212 | + }); | |
| 213 | + } | |
| 214 | + | |
| 215 | + /// PMKID grab worker: single client-less auth+assoc attempt against | |
| 216 | + /// `ap`, impersonating the monitor interface's own MAC. Emits | |
| 217 | + /// PmkidCaptured or a "no PMKID" log line. | |
| 218 | + fn pmkid(&self, ap: MacAddr, channel: u8, essid: String) { | |
| 219 | + let Some(mon) = self.mon() else { | |
| 220 | + log_err(&self.tx, "pmkid: no scan session — StartScan first"); | |
| 221 | + return; | |
| 222 | + }; | |
| 223 | + self.spawn("wifilab-pmkid", "pmkid", move |tx| { | |
| 224 | + let sta = match iface::mac_of(&mon) { | |
| 225 | + Ok(m) => m, | |
| 226 | + Err(e) => { | |
| 227 | + log_err(&tx, format!("pmkid: own MAC of {mon}: {e:#}")); | |
| 228 | + return; | |
| 229 | + } | |
| 230 | + }; | |
| 231 | + let sock = match RawSocket::open(&mon) { | |
| 232 | + Ok(s) => s, | |
| 233 | + Err(e) => { | |
| 234 | + log_err(&tx, format!("pmkid: raw socket on {mon} failed: {e}")); | |
| 235 | + return; | |
| 236 | + } | |
| 237 | + }; | |
| 238 | + if let Err(e) = iface::set_channel(&mon, channel) { | |
| 239 | + log(&tx, format!("pmkid: set_channel {channel} failed: {e:#}")); | |
| 240 | + } | |
| 241 | + match pmkid::grab(&sock, &ap, &sta, &essid, &tx) { | |
| 242 | + Ok(Some(cap)) => send(&tx, Event::PmkidCaptured(cap)), | |
| 243 | + Ok(None) => log(&tx, format!("pmkid: no PMKID volunteered by {ap}")), | |
| 244 | + Err(e) => log_err(&tx, format!("pmkid: {e:#}")), | |
| 245 | + } | |
| 246 | + }); | |
| 247 | + } | |
| 248 | + | |
| 249 | + /// 4-way capture worker: tune the monitor interface to `channel`, open | |
| 250 | + /// a raw socket, and run [`handshake::capture_loop`] (stop flag | |
| 251 | + /// checked every 250 ms frame poll). [`Event::HandshakeComplete`] is | |
| 252 | + /// emitted from inside the loop when a crackable pair completes. | |
| 253 | + fn capture_hs(&self, ap: MacAddr, channel: u8, essid: String) { | |
| 254 | + let Some(mon) = self.mon() else { | |
| 255 | + log_err(&self.tx, "handshake: no scan session — StartScan first"); | |
| 256 | + return; | |
| 257 | + }; | |
| 258 | + let stop = self.stop.clone(); | |
| 259 | + self.spawn("wifilab-capture", "handshake", move |tx| { | |
| 260 | + if let Err(e) = iface::set_channel(&mon, channel) { | |
| 261 | + log_err(&tx, format!("handshake: set_channel {channel} on {mon}: {e:#}")); | |
| 262 | + return; | |
| 263 | + } | |
| 264 | + let sock = match RawSocket::open(&mon) { | |
| 265 | + Ok(s) => s, | |
| 266 | + Err(e) => { | |
| 267 | + log_err(&tx, format!("handshake: raw socket on {mon} failed: {e}")); | |
| 268 | + return; | |
| 269 | + } | |
| 270 | + }; | |
| 271 | + match handshake::capture_loop(&sock, ap, &essid, &tx, &stop) { | |
| 272 | + Ok(true) => {} | |
| 273 | + Ok(false) => log(&tx, format!("handshake: capture ended without a pair ({ap})")), | |
| 274 | + Err(e) => log_err(&tx, format!("handshake: {e:#}")), | |
| 275 | + } | |
| 276 | + }); | |
| 277 | + } | |
| 278 | + | |
| 279 | + fn stop_networkmanager(&self) { | |
| 280 | + match iface::stop_networkmanager() { | |
| 281 | + Ok(()) => log(&self.tx, "nm: stopped"), | |
| 282 | + Err(e) => log(&self.tx, format!("nm: stop failed: {e:#}")), | |
| 283 | + } | |
| 284 | + } | |
| 285 | +} | |
| 286 | + | |
| 287 | +/// Service entry point: never returns (process exits from inside). | |
| 288 | +/// | |
| 289 | +/// stdout carries exactly one READY banner and then one JSON-serialized | |
| 290 | +/// [`Event`] per line — nothing else. stderr is free for diagnostics. | |
| 291 | +pub fn run_service() -> ! { | |
| 292 | + let code = service_main(); | |
| 293 | + std::process::exit(code); | |
| 294 | +} | |
| 295 | + | |
| 296 | +fn service_main() -> i32 { | |
| 297 | + let stdout = std::io::stdout(); | |
| 298 | + // Buffered writer handed to the forwarder thread; the banner uses the | |
| 299 | + // same lock discipline by printing through a dedicated line with an | |
| 300 | + // explicit flush BEFORE the forwarder starts. | |
| 301 | + { | |
| 302 | + let mut out = stdout.lock(); | |
| 303 | + let _ = out.write_all(READY_LINE.as_bytes()); | |
| 304 | + let _ = out.write_all(b"\n"); | |
| 305 | + let _ = out.flush(); | |
| 306 | + } | |
| 307 | + | |
| 308 | + // Single writer to stdout: every event — scanner, attacks, errors, | |
| 309 | + // logs — funnels through this channel and gets serialized by ONE | |
| 310 | + // forwarder thread, so lines never interleave. | |
| 311 | + let (tx, rx) = crossbeam_channel::unbounded::<Event>(); | |
| 312 | + let forwarder = std::thread::Builder::new() | |
| 313 | + .name("wifilab-svc-fwd".into()) | |
| 314 | + .spawn(move || { | |
| 315 | + let stdout = std::io::stdout(); | |
| 316 | + let mut out = std::io::BufWriter::new(stdout.lock()); | |
| 317 | + // Bounded drain: when the channel closes (main loop out of | |
| 318 | + // scope) we finish queued events and exit. | |
| 319 | + while let Ok(ev) = rx.recv() { | |
| 320 | + match serde_json::to_string(&ev) { | |
| 321 | + Ok(line) => { | |
| 322 | + if out.write_all(line.as_bytes()).is_err() | |
| 323 | + || out.write_all(b"\n").is_err() | |
| 324 | + || out.flush().is_err() | |
| 325 | + { | |
| 326 | + return; // parent gone | |
| 327 | + } | |
| 328 | + } | |
| 329 | + Err(e) => eprintln!("wifilab-svc: event serialization failed: {e}"), | |
| 330 | + } | |
| 331 | + } | |
| 332 | + }) | |
| 333 | + .expect("spawning service forwarder thread"); | |
| 334 | + | |
| 335 | + let mut radio = RadioService::new(tx.clone()); | |
| 336 | + let stdin = std::io::stdin(); | |
| 337 | + let mut lines = BufReader::new(stdin.lock()).lines(); | |
| 338 | + loop { | |
| 339 | + let line = match lines.next() { | |
| 340 | + Some(Ok(l)) => l, | |
| 341 | + Some(Err(e)) => { | |
| 342 | + eprintln!("wifilab-svc: stdin read failed: {e}"); | |
| 343 | + break; // treat as EOF | |
| 344 | + } | |
| 345 | + None => break, // EOF: parent closed the pipe | |
| 346 | + }; | |
| 347 | + if line.trim().is_empty() { | |
| 348 | + continue; | |
| 349 | + } | |
| 350 | + let cmd: Cmd = match serde_json::from_str(&line) { | |
| 351 | + Ok(c) => c, | |
| 352 | + Err(e) => { | |
| 353 | + log_err(&tx, format!("service: bad command line ({}): {e}", &line[..line.len().min(80)])); | |
| 354 | + continue; | |
| 355 | + } | |
| 356 | + }; | |
| 357 | + match cmd { | |
| 358 | + Cmd::StartScan { ifname } => radio.start_scan(&ifname), | |
| 359 | + Cmd::StopScan => radio.stop_scan(), | |
| 360 | + Cmd::Deauth { | |
| 361 | + ap, | |
| 362 | + target, | |
| 363 | + channel, | |
| 364 | + count, | |
| 365 | + } => radio.deauth(ap, target, channel, count), | |
| 366 | + Cmd::Pmkid { ap, channel, essid } => radio.pmkid(ap, channel, essid), | |
| 367 | + Cmd::CaptureHs { ap, channel, essid } => radio.capture_hs(ap, channel, essid), | |
| 368 | + Cmd::StopNetworkManager => radio.stop_networkmanager(), | |
| 369 | + Cmd::Shutdown => break, | |
| 370 | + } | |
| 371 | + } | |
| 372 | + | |
| 373 | + // Stop everything, restore the interface, drain the event pipe so the | |
| 374 | + // last error lines still reach the UI, and exit. | |
| 375 | + radio.stop_scan(); | |
| 376 | + drop(radio); | |
| 377 | + drop(tx); | |
| 378 | + let _ = forwarder.join(); | |
| 379 | + 0 | |
| 380 | +} | |
| 381 | + | |
| 382 | +// --------------------------------------------------------------------------- | |
| 383 | +// UI-side half — owns the child process and the crack thread. | |
| 384 | +// --------------------------------------------------------------------------- | |
| 385 | + | |
| 386 | +/// Client handle for the privileged service. Lives across scan sessions: | |
| 387 | +/// "Stop capture" only sends [`Cmd::StopScan`]; the child stays up for | |
| 388 | +/// later scans and for `StopNetworkManager`. The GPU cracker runs as a | |
| 389 | +/// plain thread in the UI process (no privilege needed) and is tracked | |
| 390 | +/// here for its stop flag only. | |
| 391 | +pub struct ServiceClient { | |
| 392 | + stdin: Arc<Mutex<ChildStdin>>, | |
| 393 | + reader: Option<JoinHandle<()>>, | |
| 394 | + child: Child, | |
| 395 | + /// Stop flag of the currently running crack job (if any). Radio | |
| 396 | + /// workers live in the service; this is a pure UI-process thread. | |
| 397 | + pub crack_stop: Mutex<Option<Arc<AtomicBool>>>, | |
| 398 | +} | |
| 399 | + | |
| 400 | +/// Child argv: same binary, hidden worker flag. Root → spawn directly; | |
| 401 | +/// non-root → wrap in pkexec (polkit prompt appears once per session). | |
| 402 | +fn spawn_service_child() -> Result<Child> { | |
| 403 | + let exe = std::env::current_exe().context("resolving current_exe for service spawn")?; | |
| 404 | + if iface::is_root() { | |
| 405 | + Command::new(exe) | |
| 406 | + .arg("--privileged-worker") | |
| 407 | + .stdin(Stdio::piped()) | |
| 408 | + .stdout(Stdio::piped()) | |
| 409 | + .stderr(Stdio::inherit()) | |
| 410 | + .spawn() | |
| 411 | + .context("spawning privileged service") | |
| 412 | + } else { | |
| 413 | + if !iface::pkexec_available() { | |
| 414 | + bail!("pkexec not available — cannot elevate the privileged service"); | |
| 415 | + } | |
| 416 | + Command::new("pkexec") | |
| 417 | + .arg(exe) | |
| 418 | + .arg("--privileged-worker") | |
| 419 | + .stdin(Stdio::piped()) | |
| 420 | + .stdout(Stdio::piped()) | |
| 421 | + .stderr(Stdio::inherit()) | |
| 422 | + .spawn() | |
| 423 | + .context("spawning pkexec — polkit not installed or no agent running") | |
| 424 | + } | |
| 425 | +} | |
| 426 | + | |
| 427 | +impl ServiceClient { | |
| 428 | + /// Spawn the privileged service and start the channel-hopping scanner | |
| 429 | + /// on `ifname`. All service events land on `tx`. A pkexec refusal / | |
| 430 | + /// missing READY / immediate child death surfaces as `Err` (never a | |
| 431 | + /// panic); later events flow asynchronously. | |
| 432 | + pub fn start(ifname: &str, tx: Sender<Event>) -> Result<Self> { | |
| 433 | + let mut child = spawn_service_child()?; | |
| 434 | + let stdin = child | |
| 435 | + .stdin | |
| 436 | + .take() | |
| 437 | + .context("service child stdin not piped")?; | |
| 438 | + let stdout = child | |
| 439 | + .stdout | |
| 440 | + .take() | |
| 441 | + .context("service child stdout not piped")?; | |
| 442 | + | |
| 443 | + let (ready_tx, ready_rx) = crossbeam_channel::bounded::<Result<()>>(1); | |
| 444 | + let reader = std::thread::Builder::new() | |
| 445 | + .name("wifilab-svc-reader".into()) | |
| 446 | + .spawn(move || { | |
| 447 | + let mut lines = BufReader::new(stdout).lines(); | |
| 448 | + let mut ready = false; | |
| 449 | + let deadline = Instant::now() + READY_TIMEOUT; | |
| 450 | + // READY phase: prefix-match so pkexec chatter on stdout | |
| 451 | + // can't trip us; hard cap at READY_TIMEOUT. | |
| 452 | + while Instant::now() < deadline { | |
| 453 | + match lines.next() { | |
| 454 | + Some(Ok(line)) if !ready => { | |
| 455 | + if line.starts_with(READY_LINE) { | |
| 456 | + ready = true; | |
| 457 | + let _ = ready_tx.try_send(Ok(())); | |
| 458 | + break; | |
| 459 | + } | |
| 460 | + // Pre-ready garbage (pkexec notes etc.): ignore. | |
| 461 | + } | |
| 462 | + Some(Ok(_)) => break, | |
| 463 | + Some(Err(e)) => { | |
| 464 | + let _ = ready_tx.try_send(Err(anyhow::anyhow!( | |
| 465 | + "service stdout read failed: {e}" | |
| 466 | + ))); | |
| 467 | + return; | |
| 468 | + } | |
| 469 | + None => { | |
| 470 | + let _ = ready_tx.try_send(Err(anyhow::anyhow!( | |
| 471 | + "service exited before READY (polkit dismissed or spawn failed)" | |
| 472 | + ))); | |
| 473 | + return; | |
| 474 | + } | |
| 475 | + } | |
| 476 | + } | |
| 477 | + if !ready { | |
| 478 | + let _ = ready_tx.try_send(Err(anyhow::anyhow!( | |
| 479 | + "service READY banner not seen within {} s", | |
| 480 | + READY_TIMEOUT.as_secs() | |
| 481 | + ))); | |
| 482 | + return; | |
| 483 | + } | |
| 484 | + // Event phase: one JSON event per stdout line, until EOF. | |
| 485 | + for line in lines { | |
| 486 | + let line = match line { | |
| 487 | + Ok(l) => l, | |
| 488 | + Err(e) => { | |
| 489 | + send(&tx, Event::Error(format!("service stdout read failed: {e}"))); | |
| 490 | + break; | |
| 491 | + } | |
| 492 | + }; | |
| 493 | + if line.trim().is_empty() { | |
| 494 | + continue; | |
| 495 | + } | |
| 496 | + match serde_json::from_str::<Event>(&line) { | |
| 497 | + Ok(ev) => send(&tx, ev), | |
| 498 | + Err(e) => send( | |
| 499 | + &tx, | |
| 500 | + Event::Error(format!( | |
| 501 | + "service: bad event line ({}): {e}", | |
| 502 | + &line[..line.len().min(80)] | |
| 503 | + )), | |
| 504 | + ), | |
| 505 | + } | |
| 506 | + } | |
| 507 | + // EOF: child died. UI uses this pair to un-flip flags. | |
| 508 | + send(&tx, Event::Log("service exited".to_string())); | |
| 509 | + send(&tx, Event::Error("service terminated".to_string())); | |
| 510 | + }) | |
| 511 | + .context("spawning service reader thread")?; | |
| 512 | + | |
| 513 | + // Wait for READY here (bounded), so spawn/config failures surface | |
| 514 | + // synchronously instead of as a late async surprise. | |
| 515 | + match ready_rx.recv_timeout(READY_TIMEOUT) { | |
| 516 | + Ok(Ok(())) => {} | |
| 517 | + Ok(Err(e)) => { | |
| 518 | + let _ = child.kill(); | |
| 519 | + let _ = child.wait(); | |
| 520 | + let _ = reader.join(); | |
| 521 | + return Err(e); | |
| 522 | + } | |
| 523 | + Err(_) => { | |
| 524 | + let _ = child.kill(); | |
| 525 | + let _ = child.wait(); | |
| 526 | + let _ = reader.join(); | |
| 527 | + bail!("service READY banner wait timed out"); | |
| 528 | + } | |
| 529 | + } | |
| 530 | + | |
| 531 | + let client = ServiceClient { | |
| 532 | + stdin: Arc::new(Mutex::new(stdin)), | |
| 533 | + reader: Some(reader), | |
| 534 | + child, | |
| 535 | + crack_stop: Mutex::new(None), | |
| 536 | + }; | |
| 537 | + client.cmd(&Cmd::StartScan { | |
| 538 | + ifname: ifname.to_string(), | |
| 539 | + }); | |
| 540 | + Ok(client) | |
| 541 | + } | |
| 542 | + | |
| 543 | + /// Ship one command line to the service. BrokenPipe (service already | |
| 544 | + /// dead) is ignored — the reader thread reported the death. | |
| 545 | + pub fn cmd(&self, c: &Cmd) { | |
| 546 | + let Ok(line) = serde_json::to_string(c) else { | |
| 547 | + return; | |
| 548 | + }; | |
| 549 | + let mut guard = self.stdin.lock().expect("service stdin poisoned"); | |
| 550 | + let _ = guard.write_all(line.as_bytes()); | |
| 551 | + let _ = guard.write_all(b"\n"); | |
| 552 | + let _ = guard.flush(); | |
| 553 | + } | |
| 554 | + | |
| 555 | + /// Stop the scan session (scanner + attack workers) but KEEP the | |
| 556 | + /// service alive for later scans and for `StopNetworkManager`. | |
| 557 | + pub fn stop_scan(&self) { | |
| 558 | + self.cmd(&Cmd::StopScan); | |
| 559 | + } | |
| 560 | + | |
| 561 | + /// Ask the running crack job (if any) to stop. UI-side flag only — | |
| 562 | + /// the service is not involved in cracking. | |
| 563 | + pub fn request_crack_stop(&self) { | |
| 564 | + if let Some(flag) = &*self.crack_stop.lock().expect("crack_stop poisoned") { | |
| 565 | + flag.store(true, Ordering::Relaxed); | |
| 566 | + } | |
| 567 | + } | |
| 568 | + | |
| 569 | + /// Crack worker: stream `wordlist` through the GPU cracker (CPU | |
| 570 | + /// fallback when no adapter) against `target` — as a plain thread in | |
| 571 | + /// the UI process (GPU + wordlist need no root). Emits CrackProgress, | |
| 572 | + /// then exactly one terminator: CrackFound + CrackStopped{found:true} | |
| 573 | + /// on success, CrackStopped{found:false} on stop or wordlist | |
| 574 | + /// exhaustion. | |
| 575 | + pub fn spawn_crack( | |
| 576 | + &self, | |
| 577 | + target_desc: String, | |
| 578 | + target: CrackTarget, | |
| 579 | + wordlist: PathBuf, | |
| 580 | + tx: Sender<Event>, | |
| 581 | + ) { | |
| 582 | + let stop = Arc::new(AtomicBool::new(false)); | |
| 583 | + *self.crack_stop.lock().expect("crack_stop poisoned") = Some(stop.clone()); | |
| 584 | + let err_tx = tx.clone(); | |
| 585 | + let result = std::thread::Builder::new() | |
| 586 | + .name("wifilab-crack".into()) | |
| 587 | + .spawn(move || { | |
| 588 | + let words = match wordlist::open(&wordlist) { | |
| 589 | + Ok(w) => w, | |
| 590 | + Err(e) => { | |
| 591 | + log_err(&tx, format!("cracker: {e:#}")); | |
| 592 | + send(&tx, Event::CrackStopped { found: false }); | |
| 593 | + return; | |
| 594 | + } | |
| 595 | + }; | |
| 596 | + let mut words = words; | |
| 597 | + let mut progress = { | |
| 598 | + let tx = tx.clone(); | |
| 599 | + move |done: u64, hps: f64| send(&tx, Event::CrackProgress { done, hps }) | |
| 600 | + }; | |
| 601 | + let found = match GpuCracker::try_new() { | |
| 602 | + Some(g) => { | |
| 603 | + log( | |
| 604 | + &tx, | |
| 605 | + format!( | |
| 606 | + "cracker: GPU backend: {} — cracking {target_desc}", | |
| 607 | + g.device_name() | |
| 608 | + ), | |
| 609 | + ); | |
| 610 | + g.crack(&target, &mut words, &mut progress, &stop) | |
| 611 | + } | |
| 612 | + None => { | |
| 613 | + log( | |
| 614 | + &tx, | |
| 615 | + format!( | |
| 616 | + "cracker: no GPU adapter, CPU fallback — cracking {target_desc}" | |
| 617 | + ), | |
| 618 | + ); | |
| 619 | + gpu::cpu_crack(&target, &mut words, &mut progress, &stop) | |
| 620 | + } | |
| 621 | + }; | |
| 622 | + match found { | |
| 623 | + Some(password) => { | |
| 624 | + log(&tx, format!("cracker: PASSWORD found: {password}")); | |
| 625 | + send(&tx, Event::CrackFound { password }); | |
| 626 | + send(&tx, Event::CrackStopped { found: true }); | |
| 627 | + } | |
| 628 | + None => { | |
| 629 | + if stop.load(Ordering::Relaxed) { | |
| 630 | + log(&tx, "cracker: stopped"); | |
| 631 | + } else { | |
| 632 | + log(&tx, "cracker: wordlist exhausted, password not found"); | |
| 633 | + } | |
| 634 | + send(&tx, Event::CrackStopped { found: false }); | |
| 635 | + } | |
| 636 | + } | |
| 637 | + }); | |
| 638 | + if let Err(e) = result { | |
| 639 | + send(&err_tx, Event::Error(format!("cracker: spawn failed: {e}"))); | |
| 640 | + send(&err_tx, Event::CrackStopped { found: false }); | |
| 641 | + } | |
| 642 | + } | |
| 643 | + | |
| 644 | + /// Tear down: tell the service to stop everything + exit, give it a | |
| 645 | + /// grace period, then kill and reap. Also stops any UI-side crack job | |
| 646 | + /// and joins the reader thread. | |
| 647 | + pub fn shutdown(mut self) { | |
| 648 | + self.request_crack_stop(); | |
| 649 | + self.cmd(&Cmd::Shutdown); | |
| 650 | + // 2 s grace for the service to restore managed mode + exit. | |
| 651 | + let deadline = Instant::now() + Duration::from_secs(2); | |
| 652 | + loop { | |
| 653 | + match self.child.try_wait() { | |
| 654 | + Ok(Some(_)) => break, | |
| 655 | + Ok(None) if Instant::now() < deadline => { | |
| 656 | + std::thread::sleep(Duration::from_millis(25)); | |
| 657 | + } | |
| 658 | + Ok(None) => { | |
| 659 | + let _ = self.child.kill(); | |
| 660 | + break; | |
| 661 | + } | |
| 662 | + Err(_) => break, | |
| 663 | + } | |
| 664 | + } | |
| 665 | + let _ = self.child.wait(); | |
| 666 | + if let Some(reader) = self.reader.take() { | |
| 667 | + let _ = reader.join(); | |
| 668 | + } | |
| 669 | + } | |
| 670 | +} | |
| 671 | + | |
| 672 | +impl Drop for ServiceClient { | |
| 673 | + /// Panic-safe mirror of [`ServiceClient::shutdown`]: the service gets | |
| 674 | + /// a chance to restore the interface even if the UI dies. | |
| 675 | + fn drop(&mut self) { | |
| 676 | + self.request_crack_stop(); | |
| 677 | + self.cmd(&Cmd::Shutdown); | |
| 678 | + let deadline = Instant::now() + Duration::from_secs(2); | |
| 679 | + loop { | |
| 680 | + match self.child.try_wait() { | |
| 681 | + Ok(Some(_)) => break, | |
| 682 | + Ok(None) if Instant::now() < deadline => { | |
| 683 | + std::thread::sleep(Duration::from_millis(25)); | |
| 684 | + } | |
| 685 | + Ok(None) => { | |
| 686 | + let _ = self.child.kill(); | |
| 687 | + break; | |
| 688 | + } | |
| 689 | + Err(_) => break, | |
| 690 | + } | |
| 691 | + } | |
| 692 | + let _ = self.child.wait(); | |
| 693 | + if let Some(reader) = self.reader.take() { | |
| 694 | + let _ = reader.join(); | |
| 695 | + } | |
| 696 | + } | |
| 697 | +} |
src/ui/app.rsmodified+84 -149
| @@ -1,10 +1,8 @@ | ||
| 1 | 1 | //! Root view: nav rail, header bar (interface picker, privilege badge, |
| 2 | 2 | //! monitor/capture toggle), page content, status line, and the background |
| 3 | -//! task that polls the backend event channel. | |
| 3 | +//! task that polls the service event channel. | |
| 4 | 4 | |
| 5 | 5 | use std::collections::BTreeMap; |
| 6 | -use std::sync::Arc; | |
| 7 | -use std::sync::atomic::{AtomicU8, Ordering}; | |
| 8 | 6 | use std::time::Duration; |
| 9 | 7 | |
| 10 | 8 | use crossbeam_channel::{Receiver, Sender}; |
| @@ -22,11 +20,11 @@ use gpuikit::input::InputState; | ||
| 22 | 20 | use gpuikit::layout::{h_stack, v_stack}; |
| 23 | 21 | use gpuikit::theme::{ActiveTheme, Themeable}; |
| 24 | 22 | |
| 25 | -use crate::backend::Backend; | |
| 26 | -use crate::common::{Event, MacAddr}; | |
| 23 | +use crate::common::{Cmd, Event, MacAddr}; | |
| 24 | +use crate::service::ServiceClient; | |
| 27 | 25 | use crate::ui::{attacks, cracker, log as log_view, networks, state::AppState}; |
| 28 | 26 | |
| 29 | -/// How often the UI drains the backend event channel. | |
| 27 | +/// How often the UI drains the service event channel. | |
| 30 | 28 | const EVENT_POLL: Duration = Duration::from_millis(100); |
| 31 | 29 | |
| 32 | 30 | /// Left nav destinations. |
| @@ -53,16 +51,19 @@ impl Page { | ||
| 53 | 51 | |
| 54 | 52 | pub struct AppRoot { |
| 55 | 53 | pub state: AppState, |
| 56 | - /// Backend event channel (mock thread today, real backend later). | |
| 54 | + /// Service event channel (mock thread or service reader thread). | |
| 57 | 55 | pub rx: Receiver<Event>, |
| 58 | 56 | /// UI-triggered actions are injected into the same pipeline. |
| 59 | 57 | pub tx: Sender<Event>, |
| 60 | 58 | pub page: Page, |
| 61 | 59 | /// Privilege indicator; real value from [`crate::iface::is_root`]. |
| 60 | + /// Informational only — the UI never needs root itself; the service | |
| 61 | + /// elevates via polkit when it spawns. | |
| 62 | 62 | pub is_root: bool, |
| 63 | - /// Real radio/attack/cracker orchestrator. `None` in mock mode or | |
| 64 | - /// before the first "Start capture". | |
| 65 | - pub backend: Option<Backend>, | |
| 63 | + /// Privileged radio service client (owns the child process + the | |
| 64 | + /// UI-side cracker stop flag). `None` in mock mode or before the | |
| 65 | + /// first "Start capture". Kept across stop/start cycles. | |
| 66 | + pub service: Option<ServiceClient>, | |
| 66 | 67 | /// Mock data mode (`--mock` / `WIFILAB_MOCK=1`): never touches devices. |
| 67 | 68 | pub is_mock: bool, |
| 68 | 69 | /// Target BSSID picked on the Networks page (AP row or client row). |
| @@ -81,10 +82,6 @@ pub struct AppRoot { | ||
| 81 | 82 | /// Toast queued by the event loop (no Window there) — shown on the |
| 82 | 83 | /// next render pass. |
| 83 | 84 | pub pending_toast: Option<SharedString>, |
| 84 | - /// Elevate-via-polkit handshake: Some while a pkexec re-exec is in | |
| 85 | - /// flight. 0 = waiting on the polkit dialog, 1 = elevated instance | |
| 86 | - /// launched (quit this one), 2 = declined/failed (message was logged). | |
| 87 | - pub elevation: Option<Arc<AtomicU8>>, | |
| 88 | 85 | /// NetworkManager seen active when capture started (fights channels). |
| 89 | 86 | pub nm_active: bool, |
| 90 | 87 | /// Used to invalidate stale cracker simulation ticks after Stop/re-Start. |
| @@ -150,7 +147,7 @@ impl AppRoot { | ||
| 150 | 147 | tx, |
| 151 | 148 | page: Page::Networks, |
| 152 | 149 | is_root: crate::iface::is_root(), |
| 153 | - backend: None, | |
| 150 | + service: None, | |
| 154 | 151 | is_mock, |
| 155 | 152 | selected: None, |
| 156 | 153 | selected_client: None, |
| @@ -159,7 +156,6 @@ impl AppRoot { | ||
| 159 | 156 | attacking_pmkid: false, |
| 160 | 157 | crack_inflight: false, |
| 161 | 158 | pending_toast: None, |
| 162 | - elevation: None, | |
| 163 | 159 | nm_active: false, |
| 164 | 160 | crack_epoch: 0, |
| 165 | 161 | ap_sort: None, |
| @@ -178,32 +174,28 @@ impl AppRoot { | ||
| 178 | 174 | "wifilab UI started (mock backend)".to_string() |
| 179 | 175 | } else { |
| 180 | 176 | format!( |
| 181 | - "wifilab UI started (REAL backend, iface {selected_iface}) — Start capture to bring up monitor mode" | |
| 177 | + "wifilab UI started (REAL backend, iface {selected_iface}) — Start capture spawns the privileged service (polkit) and brings up monitor mode" | |
| 182 | 178 | ) |
| 183 | 179 | }); |
| 184 | 180 | |
| 185 | 181 | cx.on_release(|this, _cx| { |
| 186 | - // Window closed → root view released → stop every worker and | |
| 187 | - // restore the interface to managed mode. | |
| 188 | - if let Some(be) = this.backend.take() { | |
| 189 | - be.shutdown(); | |
| 182 | + // Window closed → root view released → shut the service down | |
| 183 | + // (it stops workers, restores managed mode, exits) and stop | |
| 184 | + // any UI-side crack job. | |
| 185 | + if let Some(svc) = this.service.take() { | |
| 186 | + svc.shutdown(); | |
| 190 | 187 | } |
| 191 | 188 | }) |
| 192 | 189 | .detach(); |
| 193 | 190 | |
| 194 | 191 | if !this.is_root && !this.is_mock { |
| 195 | - if crate::iface::pkexec_available() { | |
| 196 | - cx.toast("not root — click \"Elevate via polkit\" in the header to gain privileges") | |
| 197 | - .show(window, cx); | |
| 198 | - } else { | |
| 199 | - cx.toast("not root and polkit (pkexec) unavailable — monitor mode and injection will fail") | |
| 200 | - .show(window, cx); | |
| 201 | - } | |
| 192 | + cx.toast("not root — polkit will ask for authentication when you start capture") | |
| 193 | + .show(window, cx); | |
| 202 | 194 | } |
| 203 | 195 | |
| 204 | - // Poll the backend event channel: wait on the background executor, | |
| 196 | + // Poll the service event channel: wait on the background executor, | |
| 205 | 197 | // then reduce everything queued into state on the main thread. The |
| 206 | - // backend threads never touch gpui types. | |
| 198 | + // service reader thread never touches gpui types. | |
| 207 | 199 | cx.spawn(async move |this, cx| { |
| 208 | 200 | loop { |
| 209 | 201 | cx.background_executor().timer(EVENT_POLL).await; |
| @@ -222,10 +214,11 @@ impl AppRoot { | ||
| 222 | 214 | |
| 223 | 215 | /// Header "Start/Stop capture" behaviour. |
| 224 | 216 | /// |
| 225 | - /// Real mode: lazily create the [`Backend`] (monitor-mode switch + | |
| 226 | - /// scanner thread) on the channel-selected interface; Stop shuts it | |
| 227 | - /// down and restores managed mode. Mock mode: pure UI flips (the mock | |
| 228 | - /// generator runs independently). | |
| 217 | + /// Real mode: lazily spawn the privileged service (polkit-elevated | |
| 218 | + /// when needed) which switches the interface to monitor mode and runs | |
| 219 | + /// the scanner; Stop only ends the scan session — the service stays | |
| 220 | + /// alive for the cracker page and later scans. Mock mode: pure UI | |
| 221 | + /// flips (the mock generator runs independently). | |
| 229 | 222 | pub fn toggle_monitor(&mut self, cx: &mut Context<Self>) { |
| 230 | 223 | if self.is_mock { |
| 231 | 224 | self.state.iface_running = !self.state.iface_running; |
| @@ -239,29 +232,16 @@ impl AppRoot { | ||
| 239 | 232 | return; |
| 240 | 233 | } |
| 241 | 234 | if self.state.iface_running { |
| 242 | - // STOP: release the radio but KEEP the Backend alive — the | |
| 243 | - // cracker needs it (cracking has no radio use). `stop_radio` | |
| 244 | - // restores managed mode and joins the radio workers only. | |
| 245 | - if let Some(be) = &self.backend { | |
| 246 | - self.state.push_log("ui: stopping capture, restoring managed mode…"); | |
| 247 | - cx.notify(); | |
| 248 | - be.stop_radio(); | |
| 235 | + // STOP: end the scan session but KEEP the service alive — the | |
| 236 | + // cracker needs it, and a later Start reuses it. | |
| 237 | + if let Some(svc) = &self.service { | |
| 249 | 238 | self.state |
| 250 | - .push_log("ui: capture stopped, interface restored (cracker stays available)"); | |
| 239 | + .push_log("ui: stopping capture, service restores managed mode…"); | |
| 240 | + svc.stop_scan(); | |
| 251 | 241 | } |
| 252 | 242 | self.state.iface_running = false; |
| 253 | 243 | cx.notify(); |
| 254 | 244 | } else { |
| 255 | - if !self.is_root { | |
| 256 | - self.state.push_log( | |
| 257 | - "ui: capture REFUSED — no root privileges. Elevate via polkit first.".to_string(), | |
| 258 | - ); | |
| 259 | - self.pending_toast = Some( | |
| 260 | - "ELEVATION REQUIRED: click \"Elevate via polkit\" in the header before starting capture".into(), | |
| 261 | - ); | |
| 262 | - cx.notify(); | |
| 263 | - return; | |
| 264 | - } | |
| 265 | 245 | // NetworkManager fight: pin-to-connected-channel makes ONLY the |
| 266 | 246 | // associated network (e.g. parafin) visible during the hop. |
| 267 | 247 | if crate::iface::networkmanager_active() { |
| @@ -275,15 +255,22 @@ impl AppRoot { | ||
| 275 | 255 | "NetworkManager is active — only your connected network may be visible; stop it from the header".into(), |
| 276 | 256 | ); |
| 277 | 257 | } |
| 278 | - // A Backend kept alive for the cracker from a previous capture | |
| 279 | - // would tear down our new monitor mode in its `Drop` (it | |
| 280 | - // restores managed mode). Drop it BEFORE the fresh | |
| 281 | - // `start_scan` switches the interface up in monitor mode. | |
| 282 | - self.backend = None; | |
| 283 | 258 | let ifname = self.state.ifname.clone(); |
| 284 | - match Backend::start_scan(&ifname, self.tx.clone()) { | |
| 285 | - Ok(be) => { | |
| 286 | - self.backend = Some(be); | |
| 259 | + if let Some(svc) = &self.service { | |
| 260 | + // Service already up (from an earlier session): just ask | |
| 261 | + // for a fresh scan session. | |
| 262 | + svc.cmd(&Cmd::StartScan { | |
| 263 | + ifname: ifname.clone(), | |
| 264 | + }); | |
| 265 | + self.state.iface_running = true; | |
| 266 | + self.state | |
| 267 | + .push_log(format!("ui: capture started on {ifname}")); | |
| 268 | + cx.notify(); | |
| 269 | + return; | |
| 270 | + } | |
| 271 | + match ServiceClient::start(&ifname, self.tx.clone()) { | |
| 272 | + Ok(svc) => { | |
| 273 | + self.service = Some(svc); | |
| 287 | 274 | self.state.iface_running = true; |
| 288 | 275 | self.state |
| 289 | 276 | .push_log(format!("ui: capture started on {ifname}")); |
| @@ -291,88 +278,35 @@ impl AppRoot { | ||
| 291 | 278 | Err(e) => { |
| 292 | 279 | self.state |
| 293 | 280 | .push_log(format!("ERROR: start capture on {ifname}: {e:#}")); |
| 281 | + self.pending_toast = | |
| 282 | + Some(format!("start capture failed: {e:#}").into()); | |
| 294 | 283 | } |
| 295 | 284 | } |
| 296 | 285 | cx.notify(); |
| 297 | 286 | } |
| 298 | 287 | } |
| 299 | 288 | |
| 300 | - /// Stop NetworkManager (root) so it stops pinning the radio to the | |
| 301 | - /// connected network's channel. | |
| 289 | + /// Stop NetworkManager via the privileged service so it stops pinning | |
| 290 | + /// the radio to the connected network's channel. | |
| 302 | 291 | pub fn stop_nm(&mut self, cx: &mut Context<Self>) { |
| 303 | - match crate::iface::stop_networkmanager() { | |
| 304 | - Ok(()) => { | |
| 305 | - self.nm_active = false; | |
| 292 | + match &self.service { | |
| 293 | + Some(svc) => { | |
| 294 | + svc.cmd(&Cmd::StopNetworkManager); | |
| 295 | + self.state | |
| 296 | + .push_log("ui: asking service to stop NetworkManager…"); | |
| 297 | + } | |
| 298 | + None => { | |
| 306 | 299 | self.state.push_log( |
| 307 | - "ui: NetworkManager stopped — channel hopping is now exclusive; restart it later with `systemctl start NetworkManager`" | |
| 308 | - .to_string(), | |
| 300 | + "ui: NM stop needs the privileged service — Start capture first".to_string(), | |
| 309 | 301 | ); |
| 310 | - self.pending_toast = | |
| 311 | - Some("NetworkManager stopped — all networks become visible as the hopper cycles".into()); | |
| 312 | - } | |
| 313 | - Err(e) => { | |
| 314 | - self.state | |
| 315 | - .push_log(format!("ERROR stopping NetworkManager: {e:#}")); | |
| 316 | 302 | } |
| 317 | 303 | } |
| 318 | 304 | cx.notify(); |
| 319 | 305 | } |
| 320 | 306 | |
| 321 | - /// Re-exec this app as root via polkit (pkexec). The polkit dialog is | |
| 322 | - /// fully OS-driven; on success the elevated instance opens its own | |
| 323 | - /// window and this one closes itself. | |
| 324 | - pub fn elevate(&mut self, cx: &mut Context<Self>) { | |
| 325 | - if self.is_root || self.is_mock || self.elevation.is_some() { | |
| 326 | - return; | |
| 327 | - } | |
| 328 | - if self.backend.is_some() { | |
| 329 | - self.state.push_log("ui: stop capture before elevating"); | |
| 330 | - cx.notify(); | |
| 331 | - return; | |
| 332 | - } | |
| 333 | - let flag = Arc::new(AtomicU8::new(0)); | |
| 334 | - self.elevation = Some(flag.clone()); | |
| 335 | - let ifname = self.state.ifname.clone(); | |
| 336 | - let tx = self.tx.clone(); | |
| 337 | - self.state.push_log(format!( | |
| 338 | - "ui: requesting administrative privileges via polkit (restarting elevated on {ifname})…" | |
| 339 | - )); | |
| 340 | - cx.notify(); | |
| 341 | - std::thread::spawn(move || { | |
| 342 | - match crate::iface::relaunch_elevated(&["--iface", ifname.as_str()]) { | |
| 343 | - Ok(st) if st.success() => flag.store(1, Ordering::SeqCst), | |
| 344 | - Ok(st) => { | |
| 345 | - flag.store(2, Ordering::SeqCst); | |
| 346 | - let _ = tx.send(Event::Log(format!( | |
| 347 | - "ui: elevation dialog dismissed or failed (pkexec exit {st})" | |
| 348 | - ))); | |
| 349 | - } | |
| 350 | - Err(e) => { | |
| 351 | - flag.store(2, Ordering::SeqCst); | |
| 352 | - let _ = tx.send(Event::Error(format!("polkit elevation failed: {e:#}"))); | |
| 353 | - } | |
| 354 | - } | |
| 355 | - }); | |
| 356 | - } | |
| 357 | - | |
| 358 | 307 | /// Drain every queued event, track handshake progress, refresh widgets |
| 359 | 308 | /// derived from the capture set. |
| 360 | 309 | fn drain_events(&mut self, cx: &mut Context<Self>) { |
| 361 | - // Elevation handshake: success → the new elevated window is up, | |
| 362 | - // close this one; failure → allow retry (message already queued). | |
| 363 | - if let Some(flag) = &self.elevation { | |
| 364 | - match flag.load(Ordering::SeqCst) { | |
| 365 | - 1 => { | |
| 366 | - self.state | |
| 367 | - .push_log("ui: elevated instance started — closing this window"); | |
| 368 | - self.elevation = None; | |
| 369 | - cx.quit(); | |
| 370 | - return; | |
| 371 | - } | |
| 372 | - 2 => self.elevation = None, | |
| 373 | - _ => {} | |
| 374 | - } | |
| 375 | - } | |
| 376 | 310 | let mut changed = false; |
| 377 | 311 | let mut captures_changed = false; |
| 378 | 312 | while let Ok(event) = self.rx.try_recv() { |
| @@ -388,8 +322,20 @@ impl AppRoot { | ||
| 388 | 322 | Event::PmkidCaptured(_) => { |
| 389 | 323 | self.attacking_pmkid = false; |
| 390 | 324 | } |
| 325 | + // Service child died (EOF seen by the reader thread): | |
| 326 | + // un-flip every running flag and drop the client so the | |
| 327 | + // next Start spawns a fresh, alive service. | |
| 328 | + Event::Error(line) if line == "service terminated" => { | |
| 329 | + self.attacking_handshake = false; | |
| 330 | + self.attacking_pmkid = false; | |
| 331 | + self.state.iface_running = false; | |
| 332 | + self.crack_inflight = false; | |
| 333 | + if let Some(svc) = self.service.take() { | |
| 334 | + svc.shutdown(); // reaps the corpse, restores iface | |
| 335 | + } | |
| 336 | + } | |
| 391 | 337 | // Any worker error, or a terminal log from an attack |
| 392 | - // worker (prefixed by backend.rs; scanner logs are | |
| 338 | + // worker (prefixed by the service; scanner logs are | |
| 393 | 339 | // excluded), un-spins attack buttons so the UI is never |
| 394 | 340 | // stuck "working…". |
| 395 | 341 | Event::Error(_) => { |
| @@ -404,6 +350,16 @@ impl AppRoot { | ||
| 404 | 350 | self.attacking_handshake = false; |
| 405 | 351 | self.attacking_pmkid = false; |
| 406 | 352 | } |
| 353 | + // Service-side NM result: `nm: stopped` / `nm: stop failed …`. | |
| 354 | + Event::Log(line) if line.starts_with("nm:") => { | |
| 355 | + if line == "nm: stopped" { | |
| 356 | + self.nm_active = false; | |
| 357 | + self.pending_toast = Some( | |
| 358 | + "NetworkManager stopped — all networks become visible as the hopper cycles" | |
| 359 | + .into(), | |
| 360 | + ); | |
| 361 | + } | |
| 362 | + } | |
| 407 | 363 | Event::CrackStopped { .. } => { |
| 408 | 364 | self.crack_inflight = false; |
| 409 | 365 | } |
| @@ -493,29 +449,9 @@ impl AppRoot { | ||
| 493 | 449 | } else if self.is_mock { |
| 494 | 450 | badge("not root (mock)").secondary() |
| 495 | 451 | } else { |
| 496 | - badge("not root — elevate to attack").destructive() | |
| 452 | + badge("user (service will elevate)").secondary() | |
| 497 | 453 | }; |
| 498 | 454 | |
| 499 | - let elevate_btn = (!self.is_root && !self.is_mock && crate::iface::pkexec_available()) | |
| 500 | - .then(|| { | |
| 501 | - let waiting = self.elevation.is_some(); | |
| 502 | - button( | |
| 503 | - "elevate-btn", | |
| 504 | - if waiting { | |
| 505 | - "waiting for polkit…" | |
| 506 | - } else { | |
| 507 | - "Elevate via polkit" | |
| 508 | - }, | |
| 509 | - ) | |
| 510 | - .disabled(waiting) | |
| 511 | - .on_click({ | |
| 512 | - let view = view.clone(); | |
| 513 | - move |_, _window, cx| { | |
| 514 | - view.update(cx, |app, cx| app.elevate(cx)); | |
| 515 | - } | |
| 516 | - }) | |
| 517 | - }); | |
| 518 | - | |
| 519 | 455 | let toggle = button( |
| 520 | 456 | "monitor-toggle", |
| 521 | 457 | if running { |
| @@ -538,7 +474,7 @@ impl AppRoot { | ||
| 538 | 474 | |
| 539 | 475 | let nm_badge = (self.nm_active && !self.is_mock) |
| 540 | 476 | .then(|| badge("NM active — channels pinned").destructive()); |
| 541 | - let nm_btn = (self.nm_active && self.is_root && !self.is_mock).then(|| { | |
| 477 | + let nm_btn = (self.nm_active && !self.is_mock).then(|| { | |
| 542 | 478 | button("stop-nm", "Stop NM").on_click({ |
| 543 | 479 | let view = view.clone(); |
| 544 | 480 | move |_, _window, cx| { |
| @@ -558,7 +494,6 @@ impl AppRoot { | ||
| 558 | 494 | .bg(theme.surface()) |
| 559 | 495 | .child(div().text_lg().font_weight(FontWeight::BOLD).child("wifilab")) |
| 560 | 496 | .child(privilege) |
| 561 | - .children(elevate_btn) | |
| 562 | 497 | .child(div().w(px(220.)).child(self.iface_select.clone())) |
| 563 | 498 | .children(nm_badge) |
| 564 | 499 | .children(nm_btn) |
src/ui/attacks.rsmodified+16 -11
| @@ -16,7 +16,7 @@ use gpuikit::elements::typography::{h3, small, text}; | ||
| 16 | 16 | use gpuikit::layout::{h_stack, v_stack}; |
| 17 | 17 | use gpuikit::theme::{ActiveTheme, Themeable}; |
| 18 | 18 | |
| 19 | -use crate::common::{Event, HandshakeCapture, MacAddr, PmkidCapture}; | |
| 19 | +use crate::common::{Cmd, Event, HandshakeCapture, MacAddr, PmkidCapture}; | |
| 20 | 20 | use crate::ui::app::AppRoot; |
| 21 | 21 | use crate::ui::mock; |
| 22 | 22 | |
| @@ -135,8 +135,8 @@ fn capture_handshake(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui | ||
| 135 | 135 | app.state.push_log(format!( |
| 136 | 136 | "handshake capture on {essid} ({ap}, ch {channel})…" |
| 137 | 137 | )); |
| 138 | - if let Some(be) = &app.backend { | |
| 139 | - be.capture_hs(ap, channel, essid, app.tx.clone()); | |
| 138 | + if let Some(svc) = &app.service { | |
| 139 | + svc.cmd(&Cmd::CaptureHs { ap, channel, essid }); | |
| 140 | 140 | } |
| 141 | 141 | cx.notify(); |
| 142 | 142 | return; |
| @@ -222,8 +222,8 @@ fn pmkid_attack(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App | ||
| 222 | 222 | }; |
| 223 | 223 | app.state |
| 224 | 224 | .push_log(format!("pmkid attack on {essid} ({ap}, ch {channel})…")); |
| 225 | - if let Some(be) = &app.backend { | |
| 226 | - be.pmkid(ap, channel, essid, app.tx.clone()); | |
| 225 | + if let Some(svc) = &app.service { | |
| 226 | + svc.cmd(&Cmd::Pmkid { ap, channel, essid }); | |
| 227 | 227 | } |
| 228 | 228 | cx.notify(); |
| 229 | 229 | return; |
| @@ -282,9 +282,9 @@ fn deauth(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) { | ||
| 282 | 282 | cx.notify(); |
| 283 | 283 | return; |
| 284 | 284 | } |
| 285 | - let Some(be) = &app.backend else { | |
| 285 | + let Some(svc) = &app.service else { | |
| 286 | 286 | app.state |
| 287 | - .push_log("deauth: start capture first (the backend owns the radio)"); | |
| 287 | + .push_log("deauth: start capture first (the service owns the radio)"); | |
| 288 | 288 | cx.notify(); |
| 289 | 289 | return; |
| 290 | 290 | }; |
| @@ -310,7 +310,12 @@ fn deauth(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) { | ||
| 310 | 310 | app.state.push_log(format!( |
| 311 | 311 | "deauth: {count} rounds → {target} (AP {ap}, ch {channel})" |
| 312 | 312 | )); |
| 313 | - be.deauth(ap, target, channel, count, app.tx.clone()); | |
| 313 | + svc.cmd(&Cmd::Deauth { | |
| 314 | + ap, | |
| 315 | + target, | |
| 316 | + channel, | |
| 317 | + count, | |
| 318 | + }); | |
| 314 | 319 | cx.notify(); |
| 315 | 320 | return; |
| 316 | 321 | } |
| @@ -396,8 +401,8 @@ pub fn render( | ||
| 396 | 401 | let no_target = app.selected.is_none(); |
| 397 | 402 | // Real mode without a running capture has no radio: block the buttons |
| 398 | 403 | // (a matching hint sits next to them). |
| 399 | - let no_backend = !app.is_mock && !app.state.iface_running; | |
| 400 | - let blocked = no_target || no_backend; | |
| 404 | + let not_running = !app.is_mock && !app.state.iface_running; | |
| 405 | + let blocked = no_target || not_running; | |
| 401 | 406 | let hs_running = app.attacking_handshake; |
| 402 | 407 | let pm_running = app.attacking_pmkid; |
| 403 | 408 | |
| @@ -437,7 +442,7 @@ pub fn render( | ||
| 437 | 442 | .when(hs_running || pm_running, |el| { |
| 438 | 443 | el.child(loading_indicator().small()).child(small("working…")) |
| 439 | 444 | }) |
| 440 | - .when(no_backend, |el| { | |
| 445 | + .when(not_running, |el| { | |
| 441 | 446 | el.child(small("start capture first to enable attacks")) |
| 442 | 447 | }); |
| 443 | 448 |
src/ui/cracker.rsmodified+10 -8
| @@ -111,8 +111,8 @@ fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) { | ||
| 111 | 111 | "cracker: starting on {desc} via {wordlist} [auto backend]" |
| 112 | 112 | )); |
| 113 | 113 | cx.notify(); |
| 114 | - match &app.backend { | |
| 115 | - Some(be) => be.crack( | |
| 114 | + match &app.service { | |
| 115 | + Some(svc) => svc.spawn_crack( | |
| 116 | 116 | target.describe(), |
| 117 | 117 | target, |
| 118 | 118 | std::path::PathBuf::from(&wordlist), |
| @@ -122,7 +122,7 @@ fn start(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) { | ||
| 122 | 122 | app.state.cracker.running = false; |
| 123 | 123 | app.crack_inflight = false; |
| 124 | 124 | app.state |
| 125 | - .push_log("ERROR: cracker: no backend (start capture first, then stop it)"); | |
| 125 | + .push_log("ERROR: cracker: no service (start capture first, then stop it)"); | |
| 126 | 126 | cx.notify(); |
| 127 | 127 | } |
| 128 | 128 | } |
| @@ -187,8 +187,8 @@ fn stop(view: &Entity<AppRoot>, _window: &mut Window, cx: &mut gpui::App) { | ||
| 187 | 187 | cx.notify(); |
| 188 | 188 | return; |
| 189 | 189 | } |
| 190 | - if let Some(be) = &app.backend { | |
| 191 | - be.request_crack_stop(); | |
| 190 | + if let Some(svc) = &app.service { | |
| 191 | + svc.request_crack_stop(); | |
| 192 | 192 | app.state.push_log("cracker: stop requested"); |
| 193 | 193 | } else { |
| 194 | 194 | app.state.cracker.running = false; |
| @@ -215,10 +215,12 @@ pub fn render( | ||
| 215 | 215 | } else { |
| 216 | 216 | 0.0 |
| 217 | 217 | }; |
| 218 | - // Real mode: cracker needs the radio — capture must be stopped and a | |
| 219 | - // backend must exist. | |
| 218 | + // Real mode: cracker needs the radio free — capture must be stopped | |
| 219 | + // and a service must have run at least once (it owns the cracker's | |
| 220 | + // stop flag). After the first "Stop capture" this stays permanently | |
| 221 | + // unblocked: the service is kept alive across sessions. | |
| 220 | 222 | let crack_blocked = |
| 221 | - !app.is_mock && (app.state.iface_running || app.backend.is_none()); | |
| 223 | + !app.is_mock && (app.state.iface_running || app.service.is_none()); | |
| 222 | 224 | let candidates = if app.is_mock { |
| 223 | 225 | format!("candidates: {} / {WORDLIST_TOTAL}", cracker.tried) |
| 224 | 226 | } else { |
src/ui/mock.rsmodified+8 -8
| @@ -8,7 +8,7 @@ use std::time::{Duration, Instant}; | ||
| 8 | 8 | use crossbeam_channel::Sender; |
| 9 | 9 | |
| 10 | 10 | use crate::common::{ |
| 11 | - AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture, Security, | |
| 11 | + AccessPoint, ClientInfo, Event, HandshakeCapture, MacAddr, PmkidCapture, Security, now_ms, | |
| 12 | 12 | }; |
| 13 | 13 | |
| 14 | 14 | /// Salted deterministic PRNG (xorshift64) — no rand crate, values only need |
| @@ -44,7 +44,7 @@ pub const MOCK_CLIENTS: [MacAddr; 4] = [ | ||
| 44 | 44 | ]; |
| 45 | 45 | |
| 46 | 46 | fn seed_aps() -> Vec<AccessPoint> { |
| 47 | - let now = Instant::now(); | |
| 47 | + let now = now_ms(); | |
| 48 | 48 | let ap = |mac: [u8; 6], ssid: &str, channel, security, rssi| AccessPoint { |
| 49 | 49 | bssid: MacAddr(mac), |
| 50 | 50 | ssid: ssid.to_string(), |
| @@ -52,7 +52,7 @@ fn seed_aps() -> Vec<AccessPoint> { | ||
| 52 | 52 | security, |
| 53 | 53 | rssi_dbm: rssi, |
| 54 | 54 | beacons: 200, |
| 55 | - last_seen: now, | |
| 55 | + last_seen_ms: now, | |
| 56 | 56 | }; |
| 57 | 57 | vec![ |
| 58 | 58 | ap([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], "parafin", 6, Security::Wpa2, -42), |
| @@ -65,13 +65,13 @@ fn seed_aps() -> Vec<AccessPoint> { | ||
| 65 | 65 | } |
| 66 | 66 | |
| 67 | 67 | fn seed_clients() -> Vec<ClientInfo> { |
| 68 | - let now = Instant::now(); | |
| 68 | + let now = now_ms(); | |
| 69 | 69 | let cl = |mac: MacAddr, ap: MacAddr, rssi| ClientInfo { |
| 70 | 70 | mac, |
| 71 | 71 | ap: Some(ap), |
| 72 | 72 | rssi_dbm: rssi, |
| 73 | 73 | frames: 40, |
| 74 | - last_seen: now, | |
| 74 | + last_seen_ms: now, | |
| 75 | 75 | }; |
| 76 | 76 | vec![ |
| 77 | 77 | cl(MOCK_CLIENTS[0], MOCK_BSSID, -44), |
| @@ -176,19 +176,19 @@ fn run(tx: Sender<Event>) { | ||
| 176 | 176 | loop { |
| 177 | 177 | thread::sleep(Duration::from_millis(200)); |
| 178 | 178 | let t = started.elapsed().as_secs_f32(); |
| 179 | - let now = Instant::now(); | |
| 179 | + let now = now_ms(); | |
| 180 | 180 | |
| 181 | 181 | // RSSI drift + beacon/frame counters on every tick. |
| 182 | 182 | for ap in &mut aps { |
| 183 | 183 | ap.rssi_dbm = (ap.rssi_dbm + (rng.below(5) as i8 - 2)).clamp(-90, -30); |
| 184 | 184 | ap.beacons += rng.below(3); |
| 185 | - ap.last_seen = now; | |
| 185 | + ap.last_seen_ms = now; | |
| 186 | 186 | let _ = tx.send(Event::ApUpdated(ap.clone())); |
| 187 | 187 | } |
| 188 | 188 | for cl in &mut clients { |
| 189 | 189 | cl.rssi_dbm = (cl.rssi_dbm + (rng.below(3) as i8 - 1)).clamp(-90, -30); |
| 190 | 190 | cl.frames += rng.below(12); |
| 191 | - cl.last_seen = now; | |
| 191 | + cl.last_seen_ms = now; | |
| 192 | 192 | let _ = tx.send(Event::ClientUpdated(cl.clone())); |
| 193 | 193 | } |
| 194 | 194 |
src/ui/mod.rsmodified+6 -6
| @@ -1,9 +1,8 @@ | ||
| 1 | 1 | //! GPUI + gpuikit shell for wifilab. |
| 2 | 2 | //! |
| 3 | -//! `run_app` opens the window and wires the backend event channel. Today the | |
| 4 | -//! producer is the mock generator in [`mock`]; when the real | |
| 5 | -//! radiotap/dot11/scanner/attack/cracker threads land they take over the | |
| 6 | -//! `Sender` side and the UI changes nowhere else. | |
| 3 | +//! `run_app` opens the window and wires the service event channel: the mock | |
| 4 | +//! generator in [`mock`] (mock mode) or the privileged-service reader thread | |
| 5 | +//! feed the `Sender` side; the UI itself never needs root. | |
| 7 | 6 | |
| 8 | 7 | mod app; |
| 9 | 8 | mod attacks; |
| @@ -23,8 +22,9 @@ use gpuikit::theme::{GlobalTheme, Theme}; | ||
| 23 | 22 | /// Launch the UI. Blocks until the window closes. |
| 24 | 23 | /// |
| 25 | 24 | /// `mock_flag` is the CLI `--mock` switch; combined with the legacy |
| 26 | -/// `WIFILAB_MOCK` env var. The REAL backend is the default: `Backend` is | |
| 27 | -/// created lazily on the first "Start capture" click. | |
| 25 | +/// `WIFILAB_MOCK` env var. The REAL service is the default: the | |
| 26 | +/// [`crate::service::ServiceClient`] spawns lazily on the first | |
| 27 | +/// "Start capture" click (polkit-elevated child process). | |
| 28 | 28 | pub fn run_app(iface: Option<String>, mock_flag: bool) { |
| 29 | 29 | let (tx, rx) = crossbeam_channel::unbounded(); |
| 30 | 30 |
src/ui/networks.rsmodified+8 -9
| @@ -1,8 +1,6 @@ | ||
| 1 | 1 | //! Networks page: sortable AP table, clients table, row-click target |
| 2 | 2 | //! selection. |
| 3 | 3 | |
| 4 | -use std::time::Instant; | |
| 5 | - | |
| 6 | 4 | use gpui::{Context, Entity, IntoElement, ParentElement, Styled, Window, div, px}; |
| 7 | 5 | use gpuikit::elements::badge::badge; |
| 8 | 6 | use gpuikit::elements::table::{CellAlign, Column, Row, SortDirection, Table, table}; |
| @@ -26,9 +24,10 @@ const CCOL_RSSI: usize = 2; | ||
| 26 | 24 | const CCOL_FRAMES: usize = 3; |
| 27 | 25 | const CCOL_AGE: usize = 4; |
| 28 | 26 | |
| 29 | -/// Human "last seen" age, e.g. `2s`, `5m`, `1h`. | |
| 30 | -pub fn age(last_seen: Instant) -> String { | |
| 31 | - let s = last_seen.elapsed().as_secs(); | |
| 27 | +/// Human "last seen" age, e.g. `2s`, `5m`, `1h`. `last_seen_ms` comes from | |
| 28 | +/// the UI/service-side process-local clock ([`crate::common::now_ms`]). | |
| 29 | +pub fn age(last_seen_ms: u64) -> String { | |
| 30 | + let s = crate::common::now_ms().saturating_sub(last_seen_ms) / 1000; | |
| 32 | 31 | if s < 60 { |
| 33 | 32 | format!("{s}s") |
| 34 | 33 | } else if s < 3600 { |
| @@ -57,7 +56,7 @@ fn sorted_aps(app: &AppRoot) -> Vec<AccessPoint> { | ||
| 57 | 56 | COL_SEC => l.security.label().cmp(r.security.label()), |
| 58 | 57 | COL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm), |
| 59 | 58 | COL_BEACONS => l.beacons.cmp(&r.beacons), |
| 60 | - COL_AGE => l.last_seen.cmp(&r.last_seen).reverse(), // newest = 0s first | |
| 59 | + COL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(), // newest = 0s first | |
| 61 | 60 | _ => std::cmp::Ordering::Equal, |
| 62 | 61 | }; |
| 63 | 62 | rows.sort_by(|l, r| match sort.direction { |
| @@ -76,7 +75,7 @@ fn sorted_clients(app: &AppRoot) -> Vec<ClientInfo> { | ||
| 76 | 75 | CCOL_AP => l.ap.cmp(&r.ap), |
| 77 | 76 | CCOL_RSSI => l.rssi_dbm.cmp(&r.rssi_dbm), |
| 78 | 77 | CCOL_FRAMES => l.frames.cmp(&r.frames), |
| 79 | - CCOL_AGE => l.last_seen.cmp(&r.last_seen).reverse(), | |
| 78 | + CCOL_AGE => l.last_seen_ms.cmp(&r.last_seen_ms).reverse(), | |
| 80 | 79 | _ => std::cmp::Ordering::Equal, |
| 81 | 80 | }; |
| 82 | 81 | rows.sort_by(|l, r| match sort.direction { |
| @@ -159,7 +158,7 @@ fn ap_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<AccessPoint> { | ||
| 159 | 158 | ) |
| 160 | 159 | .column( |
| 161 | 160 | Column::new("AGE", |ap: &AccessPoint, _w, _cx| { |
| 162 | - div().child(age(ap.last_seen)).into_any_element() | |
| 161 | + div().child(age(ap.last_seen_ms)).into_any_element() | |
| 163 | 162 | }) |
| 164 | 163 | .sortable() |
| 165 | 164 | .fixed(px(70.)) |
| @@ -246,7 +245,7 @@ fn client_table(app: &AppRoot, view: &Entity<AppRoot>) -> Table<ClientInfo> { | ||
| 246 | 245 | ) |
| 247 | 246 | .column( |
| 248 | 247 | Column::new("AGE", |cl: &ClientInfo, _w, _cx| { |
| 249 | - div().child(age(cl.last_seen)).into_any_element() | |
| 248 | + div().child(age(cl.last_seen_ms)).into_any_element() | |
| 250 | 249 | }) |
| 251 | 250 | .sortable() |
| 252 | 251 | .fixed(px(70.)) |
src/ui/state.rsmodified+3 -3
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | //! Application state: the UI-side home for everything arriving over the |
| 2 | -//! backend event channel. Backend swap-in keeps this type untouched. | |
| 2 | +//! service event channel (mock thread or privileged-service reader). | |
| 3 | 3 | |
| 4 | 4 | use std::collections::{BTreeMap, VecDeque}; |
| 5 | 5 | |
| @@ -25,7 +25,7 @@ pub struct CrackerState { | ||
| 25 | 25 | } |
| 26 | 26 | |
| 27 | 27 | /// Everything the window renders. Updated exclusively by |
| 28 | -/// [`AppState::apply`] so a real backend can reuse the reduction logic. | |
| 28 | +/// [`AppState::apply`] so a real service can reuse the reduction logic. | |
| 29 | 29 | pub struct AppState { |
| 30 | 30 | /// Whether the interface is (pretending to be) capturing in monitor mode. |
| 31 | 31 | pub iface_running: bool, |
| @@ -70,7 +70,7 @@ impl AppState { | ||
| 70 | 70 | self.log.push_back(line.into()); |
| 71 | 71 | } |
| 72 | 72 | |
| 73 | - /// Reduce one backend event into state. Returns `true` when the set of | |
| 73 | + /// Reduce one service event into state. Returns `true` when the set of | |
| 74 | 74 | /// crackable captures changed (callers rebuild dependent widgets). |
| 75 | 75 | pub fn apply(&mut self, event: Event) -> bool { |
| 76 | 76 | match event { |