forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

iface.rs514 lines, 18.8 KiBHistoryRawDownload
1//! System interface control via `ip`/`iw` subprocess (boring + portable).
2//!
3//! The interface must not be under active control of NetworkManager or
4//! wpa_supplicant while in monitor mode — that interference is the caller's
5//! concern (this module intentionally does NOT kill daemons like airmon-ng).
6
7use std::process::Command;
8use std::sync::Mutex;
9use std::sync::atomic::{AtomicU16, Ordering};
10
11use anyhow::{Context, Result, bail};
12
13use crate::common::MacAddr;
14
15/// Run a command, capturing stderr into the anyhow context on failure.
16fn run(cmd: &str, args: &[String]) -> Result<String> {
17 let out = Command::new(cmd)
18 .args(args)
19 .output()
20 .with_context(|| format!("spawning {cmd}"))?;
21 let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
22 if !out.status.success() {
23 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
24 bail!("{} {} failed: {}", cmd, args.join(" "), stderr);
25 }
26 Ok(stdout)
27}
28
29fn ip(args: &[&str]) -> Result<String> {
30 let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
31 run("ip", &args)
32}
33
34fn iw(args: &[&str]) -> Result<String> {
35 let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
36 run("iw", &args)
37}
38
39/// RF-channel arbitration shared by the hopping scanner and the attack
40/// workers. The scanner consults [`ChannelPin::get`] once per hop cycle:
41/// nonzero → dwell on that frequency; zero → normal hop. Attack workers
42/// move the pin instead of fighting the hopper with their own `set_freq`
43/// calls (the scanner re-asserts the pinned value, not the hop plan).
44///
45/// Two layers: `holds` is the stack of long-lived holders' desired MHz
46/// (the handshake-capture workers — the radio must get the channel BACK
47/// after a short interruption), `active` is what the scanner currently
48/// must dwell on. A deauth worker briefly
49/// [`override_freq`](ChannelPin::override_freq)s `active` per band, then
50/// [`settle`](ChannelPin::settle)s to restore the top holder's frequency
51/// (or free hop when nothing is held).
52///
53/// Holds are REFCOUNTED, not single-owner: two concurrent captures on the
54/// same band each [`hold`](ChannelPin::hold) the same MHz, and the pin
55/// frees only when the LAST [`release`](ChannelPin::release) drops — the
56/// first capture's worker exiting early must not un-pin the channel out
57/// from under the second. The TOP of the stack (most recent hold of a
58/// still-held frequency) is the owner whose frequency `settle` restores.
59pub struct ChannelPin {
60 active: AtomicU16,
61 /// Every open hold, in hold order (duplicates kept; the LAST entry is
62 /// the owner whose frequency `settle` restores).
63 holds: Mutex<Vec<u16>>,
64}
65
66impl ChannelPin {
67 /// Long-lived hold: push `mhz` onto the holder stack and pin the
68 /// radio to it. Concurrent holders of the same MHz each push their
69 /// own entry; matching [`release`](ChannelPin::release)s pop one each.
70 pub fn hold(&self, mhz: u16) {
71 self.holds.lock().expect("pin holds poisoned").push(mhz);
72 self.active.store(mhz, Ordering::Release);
73 }
74
75 /// Release ONE hold of `mhz` (a holder may hold exactly one entry per
76 /// [`hold`](ChannelPin::hold) call). A release with no matching hold —
77 /// e.g. a stale worker releasing a frequency it never held — is
78 /// ignored so it can't un-pin someone else's capture. The scanner
79 /// returns to free hopping (or the remaining top holder) only when
80 /// the released entry was the owner; a release by a NON-owner holder
81 /// of the same frequency leaves the pin untouched.
82 pub fn release(&self, mhz: u16) {
83 let mut holds = self.holds.lock().expect("pin holds poisoned");
84 let before = holds.last().copied();
85 let Some(pos) = holds.iter().rposition(|&f| f == mhz) else {
86 return; // foreign release: no matching hold, ignore
87 };
88 holds.remove(pos);
89 let after = holds.last().copied();
90 if after != before {
91 self.active.store(after.unwrap_or(0), Ordering::Release);
92 }
93 }
94
95 /// Short-lived override (deauth per-band): move the radio now WITHOUT
96 /// touching ownership — a later [`settle`](ChannelPin::settle) hands
97 /// the channel back to the owner.
98 pub fn override_freq(&self, mhz: u16) {
99 self.active.store(mhz, Ordering::Release);
100 }
101
102 /// Deauth finished: restore the owner's frequency, or free hop (0)
103 /// when nothing is held.
104 pub fn settle(&self) {
105 let owner = self
106 .holds
107 .lock()
108 .expect("pin holds poisoned")
109 .last()
110 .copied();
111 self.active.store(owner.unwrap_or(0), Ordering::Release);
112 }
113
114 /// MHz the scanner must dwell on; 0 = free hopping.
115 pub fn get(&self) -> u16 {
116 self.active.load(Ordering::Acquire)
117 }
118}
119
120impl Default for ChannelPin {
121 fn default() -> Self {
122 ChannelPin {
123 active: AtomicU16::new(0),
124 holds: Mutex::new(Vec::new()),
125 }
126 }
127}
128
129/// True when `ifname` shows up as a netdev in `iw dev` output.
130fn iface_exists(ifname: &str) -> bool {
131 iw(&["dev"])
132 .map(|out| {
133 out.lines().any(|l| {
134 l.trim_start().starts_with("Interface ")
135 && l.trim() == format!("Interface {ifname}")
136 })
137 })
138 .unwrap_or(false)
139}
140
141/// Enter monitor mode by creating a DEDICATED monitor vif `<ifname>mon`
142/// and bringing the original STA vif DOWN.
143///
144/// Why never switch type in place: on iwlwifi (verified on this lab box,
145/// AX-class) a STA vif that has ever been associated drags a firmware
146/// channel-context with it into monitor type — `iw set channel`/`set freq`
147/// succeed at the cfg80211 level, `iw dev info` shows the new channel, yet
148/// the RX path demonstrably stays pinned to the old association channel
149/// (only that AP's frames ever arrive). A freshly created monitor vif has
150/// no such context and receives everything, with the STA vif merely down.
151/// Bringing the STA vif down also releases the channel context, so the
152/// original interface survives (no `iw dev del`).
153///
154/// Idempotent. Returns the monitor vif name (`<ifname>mon`). Callers pass
155/// the returned name to channel-setting and sockets, and call
156/// [`teardown_monitor`] with the ORIGINAL ifname to restore.
157pub fn to_monitor(ifname: &str) -> Result<String> {
158 let mon = monitor_name(ifname);
159 // STA down first: releases any channel context the association held.
160 ip(&["link", "set", ifname, "down"])?;
161 if !iface_exists(&mon) {
162 let phy = phy_of(ifname)?;
163 iw(&["phy", &phy, "interface", "add", &mon, "type", "monitor"])
164 .with_context(|| format!("adding monitor vif {mon} on {phy}"))?;
165 }
166 ip(&["link", "set", &mon, "up"])?;
167 Ok(mon)
168}
169
170/// Unload + reload the kernel driver bound to `ifname`'s device, then wait
171/// for the interface to re-enumerate and force it back DOWN (the managed
172/// vif is recreated by the driver; NetworkManager may grab it otherwise).
173/// Last-resort recovery for the mt76/mt7921e monitor-TX wedge: injected
174/// frames report send() success but never radiate (verified on lab MT7922:
175/// 12 wildcard probes → 0 probe responses; after `modprobe -r mt7921e` +
176/// reload → 7 responses). RX is unaffected by the wedge, so scans look
177/// healthy while deauth/PMKID silently do nothing — the only cure found is
178/// a driver reload. ALL vifs (managed + monitor) on the phy die with the
179/// unload; callers must recreate the monitor vif afterwards.
180pub fn reset_driver(ifname: &str) -> Result<()> {
181 let uevent = std::fs::read_to_string(format!("/sys/class/net/{ifname}/device/uevent"))
182 .with_context(|| format!("reading device uevent for {ifname}"))?;
183 let driver = uevent
184 .lines()
185 .find_map(|l| l.strip_prefix("DRIVER="))
186 .context("no DRIVER= in device uevent — not a PCI/USB driver?)")?;
187 let run_modprobe = |args: &[&str]| {
188 Command::new("modprobe")
189 .args(args)
190 .output()
191 .with_context(|| format!("running modprobe {args:?}"))
192 .and_then(|o| {
193 if o.status.success() {
194 Ok(())
195 } else {
196 bail!("modprobe {args:?}: {}", String::from_utf8_lossy(&o.stderr))
197 }
198 })
199 };
200 run_modprobe(&["-r", driver])
201 .with_context(|| format!("unloading {driver} (injection-wedge recovery)"))?;
202 std::thread::sleep(std::time::Duration::from_secs(1));
203 run_modprobe(&[driver]).with_context(|| format!("reloading {driver}"))?;
204 // Re-enumeration (firmware load etc.) takes a moment.
205 for _ in 0..50 {
206 if std::path::Path::new(&format!("/sys/class/net/{ifname}")).exists() {
207 break;
208 }
209 std::thread::sleep(std::time::Duration::from_millis(100));
210 }
211 if !std::path::Path::new(&format!("/sys/class/net/{ifname}")).exists() {
212 bail!("{ifname} did not re-enumerate within 5 s of reloading {driver}");
213 }
214 std::thread::sleep(std::time::Duration::from_millis(500));
215 ip(&["link", "set", ifname, "down"])?;
216 Ok(())
217}
218
219/// Reverse [`to_monitor`]: delete the monitor vif if present and bring the
220/// original interface back up (it never left managed type). Idempotent.
221pub fn teardown_monitor(ifname: &str) -> Result<()> {
222 let mon = monitor_name(ifname);
223 if iface_exists(&mon) {
224 let _ = ip(&["link", "set", &mon, "down"]);
225 iw(&["dev", &mon, "del"])?;
226 }
227 if iface_exists(ifname) {
228 ip(&["link", "set", ifname, "up"])?;
229 }
230 Ok(())
231}
232
233/// Monitor vif name convention — single source of truth.
234pub fn monitor_name(ifname: &str) -> String {
235 format!("{ifname}mon")
236}
237
238/// Resolve the wiphy name (e.g. "phy0") that owns `ifname` via sysfs.
239fn phy_of(ifname: &str) -> Result<String> {
240 let link = format!("/sys/class/net/{ifname}/phy80211");
241 let target = std::fs::read_link(&link)
242 .with_context(|| format!("reading {link} — is {ifname} wireless?"))?;
243 let name = target
244 .file_name()
245 .and_then(|n| n.to_str())
246 .map(str::to_string)
247 .with_context(|| format!("resolving phy name for {ifname}"))?;
248 Ok(name)
249}
250
251/// Tune the interface to channel `ch` (one retry — some drivers drop the
252/// first request when issued immediately after a mode switch).
253pub fn set_channel(ifname: &str, ch: u8) -> Result<()> {
254 let ch = ch.to_string();
255 match iw(&["dev", ifname, "set", "channel", &ch]) {
256 Ok(_) => Ok(()),
257 Err(e) => {
258 std::thread::sleep(std::time::Duration::from_millis(50));
259 iw(&["dev", ifname, "set", "channel", &ch])
260 .map(|_| ())
261 .with_context(|| format!("set channel {ch} on {ifname} after retry: {e:#}"))
262 }
263 }
264}
265
266/// Tune by carrier frequency — the only unambiguous way once 6 GHz enters
267/// (6 GHz channel numbers collide with 2.4 GHz in `iw set channel`).
268pub fn set_freq(ifname: &str, freq_mhz: u16) -> Result<()> {
269 let f = freq_mhz.to_string();
270 match iw(&["dev", ifname, "set", "freq", &f]) {
271 Ok(_) => Ok(()),
272 Err(e) => {
273 std::thread::sleep(std::time::Duration::from_millis(50));
274 iw(&["dev", ifname, "set", "freq", &f])
275 .map(|_| ())
276 .with_context(|| format!("set freq {f} on {ifname} after retry: {e:#}"))
277 }
278 }
279}
280
281/// Wireless interfaces present: /sys/class/net/<if> has DEVTYPE=wlan in its
282/// uevent, or a `wireless` directory.
283pub fn list_wifi_ifaces() -> Vec<String> {
284 let mut out = Vec::new();
285 let Ok(entries) = std::fs::read_dir("/sys/class/net") else {
286 return out;
287 };
288 for ent in entries.flatten() {
289 let name = ent.file_name().to_string_lossy().into_owned();
290 let has_wireless = ent.path().join("wireless").exists();
291 let uevent_wlan = std::fs::read_to_string(ent.path().join("uevent"))
292 .map(|u| u.lines().any(|l| l == "DEVTYPE=wlan"))
293 .unwrap_or(false);
294 if has_wireless || uevent_wlan {
295 out.push(name);
296 }
297 }
298 out.sort();
299 out
300}
301
302/// Our own MAC on ifname (`/sys/class/net/<ifname>/address`).
303pub fn mac_of(ifname: &str) -> Result<MacAddr> {
304 let s = std::fs::read_to_string(format!("/sys/class/net/{ifname}/address"))
305 .with_context(|| format!("reading MAC of {ifname}"))?;
306 s.trim()
307 .parse::<MacAddr>()
308 .with_context(|| format!("parsing MAC of {ifname}"))
309}
310
311/// True when running with euid 0; UI surfaces a warning otherwise.
312pub fn is_root() -> bool {
313 // SAFETY: geteuid is always successful and thread-safe.
314 (unsafe { libc::geteuid() }) == 0
315}
316
317/// True while NetworkManager is active — it will fight channel control and
318/// pin the card to the connected network's channel (only *that* SSID's
319/// beacons get seen). No root needed to check.
320pub fn networkmanager_active() -> bool {
321 Command::new("systemctl")
322 .args(["is-active", "--quiet", "NetworkManager"])
323 .status()
324 .map(|s| s.success())
325 .unwrap_or(false)
326}
327
328/// Stop NetworkManager (and with it wpa_supplicant's radio fighting).
329/// Requires root. Restart later with [`start_networkmanager`]
330/// (`systemctl start NetworkManager`).
331pub fn stop_networkmanager() -> Result<()> {
332 run("systemctl", &["stop".into(), "NetworkManager".into()]).map(|_| ())
333}
334
335/// Start NetworkManager again (mirrors [`stop_networkmanager`]), restoring
336/// normal managed-mode connectivity once capture work is done. Requires root.
337pub fn start_networkmanager() -> Result<()> {
338 run("systemctl", &["start".into(), "NetworkManager".into()]).map(|_| ())
339}
340
341/// True when the monitor vif `<ifname>mon` no longer exists — the post-scan
342/// restore check wants this so we can warn the user if the interface was
343/// left in monitor mode.
344pub fn monitor_gone(ifname: &str) -> bool {
345 !iface_exists(&monitor_name(ifname))
346}
347
348/// True when `pkexec` (polkit) is available to elevate the privileged
349/// service child.
350pub fn pkexec_available() -> bool {
351 Command::new("pkexec")
352 .arg("--version")
353 .stdout(std::process::Stdio::null())
354 .stderr(std::process::Stdio::null())
355 .status()
356 .map(|s| s.success())
357 .unwrap_or(false)
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 #[test]
365 fn list_wifi_ifaces_does_not_panic() {
366 // On any host (lab box or CI container) this must return without
367 // panic; entries, when present, are non-empty names.
368 for name in list_wifi_ifaces() {
369 assert!(!name.is_empty());
370 }
371 }
372
373 #[test]
374 fn mac_of_loopback_is_zero() {
375 // lo always exists and always reports 00:00:00:00:00:00.
376 let mac = mac_of("lo").expect("reading lo MAC");
377 assert!(mac.is_zero());
378 }
379
380 #[test]
381 fn mac_of_missing_iface_is_err() {
382 assert!(mac_of("definitely-not-an-iface-xyz").is_err());
383 }
384
385 #[test]
386 fn is_root_agrees_with_env() {
387 // In dev/CI this runs unprivileged; under sudo it runs as root.
388 // Either way the getter must match the process uid truth.
389 assert_eq!(is_root(), (unsafe { libc::geteuid() }) == 0);
390 }
391
392 #[test]
393 fn pin_defaults_to_free_hop() {
394 let pin = ChannelPin::default();
395 assert_eq!(pin.get(), 0);
396 }
397
398 #[test]
399 fn pin_hold_pins_and_release_frees() {
400 let pin = ChannelPin::default();
401 pin.hold(2437);
402 assert_eq!(pin.get(), 2437);
403 pin.release(2437);
404 assert_eq!(pin.get(), 0);
405 }
406
407 #[test]
408 fn pin_foreign_release_is_ignored() {
409 let pin = ChannelPin::default();
410 pin.hold(2437);
411 // A stale worker releasing a DIFFERENT frequency must not un-pin.
412 pin.release(5180);
413 assert_eq!(pin.get(), 2437);
414 pin.release(2437);
415 assert_eq!(pin.get(), 0);
416 }
417
418 #[test]
419 fn pin_override_moves_active_but_settle_restores_owner() {
420 let pin = ChannelPin::default();
421 pin.hold(2437);
422 // Deauth worker briefly de-tunes to another band, then settles.
423 pin.override_freq(5180);
424 assert_eq!(pin.get(), 5180);
425 pin.settle();
426 assert_eq!(
427 pin.get(),
428 2437,
429 "settle must hand the channel back to the owner"
430 );
431 pin.release(2437);
432 assert_eq!(pin.get(), 0);
433 }
434
435 #[test]
436 fn pin_settle_without_owner_frees() {
437 let pin = ChannelPin::default();
438 pin.override_freq(5180);
439 pin.settle();
440 assert_eq!(pin.get(), 0);
441 }
442
443 #[test]
444 fn pin_rehold_replaces_owner() {
445 let pin = ChannelPin::default();
446 pin.hold(2437);
447 pin.hold(5865);
448 assert_eq!(pin.get(), 5865);
449 // The old owner's release is now foreign; the new one sticks.
450 pin.release(2437);
451 assert_eq!(pin.get(), 5865);
452 pin.release(5865);
453 assert_eq!(pin.get(), 0);
454 }
455
456 #[test]
457 fn pin_concurrent_holds_same_freq_free_on_last_release() {
458 // Two concurrent captures on the SAME band: the first worker's
459 // exit must NOT un-pin the channel from under the second — the
460 // pin frees only when the LAST holder releases.
461 let pin = ChannelPin::default();
462 pin.hold(2437);
463 pin.hold(2437);
464 assert_eq!(pin.get(), 2437);
465 pin.release(2437); // first capture's worker exits
466 assert_eq!(pin.get(), 2437, "second capture still holds the pin");
467 pin.release(2437); // last holder drops
468 assert_eq!(pin.get(), 0);
469 }
470
471 #[test]
472 fn pin_settle_restores_while_same_freq_still_held() {
473 // Deauth mid-double-capture: settling after an override must hand
474 // the channel back to the still-held frequency, not to free hop.
475 let pin = ChannelPin::default();
476 pin.hold(2437);
477 pin.hold(2437);
478 pin.override_freq(5180);
479 pin.settle();
480 assert_eq!(pin.get(), 2437);
481 pin.release(2437);
482 assert_eq!(pin.get(), 2437);
483 pin.release(2437);
484 assert_eq!(pin.get(), 0);
485 }
486
487 #[test]
488 fn pin_concurrent_threads_end_free() {
489 // N threads hold+release the same frequency with interleavings
490 // scrambled by the scheduler; no matter the order, the pin must
491 // end free once every holder dropped (no leaked or spuriously
492 // freed pins), and must NEVER read 0 while a hold is still open.
493 use std::sync::Arc;
494 let pin = Arc::new(ChannelPin::default());
495 let mut threads = Vec::new();
496 for _ in 0..8 {
497 let pin = pin.clone();
498 threads.push(std::thread::spawn(move || {
499 for _ in 0..200 {
500 pin.hold(2437);
501 assert!(
502 pin.get() != 0,
503 "pin must never free-hop while a hold is open"
504 );
505 pin.release(2437);
506 }
507 }));
508 }
509 for t in threads {
510 t.join().expect("pin worker");
511 }
512 assert_eq!(pin.get(), 0, "all holds released ⇒ free hop");
513 }
514}