A WiFi security auditing software
scan: replace airodump-ng with a native capture engine
Martin Olivierac4e4046d317
diff --git a/Cargo.lock b/Cargo.lockindex 83680b1..0b538fa 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -41,12 +41,16 @@ name = "airgorah-agent"version = "0.8.1"dependencies = ["airgorah-common",+ "chrono","csv","ctrlc","env_logger","lazy_static",+ "libc",+ "libwifi","log","nix",+ "radiotap","serde","thiserror",]@@ -144,6 +148,27 @@ version = "2.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"+[[package]]+name = "bitops"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f41a723cb1fba322fe1bc95dd28dc7e7aadd8d3f81db31511df86c64c2d4a57e"+dependencies = [+ "num-integer",+]++[[package]]+name = "bitvec"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"+dependencies = [+ "funty",+ "radium",+ "tap",+ "wyz",+]+[[package]]name = "block2"version = "0.6.2"@@ -159,6 +184,12 @@ version = "3.20.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"+[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"+[[package]]name = "bytes"version = "1.12.1"@@ -220,6 +251,17 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"+[[package]]+name = "chacha20"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "rand_core",+]+[[package]]name = "chrono"version = "0.4.45"@@ -274,6 +316,30 @@ version = "0.8.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"+[[package]]+name = "cpufeatures"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"+dependencies = [+ "libc",+]++[[package]]+name = "crc"+version = "3.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"+dependencies = [+ "crc-catalog",+]++[[package]]+name = "crc-catalog"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"+[[package]]name = "crc32fast"version = "1.5.0"@@ -384,6 +450,18 @@ dependencies = ["litrs",]+[[package]]+name = "enum_dispatch"+version = "0.3.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd"+dependencies = [+ "once_cell",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "env_filter"version = "2.0.0"@@ -448,6 +526,12 @@ dependencies = ["percent-encoding",]+[[package]]+name = "funty"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"+[[package]]name = "futures-channel"version = "0.3.33"@@ -578,6 +662,18 @@ dependencies = ["wasi",]+[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+ "rand_core",+]+[[package]]name = "gio"version = "0.22.8"@@ -1002,6 +1098,35 @@ version = "0.2.189"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"+[[package]]+name = "libwifi"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d46bfdeb37cc498135404e8b74f9fab746e159432a6a58725d50948805d2d67c"+dependencies = [+ "bitvec",+ "byteorder",+ "crc",+ "enum_dispatch",+ "libwifi_macros",+ "log",+ "nom",+ "rand",+ "strum_macros",+ "thiserror",+]++[[package]]+name = "libwifi_macros"+version = "0.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f5cf9340ba39a76234195bac38ab571abeb8cb91cf4eec372376fe359197c49"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 1.0.109",+]+[[package]]name = "litemap"version = "0.8.2"@@ -1058,12 +1183,30 @@ dependencies = ["memoffset",]+[[package]]+name = "nom"+version = "8.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"+dependencies = [+ "memchr",+]+[[package]]name = "num-conv"version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"+[[package]]+name = "num-integer"+version = "0.1.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"+dependencies = [+ "num-traits",+]+[[package]]name = "num-traits"version = "0.2.19"@@ -1189,6 +1332,12 @@ dependencies = ["unicode-ident",]+[[package]]+name = "quick-error"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"+[[package]]name = "quote"version = "1.0.47"@@ -1198,6 +1347,46 @@ dependencies = ["proc-macro2",]+[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "radiotap"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e50757032799a2a41ed705169a87efea63fb0babfe69f418b3f5630df4c8394a"+dependencies = [+ "bitops",+ "byteorder",+ "quick-error",+]++[[package]]+name = "radium"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"++[[package]]+name = "rand"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"+dependencies = [+ "chacha20",+ "getrandom 0.4.3",+ "rand_core",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"+[[package]]name = "regex"version = "1.13.1"@@ -1235,7 +1424,7 @@ checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"dependencies = ["cc","cfg-if",- "getrandom",+ "getrandom 0.2.17","libc","untrusted","windows-sys 0.52.0",@@ -1385,12 +1574,35 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"+[[package]]+name = "strum_macros"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "subtle"version = "2.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]+name = "syn"+version = "1.0.109"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]+[[package]]name = "syn"version = "2.0.119"@@ -1437,6 +1649,12 @@ dependencies = ["version-compare",]+[[package]]+name = "tap"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"+[[package]]name = "target-lexicon"version = "0.13.5"@@ -1865,6 +2083,15 @@ version = "0.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"+[[package]]+name = "wyz"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"+dependencies = [+ "tap",+]+[[package]]name = "yoke"version = "0.8.3"diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.tomlindex 1c61da7..7604ff8 100644--- a/crates/agent/Cargo.toml+++ b/crates/agent/Cargo.toml@@ -22,6 +22,10 @@ nix.workspace = truelazy_static.workspace = truecsv = "1.4"ctrlc = { version = "3.5", features = ["termination"] }+libwifi = "0.5"+radiotap = "1"+chrono = "0.4"+libc = "0.2"[build-dependencies]serde = { version = "1", features = ["derive"] }diff --git a/crates/agent/src/backend/app.rs b/crates/agent/src/backend/app.rsindex c44c16e..60c8d99 100644--- a/crates/agent/src/backend/app.rs+++ b/crates/agent/src/backend/app.rs@@ -16,7 +16,6 @@ pub fn app_cleanup() {restore_network_manager().ok();- std::fs::remove_file(get_live_scan_path() + get_csv_ext()).ok();std::fs::remove_file(get_live_scan_path() + get_cap_ext()).ok();std::fs::remove_file(get_old_scan_path() + get_cap_ext()).ok();}diff --git a/crates/agent/src/backend/mod.rs b/crates/agent/src/backend/mod.rsindex fb52504..0352844 100644--- a/crates/agent/src/backend/mod.rs+++ b/crates/agent/src/backend/mod.rs@@ -2,7 +2,9 @@ pub mod app;pub mod capture;pub mod deauth;pub mod interface;+pub mod pcap;pub mod scan;+pub mod sniffer;pub mod vendors;pub use app::*;diff --git a/crates/agent/src/backend/pcap.rs b/crates/agent/src/backend/pcap.rsnew file mode 100644index 0000000..4e0a826--- /dev/null+++ b/crates/agent/src/backend/pcap.rs@@ -0,0 +1,61 @@+//! Minimal pcap writer for the native capture engine.+//!+//! The frames we pull off the monitor interface are radiotap-prefixed 802.11+//! frames, so the file is written with link-type+//! `LINKTYPE_IEEE802_11_RADIOTAP` (127) — the same format `airodump-ng`+//! produced. This keeps everything downstream (handshake detection via+//! `aircrack-ng`, `mergecap`, and the GUI capture export) working unchanged.+//!+//! Only the classic libpcap format is implemented (global header + per-record+//! header + raw bytes); that is all `aircrack-ng`/`mergecap` need and it avoids+//! pulling in a libpcap dependency.++use std::fs::File;+use std::io::{self, BufWriter, Write};+use std::path::Path;+use std::time::{SystemTime, UNIX_EPOCH};++const LINKTYPE_IEEE802_11_RADIOTAP: u32 = 127;+const SNAPLEN: u32 = 65535;+const PCAP_MAGIC: u32 = 0xa1b2_c3d4;++/// A writer appending captured frames to a libpcap file.+pub struct PcapWriter {+ file: BufWriter<File>,+}++impl PcapWriter {+ /// Create (truncating) a capture file at `path` and write the global header.+ pub fn create<P: AsRef<Path>>(path: P) -> io::Result<Self> {+ let mut file = BufWriter::new(File::create(path)?);++ file.write_all(&PCAP_MAGIC.to_ne_bytes())?;+ file.write_all(&2u16.to_ne_bytes())?; // version major+ file.write_all(&4u16.to_ne_bytes())?; // version minor+ file.write_all(&0i32.to_ne_bytes())?; // thiszone+ file.write_all(&0u32.to_ne_bytes())?; // sigfigs+ file.write_all(&SNAPLEN.to_ne_bytes())?; // snaplen+ file.write_all(&LINKTYPE_IEEE802_11_RADIOTAP.to_ne_bytes())?; // network+ file.flush()?;++ Ok(Self { file })+ }++ /// Append one captured frame (radiotap header included) as a pcap record.+ ///+ /// Flushes immediately: the live capture is read by handshake detection while+ /// the scan is still running, so records must hit the file as they arrive.+ pub fn write_frame(&mut self, frame: &[u8]) -> io::Result<()> {+ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default();+ let len = frame.len() as u32;++ self.file.write_all(&(now.as_secs() as u32).to_ne_bytes())?;+ self.file.write_all(&now.subsec_micros().to_ne_bytes())?;+ self.file.write_all(&len.to_ne_bytes())?; // captured length+ self.file.write_all(&len.to_ne_bytes())?; // original length+ self.file.write_all(frame)?;+ self.file.flush()+ }+}diff --git a/crates/agent/src/backend/scan.rs b/crates/agent/src/backend/scan.rsindex 8968fbc..4118e0b 100644--- a/crates/agent/src/backend/scan.rs+++ b/crates/agent/src/backend/scan.rs@@ -1,71 +1,14 @@use std::collections::HashMap;use std::path::Path;-use std::process::{Command, Stdio};+use std::sync::Arc;use std::sync::MutexGuard;+use std::sync::atomic::{AtomicBool, Ordering};use super::get_attack_pool;+use super::sniffer;use crate::globals::*;use airgorah_common::types::*;-use serde::Deserialize;--use nix::sys::signal::{Signal, kill};-use nix::unistd::Pid;--/// Represents the AP section of the csv file generated by airodump-#[derive(Debug, Deserialize)]-struct RawAP {- #[serde(rename = "BSSID")]- bssid: String,- #[serde(rename = " First time seen")]- first_time_seen: String,- #[serde(rename = " Last time seen")]- last_time_seen: String,- #[serde(rename = " channel")]- channel: String,- #[serde(rename = " Speed")]- speed: String,- #[serde(rename = " Privacy")]- privacy: String,- #[serde(rename = " Cipher")]- _cipher: String,- #[serde(rename = " Authentication")]- _authentication: String,- #[serde(rename = " Power")]- power: String,- #[serde(rename = " # beacons")]- _beacons: String,- #[serde(rename = " # IV")]- _iv: String,- #[serde(rename = " LAN IP")]- _lan_ip: String,- #[serde(rename = " ID-length")]- id_length: String,- #[serde(rename = " ESSID")]- essid: String,- #[serde(rename = " Key")]- _key: String,-}--/// Represents the Client section of the csv file generated by airodump-#[derive(Debug, Deserialize)]-struct RawClient {- #[serde(rename = "Station MAC")]- station_mac: String,- #[serde(rename = " First time seen")]- first_time_seen: String,- #[serde(rename = " Last time seen")]- last_time_seen: String,- #[serde(rename = " Power")]- power: String,- #[serde(rename = " # packets")]- packets: String,- #[serde(rename = " BSSID")]- bssid: String,- #[serde(rename = " Probed ESSIDs")]- probes: String,-}-#[derive(thiserror::Error, Debug)]pub enum ScanError {#[error("Could not setup scan process: no band selected")]@@ -73,17 +16,14 @@ pub enum ScanError {#[error("Input/Output error: {0}")]IoError(#[from] std::io::Error),-- #[error("Kill error: errno code: {0}")]- KillError(#[from] nix::errno::Errno),}/// Check if a scan is currently runningpub fn is_scan_process() -> bool {- SCAN_PROC.lock().unwrap().is_some()+ SCAN_HANDLE.lock().unwrap().is_some()}-/// Set the scan process+/// Start (or restart) the native capture thread.pub fn set_scan_process(iface: &str,ghz_2_4: bool,@@ -96,46 +36,19 @@ pub fn set_scan_process(stop_scan_process()?;- let live_scan_path = get_live_scan_path();- let mut proc_args = vec![- iface,- "-a",- "--output-format",- "csv,cap",- "-w",- &live_scan_path,- "--write-interval",- "1",- ];-- let mut band = String::new();+ let channels = sniffer::build_channel_list(ghz_2_4, ghz_5, channel_filter.as_deref());- if ghz_5 {- band += "a";- }-- if ghz_2_4 {- band += "bg";- }+ let stop = Arc::new(AtomicBool::new(false));+ let thread_stop = stop.clone();+ let thread_iface = iface.to_string();+ let handle = std::thread::spawn(move || {+ sniffer::run(thread_iface, channels, thread_stop);+ });- proc_args.push("--band");- proc_args.push(&band);-- let channels;-- if let Some(ref filter) = channel_filter {- channels = filter;-- proc_args.push("--channel");- proc_args.push(channels);- }-- let child = Command::new("airodump-ng")- .args(proc_args)- .stdout(Stdio::null())- .spawn()?;-- SCAN_PROC.lock().unwrap().replace(child);+ SCAN_HANDLE+ .lock()+ .unwrap()+ .replace(ScanHandle { stop, handle });log::info!("scan started: 2.4ghz: {ghz_2_4}, 5ghz: {ghz_5}, channel filter: {channel_filter:?}"@@ -144,25 +57,21 @@ pub fn set_scan_process(Ok(())}-/// Stop the scan process+/// Stop the capture thread and fold its capture into the accumulated one.pub fn stop_scan_process() -> Result<(), ScanError> {- if let Some(child) = SCAN_PROC.lock().unwrap().as_mut() {- let child_pid = Pid::from_raw(child.id() as i32);-- kill(child_pid, Signal::SIGTERM)?;-- log::info!("scan stopped, sent SIGTERM to pid {child_pid}");-- child.wait()?;+ let handle = SCAN_HANDLE.lock().unwrap().take();+ if let Some(scan) = handle {+ scan.stop.store(true, Ordering::Relaxed);+ let _ = scan.handle.join();+ log::info!("scan stopped");}- SCAN_PROC.lock().unwrap().take();-+ // Merge the just-finished live capture into the accumulated old capture, so a+ // handshake captured across several scan restarts (e.g. the deauth "park on+ // channel" behaviour) ends up in a single file.let old_path_exists = Path::new(&(get_old_scan_path() + get_cap_ext())).exists();let live_path_exists = Path::new(&(get_live_scan_path() + get_cap_ext())).exists();- std::fs::remove_file(get_live_scan_path() + get_csv_ext()).ok();-if !live_path_exists {return Ok(());}@@ -205,164 +114,24 @@ pub fn reset_scan_data() {get_unlinked_clients().clear();}-/// Get the data captured from airodump.+/// Snapshot of the discovered access points for the GUI.+///+/// The capture thread maintains [`APS`] live, so this just clones it, overlaying+/// any AP currently under attack (which must stay visible even if it stopped+/// beaconing).pub fn get_airodump_data() -> HashMap<String, AP> {let mut aps: HashMap<String, AP> = HashMap::new();- for attacked_ap in get_attack_pool().iter() {- aps.insert(attacked_ap.0.clone(), attacked_ap.1.0.clone());+ let attacked: Vec<AP> = get_attack_pool()+ .values()+ .map(|(ap, _)| ap.clone())+ .collect();+ for ap in attacked {+ aps.insert(ap.bssid.clone(), ap);}- let mut glob_aps = get_aps();-- for ap in glob_aps.iter() {- aps.insert(ap.0.clone(), ap.1.clone());- }-- let full_path = get_live_scan_path() + get_csv_ext();- let csv_file = match std::fs::read_to_string(full_path) {- Ok(file) => file,- Err(_) => return aps,- };-- let file_parts: Vec<&str> = csv_file.split("\r\n\r\n").collect();- let ap_part = if !file_parts.is_empty() {- file_parts[0]- } else {- ""- };- let cli_part = if file_parts.len() >= 2 {- file_parts[1]- } else {- ""- };-- let mut ap_reader = csv::Reader::from_reader(ap_part.as_bytes());- let mut cli_reader = csv::Reader::from_reader(cli_part.as_bytes());-- for result in ap_reader.deserialize::<RawAP>().flatten() {- let channel_nb = result.channel.trim_start().parse::<i32>().unwrap_or(-1);- let band = if channel_nb > 14 {- "5 GHz".to_string()- } else {- "2.4 GHz".to_string()- };- let bssid = result.bssid.trim_start().to_string();- let mut essid = result.essid.trim_start().to_string();- let mut hidden = false;-- let old_ap_data = glob_aps.get(&bssid);-- if essid.is_empty() {- hidden = true;- essid = format!("[Hidden] (length: {})", result.id_length.trim_start());-- if let Some(old_ap_data) = old_ap_data- && !old_ap_data.essid.starts_with("[Hidden] (length:")- {- essid = old_ap_data.essid.clone();- }- }-- let old_data = aps.insert(- bssid.clone(),- AP {- essid,- bssid: bssid.clone(),- band,- channel: result.channel.trim_start().to_string(),- speed: result.speed.trim_start().to_string(),- power: result.power.trim_start().to_string(),- privacy: match result.privacy.trim_start() {- "" => "Unknown".to_string(),- e => {- let array = e- .split_whitespace()- .map(|s| s.to_string())- .collect::<Vec<String>>();- array.first().unwrap_or(&"Unknown".to_string()).to_string()- }- },- hidden,- handshake: {- match old_ap_data {- Some(ap) => ap.handshake,- None => false,- }- },- saved_handshake: match old_ap_data {- Some(ap) => ap.saved_handshake.clone(),- None => None,- },- first_time_seen: {- match old_ap_data {- Some(ap) => ap.first_time_seen.clone(),- None => result.first_time_seen.trim_start().to_string(),- }- },- last_time_seen: result.last_time_seen.trim_start().to_string(),- clients: HashMap::new(),- },- );-- if let Some(ap) = old_data {- aps.get_mut(&bssid).unwrap().clients = ap.clients;- }- }-- for result in cli_reader.deserialize::<RawClient>().flatten() {- let mac = result.station_mac.trim_start().to_string();- let vendor = super::find_vendor(&mac);-- match aps.get_mut(result.bssid.trim_start()) {- Some(ap) => {- let old_client = ap.clients.get(&mac);-- ap.clients.insert(- mac.clone(),- Client {- mac,- packets: result.packets.trim_start().to_string(),- power: result.power.trim_start().to_string(),- first_time_seen: {- match old_client {- Some(client) => client.first_time_seen.clone(),- None => result.first_time_seen.trim_start().to_string(),- }- },- last_time_seen: result.last_time_seen.trim_start().to_string(),- vendor: vendor.clone(),- probes: result.probes.trim_start().to_string(),- },- );- }- None => {- let unlinked_clients = get_unlinked_clients().clone();- let old_client = unlinked_clients.get(&mac);-- get_unlinked_clients().insert(- mac.clone(),- Client {- mac,- packets: result.packets.trim_start().to_string(),- power: result.power.trim_start().to_string(),- first_time_seen: {- match old_client {- Some(client) => client.first_time_seen.clone(),- None => result.first_time_seen.trim_start().to_string(),- }- },- last_time_seen: result.last_time_seen.trim_start().to_string(),- vendor: vendor.clone(),- probes: result.probes.trim_start().to_string(),- },- );- }- }- }-- for (bssid, ap) in aps.iter() {- glob_aps.insert(bssid.clone(), ap.clone());+ for (bssid, ap) in get_aps().iter() {+ aps.insert(bssid.clone(), ap.clone());}aps@@ -380,10 +149,6 @@ pub fn get_cap_ext() -> &'static str {"-01.cap"}-pub fn get_csv_ext() -> &'static str {- "-01.csv"-}-pub fn get_live_scan_path() -> String {format!("{}-{}", LIVE_SCAN_PATH, std::process::id())}diff --git a/crates/agent/src/backend/sniffer.rs b/crates/agent/src/backend/sniffer.rsnew file mode 100644index 0000000..53559c0--- /dev/null+++ b/crates/agent/src/backend/sniffer.rs@@ -0,0 +1,535 @@+//! Native 802.11 capture engine — the in-house replacement for `airodump-ng`.+//!+//! A capture thread opens a raw `AF_PACKET` socket on the monitor interface,+//! hops (or parks on) the requested channels, and for every frame:+//! * appends it to the live capture file (radiotap + 802.11, see [`super::pcap`]),+//! * parses it and folds the result into the shared [`APS`] / [`UNLINKED_CLIENTS`]+//! state that the GUI polls.+//!+//! Frame parsing is delegated to `radiotap` (to strip the radiotap header and read+//! signal/flags) and `libwifi` (to decode the 802.11 frame). The thread is stopped+//! by raising the `stop` flag and joining it (see [`super::scan`]).++use super::find_vendor;+use super::pcap::PcapWriter;+use super::scan::{get_aps, get_cap_ext, get_live_scan_path, get_unlinked_clients};++use airgorah_common::types::{AP, Client};++use libwifi::Addresses;+use libwifi::Frame;+use libwifi::frame::components::{DataHeader, ManagementHeader, RsnAkmSuite, StationInfo};++use std::collections::HashMap;+use std::ffi::CString;+use std::io;+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};+use std::time::{Duration, Instant};++/// 2.4 GHz channels scanned when the band is enabled without a channel filter.+const CHANNELS_2_4: &[u32] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];++/// 5 GHz channels scanned when the band is enabled without a channel filter.+/// DFS channels are included; the card may refuse some depending on the+/// regulatory domain, in which case that hop is simply skipped.+const CHANNELS_5: &[u32] = &[+ 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144,+ 149, 153, 157, 161, 165,+];++/// How long to dwell on each channel while hopping.+const HOP_INTERVAL: Duration = Duration::from_millis(250);++/// Resolve the channels to visit from the enabled bands, or from an explicit+/// comma-separated channel filter when one is given.+pub fn build_channel_list(ghz_2_4: bool, ghz_5: bool, filter: Option<&str>) -> Vec<u32> {+ if let Some(filter) = filter {+ return filter+ .split_terminator(',')+ .filter_map(|c| c.parse::<u32>().ok())+ .collect();+ }++ let mut channels = Vec::new();+ if ghz_2_4 {+ channels.extend_from_slice(CHANNELS_2_4);+ }+ if ghz_5 {+ channels.extend_from_slice(CHANNELS_5);+ }+ channels+}++/// Capture-thread body. Runs until `stop` is raised.+pub fn run(iface: String, channels: Vec<u32>, stop: Arc<AtomicBool>) {+ let socket = match open_capture_socket(&iface) {+ Ok(socket) => socket,+ Err(e) => {+ log::error!("scan: could not open capture socket on {iface}: {e}");+ return;+ }+ };++ let mut pcap = match PcapWriter::create(get_live_scan_path() + get_cap_ext()) {+ Ok(pcap) => pcap,+ Err(e) => {+ log::error!("scan: could not create capture file: {e}");+ return;+ }+ };++ let hopping = channels.len() > 1;+ let mut chan_idx = 0;+ let mut current_channel = channels.first().copied().unwrap_or(0);+ if let Some(&channel) = channels.first() {+ set_channel(&iface, channel);+ }+ let mut last_hop = Instant::now();++ let mut buf = [0u8; 8192];++ while !stop.load(Ordering::Relaxed) {+ if hopping && last_hop.elapsed() >= HOP_INTERVAL {+ chan_idx = (chan_idx + 1) % channels.len();+ current_channel = channels[chan_idx];+ set_channel(&iface, current_channel);+ last_hop = Instant::now();+ }++ match recv_frame(&socket, &mut buf) {+ Ok(0) => {}+ Ok(n) => {+ let frame = &buf[..n];+ if let Err(e) = pcap.write_frame(frame) {+ log::error!("scan: capture write failed: {e}");+ break;+ }+ process_frame(frame, current_channel);+ }+ // A receive timeout (so the loop can hop / observe `stop`) surfaces as+ // EAGAIN/EWOULDBLOCK; EINTR is a benign interruption. Anything else is fatal.+ Err(e) => match e.raw_os_error() {+ Some(code)+ if code == libc::EAGAIN || code == libc::EWOULDBLOCK || code == libc::EINTR => {+ }+ _ => {+ log::error!("scan: capture recv failed: {e}");+ break;+ }+ },+ }+ }++ log::info!("scan: capture thread on {iface} stopped");+}++// --- raw AF_PACKET socket ---------------------------------------------------++/// Open a raw `AF_PACKET` socket capturing every frame on `iface`, with a short+/// receive timeout so the capture loop can hop channels and observe the stop flag.+fn open_capture_socket(iface: &str) -> io::Result<OwnedFd> {+ let eth_p_all = (libc::ETH_P_ALL as u16).to_be();++ // SAFETY: standard socket(2) call; the returned fd is immediately wrapped in an+ // OwnedFd so it is closed on drop.+ let fd = unsafe { libc::socket(libc::AF_PACKET, libc::SOCK_RAW, eth_p_all as i32) };+ if fd < 0 {+ return Err(io::Error::last_os_error());+ }+ let socket = unsafe { OwnedFd::from_raw_fd(fd) };++ let ifindex = interface_index(iface)?;++ let mut addr: libc::sockaddr_ll = unsafe { std::mem::zeroed() };+ addr.sll_family = libc::AF_PACKET as u16;+ addr.sll_protocol = eth_p_all;+ addr.sll_ifindex = ifindex as i32;++ // SAFETY: bind(2) with a correctly sized sockaddr_ll.+ let ret = unsafe {+ libc::bind(+ socket.as_raw_fd(),+ &addr as *const libc::sockaddr_ll as *const libc::sockaddr,+ std::mem::size_of::<libc::sockaddr_ll>() as libc::socklen_t,+ )+ };+ if ret < 0 {+ return Err(io::Error::last_os_error());+ }++ let timeout = libc::timeval {+ tv_sec: 0,+ tv_usec: 100_000,+ };+ // SAFETY: setsockopt(2) with a correctly sized timeval.+ let ret = unsafe {+ libc::setsockopt(+ socket.as_raw_fd(),+ libc::SOL_SOCKET,+ libc::SO_RCVTIMEO,+ &timeout as *const libc::timeval as *const libc::c_void,+ std::mem::size_of::<libc::timeval>() as libc::socklen_t,+ )+ };+ if ret < 0 {+ return Err(io::Error::last_os_error());+ }++ Ok(socket)+}++/// Resolve an interface name to its kernel index.+fn interface_index(iface: &str) -> io::Result<u32> {+ let name = CString::new(iface).map_err(|_| {+ io::Error::new(io::ErrorKind::InvalidInput, "interface name contains a nul")+ })?;+ // SAFETY: if_nametoindex(3) reads a valid C string; returns 0 on error.+ let index = unsafe { libc::if_nametoindex(name.as_ptr()) };+ if index == 0 {+ return Err(io::Error::last_os_error());+ }+ Ok(index)+}++/// Receive one frame, returning the number of bytes read (0 on an empty read).+fn recv_frame(socket: &OwnedFd, buf: &mut [u8]) -> io::Result<usize> {+ // SAFETY: recv(2) into a buffer of the given length.+ let n = unsafe {+ libc::recv(+ socket.as_raw_fd(),+ buf.as_mut_ptr() as *mut libc::c_void,+ buf.len(),+ 0,+ )+ };+ if n < 0 {+ return Err(io::Error::last_os_error());+ }+ Ok(n as usize)+}++/// Tune the interface to a channel via `iw`. Failures (e.g. a regulatory-blocked+/// DFS channel) are non-fatal — the hop is just skipped.+fn set_channel(iface: &str, channel: u32) -> bool {+ std::process::Command::new("iw")+ .args(["dev", iface, "set", "channel", &channel.to_string()])+ .output()+ .map(|out| out.status.success())+ .unwrap_or(false)+}++// --- frame processing -------------------------------------------------------++/// Strip radiotap, decode the 802.11 frame, and fold it into the shared state.+/// `current_channel` is the channel the card is tuned to, used as a fallback when+/// a beacon does not carry a DS-parameter channel (common on 5 GHz).+fn process_frame(raw: &[u8], current_channel: u32) {+ let (radiotap, body) = match radiotap::Radiotap::parse(raw) {+ Ok(parsed) => parsed,+ Err(_) => return,+ };++ if radiotap.flags.as_ref().is_some_and(|f| f.bad_fcs) {+ return;+ }+ let fcs_included = radiotap.flags.as_ref().is_some_and(|f| f.fcs);+ let signal = radiotap.antenna_signal.map(|s| s.value as i32);++ let frame = match libwifi::parse_frame(body, fcs_included) {+ Ok(frame) => frame,+ Err(_) => return,+ };++ match frame {+ Frame::Beacon(b) => update_ap(+ &b.header,+ b.capability_info,+ &b.station_info,+ signal,+ current_channel,+ ),+ Frame::ProbeResponse(b) => update_ap(+ &b.header,+ b.capability_info,+ &b.station_info,+ signal,+ current_channel,+ ),+ Frame::ProbeRequest(p) => record_probe(&p.header, &p.station_info, signal),+ Frame::Data(d) => record_data_client(&d.header, signal),+ Frame::QosData(d) => record_data_client(&d.header, signal),+ Frame::NullData(d) => record_data_client(&d.header, signal),+ Frame::QosNull(d) => record_data_client(&d.header, signal),+ _ => {}+ }+}++/// Fold a beacon / probe-response into the AP table.+fn update_ap(+ header: &ManagementHeader,+ capability_info: u16,+ info: &StationInfo,+ signal: Option<i32>,+ current_channel: u32,+) {+ let bssid = match header.bssid() {+ Some(mac) => mac.to_long_string(),+ None => return,+ };+ if !is_unicast(&bssid) {+ return;+ }++ let channel = info+ .channel()+ .map(i32::from)+ .unwrap_or(current_channel as i32);+ let band = band_of(channel);+ let privacy = classify_privacy(capability_info, info);+ let speed = max_rate(info);+ let (essid, hidden) = essid_of(info);+ let power = signal.map(|s| s.to_string()).unwrap_or_default();+ let now = timestamp();++ let mut aps = get_aps();+ match aps.get_mut(&bssid) {+ Some(ap) => {+ // Keep a real ESSID we already learned rather than overwriting it with a+ // later hidden beacon.+ if !hidden {+ ap.essid = essid;+ ap.hidden = false;+ } else if ap.essid.is_empty() || ap.essid.starts_with("[Hidden] (length:") {+ ap.essid = essid;+ ap.hidden = true;+ }+ ap.channel = channel.to_string();+ ap.band = band;+ ap.privacy = privacy;+ if !speed.is_empty() {+ ap.speed = speed;+ }+ if !power.is_empty() {+ ap.power = power;+ }+ ap.last_time_seen = now;+ }+ None => {+ aps.insert(+ bssid.clone(),+ AP {+ essid,+ bssid,+ band,+ channel: channel.to_string(),+ speed,+ power,+ privacy,+ hidden,+ handshake: false,+ saved_handshake: None,+ first_time_seen: now.clone(),+ last_time_seen: now,+ clients: HashMap::new(),+ },+ );+ }+ }+}++/// Record a station seen in a probe request, along with the ESSID it probed for.+fn record_probe(header: &ManagementHeader, info: &StationInfo, signal: Option<i32>) {+ let station = header.address_2.to_long_string();+ if !is_unicast(&station) {+ return;+ }++ let probe = match info.essid() {+ Some(essid) if !essid.starts_with("<hidden") && !essid.is_empty() => Some(essid),+ _ => None,+ };++ record_client(&station, None, signal, probe);+}++/// Record a station seen exchanging data with an AP.+fn record_data_client(header: &DataHeader, signal: Option<i32>) {+ let fc = &header.frame_control;+ // ra() is address_1, ta() is address_2. In infrastructure BSS the AP is the+ // "distribution system" side, so the wireless station is the transmitter on+ // uplink and the receiver on downlink. Ad-hoc (neither bit) and WDS (both) are+ // ignored.+ let (station, bssid) = if fc.to_ds() && !fc.from_ds() {+ (header.ta(), header.ra())+ } else if fc.from_ds() && !fc.to_ds() {+ (header.ra(), header.ta())+ } else {+ return;+ };++ let station = station.to_long_string();+ let bssid = bssid.to_long_string();+ if !is_unicast(&station) {+ return;+ }++ record_client(&station, Some(&bssid), signal, None);+}++/// Insert or update a client, attaching it to a known AP when possible and+/// otherwise keeping it in the unlinked set (mirroring airodump's two lists).+fn record_client(station: &str, bssid: Option<&str>, signal: Option<i32>, probe: Option<String>) {+ let now = timestamp();+ let vendor = find_vendor(station);+ let power = signal.map(|s| s.to_string()).unwrap_or_default();++ let mut aps = get_aps();++ // Attach under the AP named by a data frame, or under the AP this station is+ // already listed with (so a later probe request updates the right record).+ let target = match bssid {+ Some(bssid) if aps.contains_key(bssid) => Some(bssid.to_string()),+ Some(_) | None => aps+ .iter()+ .find(|(_, ap)| ap.clients.contains_key(station))+ .map(|(bssid, _)| bssid.clone()),+ };++ if let Some(bssid) = target {+ let ap = aps.get_mut(&bssid).expect("target AP present");+ upsert_client(&mut ap.clients, station, &power, &vendor, &now, probe);+ drop(aps);+ get_unlinked_clients().remove(station);+ return;+ }++ drop(aps);+ upsert_client(+ &mut get_unlinked_clients(),+ station,+ &power,+ &vendor,+ &now,+ probe,+ );+}++/// Insert a new client record or refresh an existing one (bumping its packet+/// count, power, last-seen time, and merging in a newly probed ESSID).+fn upsert_client(+ clients: &mut HashMap<String, Client>,+ mac: &str,+ power: &str,+ vendor: &str,+ now: &str,+ probe: Option<String>,+) {+ match clients.get_mut(mac) {+ Some(client) => {+ client.packets = (client.packets.parse::<u64>().unwrap_or(0) + 1).to_string();+ if !power.is_empty() {+ client.power = power.to_string();+ }+ client.last_time_seen = now.to_string();+ if let Some(probe) = probe+ && !probe.is_empty()+ && !client.probes.split(", ").any(|p| p == probe)+ {+ if client.probes.is_empty() {+ client.probes = probe;+ } else {+ client.probes = format!("{}, {probe}", client.probes);+ }+ }+ }+ None => {+ clients.insert(+ mac.to_string(),+ Client {+ mac: mac.to_string(),+ packets: "1".to_string(),+ power: power.to_string(),+ first_time_seen: now.to_string(),+ last_time_seen: now.to_string(),+ vendor: vendor.to_string(),+ probes: probe.unwrap_or_default(),+ },+ );+ }+ }+}++// --- field helpers ----------------------------------------------------------++/// Human-readable band label from a channel number (matches the previous CSV path).+fn band_of(channel: i32) -> String {+ if channel > 14 { "5 GHz" } else { "2.4 GHz" }.to_string()+}++/// Derive airgorah's single-token privacy label from the beacon's security IEs.+fn classify_privacy(capability_info: u16, info: &StationInfo) -> String {+ if let Some(rsn) = &info.rsn_information {+ if rsn.akm_suites.contains(&RsnAkmSuite::SAE) {+ return "WPA3".to_string();+ }+ return "WPA2".to_string();+ }+ if info.wpa_info.is_some() {+ return "WPA".to_string();+ }+ // Capability "Privacy" bit (bit 4) without RSN/WPA means legacy WEP.+ if capability_info & 0x0010 != 0 {+ return "WEP".to_string();+ }+ "OPN".to_string()+}++/// Highest advertised supported rate in Mbit/s, as a string (empty if unknown).+fn max_rate(info: &StationInfo) -> String {+ let mut max = 0.0f32;+ for rate in &info.supported_rates {+ if rate.rate > max {+ max = rate.rate;+ }+ }+ if let Some(extended) = &info.extended_supported_rates {+ for rate in extended {+ if rate.rate > max {+ max = rate.rate;+ }+ }+ }+ if max <= 0.0 {+ String::new()+ } else {+ (max as u32).to_string()+ }+}++/// The ESSID and whether the network is hidden, in the format the GUI expects.+fn essid_of(info: &StationInfo) -> (String, bool) {+ match info.essid() {+ Some(essid) if !essid.starts_with("<hidden") && !essid.is_empty() => (essid, false),+ _ => {+ let length = info.ssid_length.unwrap_or(0);+ (format!("[Hidden] (length: {length})"), true)+ }+ }+}++/// A real, individually-addressed MAC (not broadcast, multicast, or all-zero).+fn is_unicast(mac: &str) -> bool {+ if mac == "00:00:00:00:00:00" {+ return false;+ }+ u8::from_str_radix(&mac[0..2], 16)+ .map(|first_octet| first_octet & 0x01 == 0)+ .unwrap_or(false)+}++/// Current local time in airodump's `YYYY-MM-DD HH:MM:SS` format.+fn timestamp() -> String {+ chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string()+}diff --git a/crates/agent/src/globals.rs b/crates/agent/src/globals.rsindex fdab986..2c1b02d 100644--- a/crates/agent/src/globals.rs+++ b/crates/agent/src/globals.rs@@ -1,7 +1,7 @@//! Privileged state owned by the agent.//!//! This is the half of the old monolithic `globals.rs` that manipulates or holds-//! handles to privileged resources: the running `airodump` scan, the running+//! handles to privileged resources: the running native scan, the running//! `aireplay`/`mdk4` attacks, the accumulated scan data, and the interface/service//! state that must be restored on teardown.@@ -10,7 +10,10 @@ use airgorah_common::types::{AP, Client};use lazy_static::lazy_static;use std::collections::HashMap;use std::process::Child;+use std::sync::Arc;use std::sync::Mutex;+use std::sync::atomic::AtomicBool;+use std::thread::JoinHandle;/// Root-owned 0700 directory for the agent's scan/capture files.pub static CAPTURE_DIR: &str = "/var/lib/airgorah";@@ -29,10 +32,18 @@ pub enum AttackedClients {pub type AttackPool = HashMap<String, (AP, AttackedClients)>;+/// Handle to the running native capture thread. `stop` is raised to ask the+/// thread to exit; `handle` is joined to wait for it to finish flushing the+/// capture file. Replaces the old `airodump-ng` child process.+pub struct ScanHandle {+ pub stop: Arc<AtomicBool>,+ pub handle: JoinHandle<()>,+}+lazy_static! {pub static ref IFACE: Mutex<Option<String>> = Mutex::new(None);pub static ref IFACE_WAS_MONITOR: Mutex<bool> = Mutex::new(false);- pub static ref SCAN_PROC: Mutex<Option<Child>> = Mutex::new(None);+ pub static ref SCAN_HANDLE: Mutex<Option<ScanHandle>> = Mutex::new(None);pub static ref APS: Mutex<HashMap<String, AP>> = Mutex::new(HashMap::new());pub static ref UNLINKED_CLIENTS: Mutex<HashMap<String, Client>> = Mutex::new(HashMap::new());pub static ref ATTACK_POOL: Mutex<AttackPool> = Mutex::new(HashMap::new());diff --git a/crates/common/src/deps.rs b/crates/common/src/deps.rsindex 417674e..50ac8b6 100644--- a/crates/common/src/deps.rs+++ b/crates/common/src/deps.rs@@ -63,11 +63,6 @@ pub const TOOLS: &[Tool] = &[requirer: Requirer::Agent,optional: false,},- Tool {- name: "airodump-ng",- requirer: Requirer::Agent,- optional: false,- },Tool {name: "aireplay-ng",requirer: Requirer::Agent,