A WiFi security auditing software
feat: split GUI and privileged agent (#182)
Martin Olivierf21dab0fe8f9
diff --git a/.fpm b/.fpmindex 0cb84eb..9e7a2c6 100644--- a/.fpm+++ b/.fpm@@ -1,4 +1,4 @@--s dir ./target/debug/airgorah ./icons/app_icon.png package README.md LICENSE+-s dir ./target/debug/airgorah ./target/debug/airgorah-agent ./crates/gui/icons/app_icon.png package README.md LICENSE--name airgorah--license MIT--version 0.7.4@@ -17,10 +17,10 @@--depends adwaita-icon-themetarget/debug/airgorah=/usr/bin/airgorah-icons/app_icon.png=/usr/share/pixmaps/airgorah.png+target/debug/airgorah-agent=/usr/bin/airgorah-agent+crates/gui/icons/app_icon.png=/usr/share/pixmaps/airgorah.png-package/config.toml=/etc/airgorah/config.toml-package/.desktop=/usr/share/applications/airgorah.desktop+package/.desktop=/usr/share/applications/com.molivier.airgorah.desktoppackage/.policy=/usr/share/polkit-1/actions/org.freedesktop.policykit.airgorah.policyREADME.md=/usr/share/doc/airgorah/README.mddiff --git a/.github/FUNDING.yml b/.github/FUNDING.ymldeleted file mode 100644index 4db5de5..0000000--- a/.github/FUNDING.yml+++ /dev/null@@ -1,14 +0,0 @@-# These are supported funding model platforms--github: [martin-olivier]-patreon: # Replace with a single Patreon username-open_collective: # Replace with a single Open Collective username-ko_fi: # Replace with a single Ko-fi username-tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel-community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry-liberapay: # Replace with a single Liberapay username-issuehunt: # Replace with a single IssueHunt username-otechie: # Replace with a single Otechie username-lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry-polar: # Replace with a single Polar username-custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']diff --git a/.github/assets/illustration.png b/.github/assets/illustration.pngindex c4f587c..5f66c49 100755Binary files a/.github/assets/illustration.png and b/.github/assets/illustration.png differdiff --git a/Cargo.lock b/Cargo.lockindex c088af1..98c88d3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -21,9 +21,8 @@ dependencies = [name = "airgorah"version = "0.7.4"dependencies = [+ "airgorah-common","chrono",- "csv",- "ctrlc","env_logger","gtk4","lazy_static",@@ -32,10 +31,33 @@ dependencies = ["regex","serde","serde_json",- "sudo","thiserror","toml","ureq",+]++[[package]]+name = "airgorah-agent"+version = "0.7.4"+dependencies = [+ "airgorah-common",+ "csv",+ "ctrlc",+ "env_logger",+ "lazy_static",+ "log",+ "nix",+ "serde",+ "thiserror",+]++[[package]]+name = "airgorah-common"+version = "0.7.4"+dependencies = [+ "regex",+ "serde",+ "serde_json","which",]@@ -1033,6 +1055,7 @@ dependencies = ["cfg-if","cfg_aliases","libc",+ "memoffset",][[package]]@@ -1368,16 +1391,6 @@ version = "2.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"-[[package]]-name = "sudo"-version = "0.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "88bd84d4c082e18e37fef52c0088e4407dabcef19d23a607fb4b5ee03b7d5b83"-dependencies = [- "libc",- "log",-]-[[package]]name = "syn"version = "2.0.119"diff --git a/Cargo.toml b/Cargo.tomlindex c26ee6f..6dec9ef 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,35 +1,24 @@-[package]-name = "airgorah"+[workspace]+resolver = "3"+members = ["crates/common", "crates/agent", "crates/gui"]++[workspace.package]version = "0.7.4"edition = "2024"license = "MIT"-description = "A WiFi security auditing software mainly based on aircrack-ng tools suite"authors = ["Martin Olivier <[email protected]>"]homepage = "https://github.com/martin-olivier/airgorah"repository = "https://github.com/martin-olivier/airgorah"documentation = "https://github.com/martin-olivier/airgorah/wiki"-keywords = ["networking", "pentest", "aircrack-ng", "gui", "linux"]-readme = "README.md"-exclude = ["/.github", "/.fpm", "/Dockerfile"]-[dependencies]-gtk4 = { version = "0.11", features = ["v4_6"] }+[workspace.dependencies]+airgorah-common = { path = "crates/common" }serde = { version = "1", features = ["derive"] }serde_json = "1"-toml = "1"-csv = "1.4"-which = "8"-sudo = "0.6"-ctrlc = "3.5"regex = "1.13"-chrono = "0.4"-lazy_static = "1"-nix = { version = "0.31", features = ["signal"] }-ureq = { version = "3", features = ["json"] }log = "0.4"env_logger = "0.11"thiserror = "2"--[build-dependencies]-serde = { version = "1", features = ["derive"] }-csv = "1.4"+nix = { version = "0.31", features = ["signal", "socket", "user", "fs"] }+which = "8"+lazy_static = "1"diff --git a/LICENSE b/LICENSEindex f601f43..cfadf5d 100644--- a/LICENSE+++ b/LICENSE@@ -1,6 +1,6 @@MIT License-Copyright (c) 2025 Martin Olivier+Copyright (c) 2026 Martin OlivierPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealdiff --git a/README.md b/README.mdindex 652cdfb..b401d47 100644--- a/README.md+++ b/README.md@@ -1,5 +1,5 @@<h1 align="center">- <img src="icons/app_icon.png" width=100 height=100/><br>+ <img src="crates/gui/icons/app_icon.png" width=100 height=100/><br>Airgorah</h1><p align="center">@@ -32,7 +32,10 @@ It is written in Rust and uses [GTK4](https://github.com/gtk-rs/gtk4-rs) for the## Requirements-This software only works on `linux` and requires `root` privileges to run.+This software only works on `linux`. The graphical interface runs as a normal+user (so it works under both `X11` and `Wayland`). When a privileged operation is+needed, it launches a small privileged agent (`airgorah-agent`) via `polkit`,+which will prompt for authentication once.You will also need a wireless network card that supports `monitor mode` and `packet injection`.diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.tomlnew file mode 100644index 0000000..9c21093--- /dev/null+++ b/crates/agent/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "airgorah-agent"+version.workspace = true+edition.workspace = true+license.workspace = true+description = "Privileged agent process for airgorah: owns interface, scan, deauth and capture operations"++[[bin]]+name = "airgorah-agent"+path = "src/main.rs"++[dependencies]+airgorah-common.workspace = true+serde.workspace = true+log.workspace = true+env_logger.workspace = true+thiserror.workspace = true+nix.workspace = true+lazy_static.workspace = true+csv = "1.4"+ctrlc = { version = "3.5", features = ["termination"] }++[build-dependencies]+serde = { version = "1", features = ["derive"] }+csv = "1.4"diff --git a/build.rs b/crates/agent/build.rssimilarity index 96%rename from build.rsrename to crates/agent/build.rsindex f121d3d..e6e9b53 100644--- a/build.rs+++ b/crates/agent/build.rs@@ -11,7 +11,7 @@ struct RawVendors {}fn main() {- let csv_path = "package/vendors.csv";+ let csv_path = "vendors.csv";let file_content = std::fs::read_to_string(csv_path).expect("Unable to read CSV file");let parsed_data = parse_csv(&file_content);diff --git a/crates/agent/src/backend/app.rs b/crates/agent/src/backend/app.rsnew file mode 100644index 0000000..c44c16e--- /dev/null+++ b/crates/agent/src/backend/app.rs@@ -0,0 +1,22 @@+use super::*;++/// Stop the scan process, kill all the attack processes, disable monitor mode,+/// restore the network managers, and remove the files created by the app.+///+/// Runs agent-side because the agent owns every one of those resources. It is+/// invoked both on a clean shutdown and when the GUI disconnects unexpectedly, so+/// the wireless card is never left in monitor mode with an orphaned scan running.+pub fn app_cleanup() {+ stop_scan_process().ok();+ stop_all_deauth_attacks();++ if let Some(ref iface) = get_iface() {+ disable_monitor_mode(iface).ok();+ }++ 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/capture.rs b/crates/agent/src/backend/capture.rsnew file mode 100644index 0000000..fb5867a--- /dev/null+++ b/crates/agent/src/backend/capture.rs@@ -0,0 +1,55 @@+use super::*;+use airgorah_common::handshake::get_handshakes;+use std::io::{Read, Seek, SeekFrom};+use std::path::Path;++/// Update the handshake capture status of all APs by scanning the live/old+/// capture files. Runs agent-side because those files are root-owned.+pub fn update_handshakes() -> std::io::Result<()> {+ let paths: Vec<String> = [+ get_live_scan_path() + get_cap_ext(),+ get_old_scan_path() + get_cap_ext(),+ ]+ .into_iter()+ .filter(|path| Path::new(path).exists())+ .collect();++ if paths.is_empty() {+ return Ok(());+ }++ let handshakes = get_handshakes(&paths)?;++ let mut aps = get_aps();++ for (bssid, _) in handshakes {+ if let Some(ap) = aps.get_mut(&bssid) {+ ap.handshake = true;+ }+ }++ log::trace!("handshakes updated");++ Ok(())+}++/// Bytes per capture chunk. Kept well under the IPC frame cap: serde_json expands+/// a byte vector into a JSON array of integers (~3.6x).+const CHUNK_SIZE: u64 = 4 * 1024 * 1024;++/// Read one chunk of the accumulated capture at `offset`, returning the bytes and+/// whether it is the last chunk.+pub fn get_capture_chunk(offset: u64) -> std::io::Result<(Vec<u8>, bool)> {+ let mut file = std::fs::File::open(get_old_scan_path() + get_cap_ext())?;+ let len = file.metadata()?.len();++ let to_read = len.saturating_sub(offset).min(CHUNK_SIZE);+ let mut buf = vec![0u8; to_read as usize];++ file.seek(SeekFrom::Start(offset))?;+ file.read_exact(&mut buf)?;++ let last = offset + to_read >= len;++ Ok((buf, last))+}diff --git a/src/backend/deauth.rs b/crates/agent/src/backend/deauth.rsold mode 100755new mode 100644similarity index 84%rename from src/backend/deauth.rsrename to crates/agent/src/backend/deauth.rsindex 1205289..79e8ee0--- a/src/backend/deauth.rs+++ b/crates/agent/src/backend/deauth.rs@@ -1,5 +1,5 @@use crate::globals::*;-use crate::types::*;+use airgorah_common::types::*;use std::process::{Command, Stdio};use std::sync::MutexGuard;@@ -119,3 +119,22 @@ pub fn stop_all_deauth_attacks() {pub fn get_attack_pool() -> MutexGuard<'static, AttackPool> {ATTACK_POOL.lock().unwrap()}++/// Project the live attack pool onto its serializable wire representation.+pub fn get_attack_states() -> Vec<AttackState> {+ get_attack_pool()+ .iter()+ .map(|(_bssid, (ap, target))| {+ let target = match target {+ AttackedClients::All(_) => AttackTarget::All,+ AttackedClients::Selection(list) => {+ AttackTarget::Selection(list.iter().map(|(mac, _)| mac.clone()).collect())+ }+ };+ AttackState {+ ap: ap.clone(),+ target,+ }+ })+ .collect()+}diff --git a/src/backend/interface.rs b/crates/agent/src/backend/interface.rssimilarity index 73%rename from src/backend/interface.rsrename to crates/agent/src/backend/interface.rsindex 4df4e58..3a16c9c 100644--- a/src/backend/interface.rs+++ b/crates/agent/src/backend/interface.rs@@ -1,5 +1,6 @@-use super::*;use crate::globals::*;+use airgorah_common::deps;+use airgorah_common::types::MacMode;use std::process::{Command, Stdio};#[derive(thiserror::Error, Debug)]@@ -13,12 +14,6 @@ pub enum IfaceError {#[error("Utf8 conversion error")]Utf8Error(#[from] std::string::FromUtf8Error),- #[error("PHY parsing error")]- PhyParsing,-- #[error("PHY '{0}' could not be found")]- PhyNotFound(String),-#[error("Interface '{0}' could not be found")]IfaceNotFound(String),@@ -33,9 +28,6 @@ pub enum IfaceError {#[error("Could not disable monitor mode on '{0}':\n{1}")]ManagedFailed(String, String),-- #[error("systemctl is required to kill/restore network managers")]- MissingSystemd,}/// Get the available interfaces@@ -53,39 +45,6 @@ pub fn get_interfaces() -> Result<Vec<String>, IfaceError> {Ok(out.split_terminator('\n').map(String::from).collect())}-/// Check if an interface supports 5GHz-pub fn is_5ghz_supported(iface: &str) -> Result<bool, IfaceError> {- let phy_path = format!("/sys/class/net/{iface}/phy80211");-- let phy_link = std::fs::read_link(phy_path)?;-- let phy_name = match phy_link.file_name() {- Some(name) => name,- None => return Err(IfaceError::PhyParsing),- };-- let phy_name_str = match phy_name.to_str() {- Some(name) => name,- None => return Err(IfaceError::PhyParsing),- };-- let check_band_cmd = Command::new("iw")- .args(["phy", phy_name_str, "info"])- .output()?;-- if !check_band_cmd.status.success() {- return Err(IfaceError::PhyNotFound(phy_name_str.to_string()));- }-- let check_band_output = String::from_utf8(check_band_cmd.stdout)?;-- if check_band_output.contains("5200 MHz") || check_band_output.contains("5200.0 MHz") {- return Ok(true);- }-- Ok(false)-}-/// Check if an interface is in monitor modepub fn is_monitor_mode(iface: &str) -> Result<bool, IfaceError> {let check_monitor_cmd = Command::new("iw").args(["dev", iface, "info"]).output()?;@@ -103,8 +62,8 @@ pub fn is_monitor_mode(iface: &str) -> Result<bool, IfaceError> {Ok(false)}-// Set the MAC address of an interface-pub fn set_mac_address(iface: &str) -> Result<(), IfaceError> {+/// Set the MAC address of an interface according to the requested mode.+pub fn set_mac_address(iface: &str, mac: &MacMode) -> Result<(), IfaceError> {if !is_monitor_mode(iface)? {return Err(IfaceError::IfaceNotMonitor);}@@ -113,16 +72,16 @@ pub fn set_mac_address(iface: &str) -> Result<(), IfaceError> {.args(["link", "set", "dev", iface, "down"]).output()?;- let success = match get_settings().mac_address.as_str() {- "random" => {+ let success = match mac {+ MacMode::Random => {Command::new("macchanger").args(["-A", iface]).output()?;true}- "default" => {+ MacMode::Default => {Command::new("macchanger").args(["-p", iface]).output()?;true}- mac => Command::new("macchanger")+ MacMode::Specific(mac) => Command::new("macchanger").args(["-m", mac, iface]).output()?.status@@ -137,22 +96,18 @@ pub fn set_mac_address(iface: &str) -> Result<(), IfaceError> {return Err(IfaceError::InvalidMac);}- log::info!(- "{}: MAC address changed to {}",- iface,- get_settings().mac_address- );+ log::info!("{iface}: MAC address changed");Ok(())}/// enable monitor mode on an interface-pub fn enable_monitor_mode(iface: &str) -> Result<String, IfaceError> {+pub fn enable_monitor_mode(iface: &str, kill_network_manager: bool) -> Result<String, IfaceError> {if is_monitor_mode(iface)? {*IFACE_WAS_MONITOR.lock().unwrap() = true;}- kill_network_manager()?;+ kill_network_manager_services(kill_network_manager);if is_monitor_mode(iface)? {return Ok(iface.to_string());@@ -243,6 +198,11 @@ pub fn set_iface(iface: String) {IFACE.lock().unwrap().replace(iface);}+/// Clear the current interface+pub fn clear_iface() {+ IFACE.lock().unwrap().take();+}+/// List of services that can interfere with the app on the management of wireless cardsconst INTERFERENCE_SERVICES: [&str; 19] = ["wpa_action",@@ -266,23 +226,35 @@ const INTERFERENCE_SERVICES: [&str; 19] = ["hostapd",];-/// Kill the network manager to avoid channel hopping conflicts-pub fn kill_network_manager() -> Result<(), IfaceError> {- if !get_settings().kill_network_manager {- return Ok(());+/// Kill the network managers to avoid channel hopping conflicts.+///+/// `enabled` reflects the GUI's `kill_network_manager` setting. If `systemctl` is+/// absent the request is skipped rather than failed (the GUI already disables the+/// option in that case).+fn kill_network_manager_services(enabled: bool) {+ if !enabled {+ return;}- if !has_dependency("systemctl") {- return Err(IfaceError::MissingSystemd);+ if !deps::is_installed(deps::SYSTEMCTL) {+ log::warn!("systemctl not found, skipping network manager kill");+ return;}for service in INTERFERENCE_SERVICES {- let is_service_running = Command::new("systemctl")+ let is_service_running = match Command::new("systemctl").args(["is-active", service])- .output()?;-- if is_service_running.status.success() {- Command::new("systemctl").args(["stop", service]).output()?;+ .output()+ {+ Ok(out) => out.status.success(),+ Err(_) => continue,+ };++ if is_service_running {+ Command::new("systemctl")+ .args(["stop", service])+ .output()+ .ok();SERVICES_TO_RESTORE.lock()@@ -292,20 +264,15 @@ pub fn kill_network_manager() -> Result<(), IfaceError> {log::warn!("killed '{service}'");}}-- Ok(())}-/// Restore the network manager+/// Restore any network manager services that were killed. A no-op when nothing+/// was stopped.pub fn restore_network_manager() -> Result<(), IfaceError> {- if !get_settings().kill_network_manager {+ if !deps::is_installed(deps::SYSTEMCTL) {return Ok(());}- if !has_dependency("systemctl") {- return Err(IfaceError::MissingSystemd);- };-let services_to_restore: Vec<_> = SERVICES_TO_RESTORE.lock().unwrap().drain(..).collect();for service in services_to_restore {diff --git a/src/backend/mod.rs b/crates/agent/src/backend/mod.rsold mode 100755new mode 100644similarity index 73%rename from src/backend/mod.rsrename to crates/agent/src/backend/mod.rsindex e733b90..fb52504--- a/src/backend/mod.rs+++ b/crates/agent/src/backend/mod.rs@@ -1,17 +1,13 @@pub mod app;pub mod capture;pub mod deauth;-pub mod decrypt;pub mod interface;pub mod scan;-pub mod settings;pub mod vendors;pub use app::*;pub use capture::*;pub use deauth::*;-pub use decrypt::*;pub use interface::*;pub use scan::*;-pub use settings::*;pub use vendors::*;diff --git a/src/backend/scan.rs b/crates/agent/src/backend/scan.rssimilarity index 90%rename from src/backend/scan.rsrename to crates/agent/src/backend/scan.rsindex 0bf72d2..8968fbc 100644--- a/src/backend/scan.rs+++ b/crates/agent/src/backend/scan.rs@@ -3,9 +3,9 @@ use std::path::Path;use std::process::{Command, Stdio};use std::sync::MutexGuard;-use super::*;+use super::get_attack_pool;use crate::globals::*;-use crate::types::*;+use airgorah_common::types::*;use serde::Deserialize;@@ -83,47 +83,6 @@ pub fn is_scan_process() -> bool {SCAN_PROC.lock().unwrap().is_some()}-/// Check if the content of the channel filter is valid-pub fn is_valid_channel_filter(channel_filter: &str, ghz_2_4_but: bool, ghz_5_but: bool) -> bool {- let channel_list: Vec<String> = channel_filter- .split_terminator(',')- .map(String::from)- .collect();-- let mut channel_buf = vec![];-- if channel_filter.ends_with(',') {- return false;- }-- for channel_str in channel_list {- let channel = match channel_str.parse::<u32>() {- Ok(chan) => chan,- Err(_) => return false,- };-- if channel < 1 || (15..=35).contains(&channel) || channel > 165 {- return false;- }-- if (1..=14).contains(&channel) && !ghz_2_4_but {- return false;- }-- if (36..=165).contains(&channel) && !ghz_5_but {- return false;- }-- if channel_buf.contains(&channel) {- return false;- }-- channel_buf.push(channel);- }-- true-}-/// Set the scan processpub fn set_scan_process(iface: &str,@@ -240,7 +199,13 @@ pub fn stop_scan_process() -> Result<(), ScanError> {Ok(())}-/// Get the data captured from airodump+/// Drop the accumulated scan data (used by the GUI's "restart" action).+pub fn reset_scan_data() {+ get_aps().clear();+ get_unlinked_clients().clear();+}++/// Get the data captured from airodump.pub fn get_airodump_data() -> HashMap<String, AP> {let mut aps: HashMap<String, AP> = HashMap::new();@@ -347,7 +312,7 @@ pub fn get_airodump_data() -> HashMap<String, AP> {for result in cli_reader.deserialize::<RawClient>().flatten() {let mac = result.station_mac.trim_start().to_string();- let client_vendor = super::find_vendor(&mac);+ let vendor = super::find_vendor(&mac);match aps.get_mut(result.bssid.trim_start()) {Some(ap) => {@@ -366,7 +331,7 @@ pub fn get_airodump_data() -> HashMap<String, AP> {}},last_time_seen: result.last_time_seen.trim_start().to_string(),- vendor: client_vendor,+ vendor: vendor.clone(),probes: result.probes.trim_start().to_string(),},);@@ -388,7 +353,7 @@ pub fn get_airodump_data() -> HashMap<String, AP> {}},last_time_seen: result.last_time_seen.trim_start().to_string(),- vendor: client_vendor,+ vendor: vendor.clone(),probes: result.probes.trim_start().to_string(),},);diff --git a/crates/agent/src/backend/vendors.rs b/crates/agent/src/backend/vendors.rsnew file mode 100644index 0000000..1cd6a0e--- /dev/null+++ b/crates/agent/src/backend/vendors.rs@@ -0,0 +1,43 @@+//! Vendor (OUI) resolution.+//!+//! The agent produces the client records, so it also resolves each MAC to its+//! manufacturer here — the scan snapshot the GUI receives is then complete, with+//! no field left for the GUI to backfill. The OUI table is generated at build+//! time from `vendors.csv` (see `build.rs`).+//!+//! Resolution runs inline while building a snapshot, cached per MAC so repeated+//! polls do no extra work. The lookup is a handful of hashmap probes, so no+//! background thread is needed.++use crate::globals::VENDORS_CACHE;++use std::collections::HashMap;++include!(concat!(env!("OUT_DIR"), "/vendors.rs"));++/// Resolve a client's MAC address to a vendor name, or `"Unknown"`.+///+/// Walks from the longest usable MAC prefix down, matching against the OUI table+/// (which contains both 24-bit OUIs and longer MA-M/MA-S registrations).+pub fn find_vendor(mac: &str) -> String {+ let mut cache = VENDORS_CACHE.lock().unwrap();++ if let Some(vendor) = cache.get(mac) {+ return vendor.clone();+ }++ let mut prefix = mac.get(..13).unwrap_or(mac).to_string();+ let mut vendor = String::from("Unknown");++ while !prefix.is_empty() {+ if let Some(item) = VENDORS.get(prefix.as_str()) {+ vendor = item.to_string();+ break;+ }+ prefix.pop();+ }++ cache.insert(mac.to_string(), vendor.clone());++ vendor+}diff --git a/crates/agent/src/globals.rs b/crates/agent/src/globals.rsnew file mode 100644index 0000000..fdab986--- /dev/null+++ b/crates/agent/src/globals.rs@@ -0,0 +1,41 @@+//! 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+//! `aireplay`/`mdk4` attacks, the accumulated scan data, and the interface/service+//! state that must be restored on teardown.++use airgorah_common::types::{AP, Client};++use lazy_static::lazy_static;+use std::collections::HashMap;+use std::process::Child;+use std::sync::Mutex;++/// Root-owned 0700 directory for the agent's scan/capture files.+pub static CAPTURE_DIR: &str = "/var/lib/airgorah";++pub static LIVE_SCAN_PATH: &str = "/var/lib/airgorah/live_scan";+pub static OLD_SCAN_PATH: &str = "/var/lib/airgorah/old_scan";+pub static MERGE_SCAN_PATH: &str = "/var/lib/airgorah/merge_scan";++/// Live process handles for an ongoing deauth attack. Kept agent-internal (it+/// holds `Child`s) and projected onto [`airgorah_common::types::AttackState`] for+/// the wire.+pub enum AttackedClients {+ All(Child),+ Selection(Vec<(String, Child)>),+}++pub type AttackPool = HashMap<String, (AP, AttackedClients)>;++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 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());+ pub static ref SERVICES_TO_RESTORE: Mutex<Vec<String>> = Mutex::new(vec![]);+ pub static ref VENDORS_CACHE: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());+}diff --git a/crates/agent/src/main.rs b/crates/agent/src/main.rsnew file mode 100644index 0000000..f7677ec--- /dev/null+++ b/crates/agent/src/main.rs@@ -0,0 +1,137 @@+//! `airgorah-agent` — the privileged half of airgorah.+//!+//! Launched by the unprivileged GUI (normally via `pkexec`), it runs as root,+//! listens on a per-instance Unix socket, and performs every operation that needs+//! privilege: interface control, scanning, deauth attacks and capture access. It+//! serves exactly one client, and cleans up all privileged state when that client+//! disconnects — so the wireless card is never left in monitor mode with an+//! orphaned scan running.++mod backend;+mod globals;+mod server;+mod validate;++use airgorah_common::ipc::{RUNTIME_DIR, socket_path};++use nix::unistd::{Uid, chown, geteuid, getppid, getuid};+use std::os::unix::fs::PermissionsExt;+use std::os::unix::net::UnixListener;++fn main() {+ env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();++ if !geteuid().is_root() {+ eprintln!("airgorah-agent must run as root");+ std::process::exit(1);+ }++ let uid = resolve_target_uid();+ let instance = resolve_instance();+ let sock_path = socket_path(uid, instance);++ if let Err(e) = prepare_runtime_dir() {+ eprintln!("failed to prepare {RUNTIME_DIR}: {e}");+ std::process::exit(1);+ }++ if let Err(e) = prepare_capture_dir() {+ eprintln!("failed to prepare {}: {e}", globals::CAPTURE_DIR);+ std::process::exit(1);+ }++ // Clear a stale socket left by a previous crashed run.+ std::fs::remove_file(&sock_path).ok();++ let listener = match UnixListener::bind(&sock_path) {+ Ok(listener) => listener,+ Err(e) => {+ eprintln!("failed to bind {sock_path}: {e}");+ std::process::exit(1);+ }+ };++ if let Err(e) = secure_socket(&sock_path, uid) {+ eprintln!("failed to secure {sock_path}: {e}");+ std::fs::remove_file(&sock_path).ok();+ std::process::exit(1);+ }++ // Clean up on SIGINT/SIGTERM too, not only on a graceful disconnect.+ let signal_sock = sock_path.clone();+ ctrlc::set_handler(move || {+ backend::app_cleanup();+ std::fs::remove_file(&signal_sock).ok();+ std::process::exit(1);+ })+ .ok();++ // Handshake detection now lives agent-side (it owns the capture files).+ std::thread::spawn(|| {+ loop {+ backend::update_handshakes().ok();+ std::thread::sleep(std::time::Duration::from_millis(1500));+ }+ });++ log::info!("listening on {sock_path} for uid {uid}");++ // Accept exactly one client: the GUI that launched us.+ match listener.accept() {+ Ok((stream, _)) => {+ if server::authorized(&stream, uid) {+ server::handle_connection(stream);+ }+ }+ Err(e) => log::error!("accept failed: {e}"),+ }++ backend::app_cleanup();+ std::fs::remove_file(&sock_path).ok();+ log::info!("exiting");+}++/// Decide which uid the socket belongs to (and which peer is authorized).+///+/// `pkexec` runs us as root but exports `PKEXEC_UID` with the launching user's+/// uid, which is the authoritative source. When the agent is run directly+/// (e.g. by an already-root GUI, with no `PKEXEC_UID`) we fall back to the real+/// uid. Either way the actual authorization is the `SO_PEERCRED` check on the+/// accepted connection.+fn resolve_target_uid() -> u32 {+ std::env::var("PKEXEC_UID")+ .ok()+ .and_then(|s| s.parse::<u32>().ok())+ .unwrap_or_else(|| getuid().as_raw())+}++/// Each GUI instance gets its own socket, keyed by the GUI's process id, so+/// several instances can run at once (e.g. one per wireless card). `pkexec`+/// exec's us in place (and an already-root GUI spawns us directly), so our parent+/// *is* the GUI — its pid is exactly the instance id it built the socket path+/// from.+fn resolve_instance() -> u32 {+ getppid().as_raw() as u32+}++fn prepare_runtime_dir() -> std::io::Result<()> {+ std::fs::create_dir_all(RUNTIME_DIR)?;+ std::fs::set_permissions(RUNTIME_DIR, std::fs::Permissions::from_mode(0o755))?;+ Ok(())+}++/// Create the scan/capture scratch directory, restricted to root (`0700`).+fn prepare_capture_dir() -> std::io::Result<()> {+ std::fs::create_dir_all(globals::CAPTURE_DIR)?;+ std::fs::set_permissions(globals::CAPTURE_DIR, std::fs::Permissions::from_mode(0o700))?;+ Ok(())+}++/// Restrict the socket to its owner and hand ownership to the launching user, so+/// only that user (and root) can connect.+fn secure_socket(path: &str, uid: u32) -> std::io::Result<()> {+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;+ chown(path, Some(Uid::from_raw(uid)), None)+ .map_err(|e| std::io::Error::from_raw_os_error(e as i32))?;+ Ok(())+}diff --git a/crates/agent/src/server.rs b/crates/agent/src/server.rsnew file mode 100644index 0000000..dfaca61--- /dev/null+++ b/crates/agent/src/server.rs@@ -0,0 +1,233 @@+//! Connection handling and request dispatch.+//!+//! The agent serves exactly one client — the GUI that launched it — over a Unix+//! socket. Every request is authorized by peer credentials before this module is+//! reached (see [`authorized`]), and each request argument that becomes a command+//! line is re-validated here, because the GUI is a lower-trust caller once the+//! privilege boundary exists.++use crate::backend;+use crate::validate::{is_valid_interface_name, is_valid_mac};+use airgorah_common::VERSION;+use airgorah_common::channel::is_valid_channel_filter;+use airgorah_common::deps::{self, Requirer};+use airgorah_common::ipc::*;+use airgorah_common::types::*;++use nix::sys::socket::{getsockopt, sockopt::PeerCredentials};+use std::io;+use std::os::unix::net::UnixStream;++/// Authorize a freshly accepted connection: the peer must be the uid the agent+/// was launched for. Without this, any local user could drive privileged+/// operations (including deauth attacks) through the socket.+pub fn authorized(stream: &UnixStream, expected_uid: u32) -> bool {+ match getsockopt(stream, PeerCredentials) {+ Ok(cred) => {+ if cred.uid() == expected_uid {+ true+ } else {+ log::error!(+ "rejecting peer uid {} (expected {expected_uid})",+ cred.uid()+ );+ false+ }+ }+ Err(e) => {+ log::error!("could not read peer credentials: {e}");+ false+ }+ }+}++/// Serve requests until the client disconnects or asks the agent to shut down.+pub fn handle_connection(mut stream: UnixStream) {+ loop {+ let request: Request = match read_msg(&mut stream) {+ Ok(request) => request,+ Err(e) => {+ if e.kind() != io::ErrorKind::UnexpectedEof {+ log::error!("failed to read request: {e}");+ }+ // EOF: the GUI is gone. Returning triggers cleanup in main().+ break;+ }+ };++ let (response, shutdown) = dispatch(request);++ if let Err(e) = write_msg(&mut stream, &response) {+ log::error!("failed to write response: {e}");+ break;+ }++ if shutdown {+ break;+ }+ }+}++fn err<E: std::fmt::Display>(e: E) -> Response {+ Response::Error {+ message: e.to_string(),+ }+}++/// Handle one request. Returns the response and whether the agent should stop.+fn dispatch(request: Request) -> (Response, bool) {+ match request {+ Request::Hello { version } => {+ if version != VERSION {+ return (+ err(format!(+ "protocol version mismatch: agent={VERSION}, gui={version}"+ )),+ false,+ );+ }+ (+ Response::Setup {+ missing_dependencies: deps::missing_required(Requirer::Agent)+ .into_iter()+ .map(String::from)+ .collect(),+ },+ false,+ )+ }++ Request::EnableMonitor {+ iface,+ kill_network_manager,+ } => {+ if !is_valid_interface_name(&iface) {+ return (err("invalid interface name"), false);+ }+ match backend::enable_monitor_mode(&iface, kill_network_manager) {+ Ok(mon_iface) => {+ backend::set_iface(mon_iface.clone());+ (Response::MonitorEnabled { iface: mon_iface }, false)+ }+ Err(e) => (err(e), false),+ }+ }++ Request::SetMac { iface, mac } => {+ if !is_valid_interface_name(&iface) {+ return (err("invalid interface name"), false);+ }+ if let MacMode::Specific(ref mac) = mac+ && !is_valid_mac(mac)+ {+ return (err("invalid MAC address"), false);+ }+ match backend::set_mac_address(&iface, &mac) {+ Ok(()) => (Response::Ok, false),+ Err(e) => (err(e), false),+ }+ }++ Request::DisableMonitor { iface } => {+ if !is_valid_interface_name(&iface) {+ return (err("invalid interface name"), false);+ }+ let result = backend::disable_monitor_mode(&iface);+ backend::clear_iface();+ match result {+ Ok(()) => (Response::Ok, false),+ Err(e) => (err(e), false),+ }+ }++ Request::StartScan {+ iface,+ ghz_2_4,+ ghz_5,+ channels,+ } => {+ if !is_valid_interface_name(&iface) {+ return (err("invalid interface name"), false);+ }+ if let Some(ref filter) = channels+ && !is_valid_channel_filter(filter, ghz_2_4, ghz_5)+ {+ return (err("invalid channel filter"), false);+ }+ match backend::set_scan_process(&iface, ghz_2_4, ghz_5, channels) {+ Ok(()) => (Response::Ok, false),+ Err(e) => (err(e), false),+ }+ }++ Request::StopScan => match backend::stop_scan_process() {+ Ok(()) => (Response::Ok, false),+ Err(e) => (err(e), false),+ },++ Request::IsScanning => (Response::Bool(backend::is_scan_process()), false),++ Request::ResetScanData => {+ backend::reset_scan_data();+ (Response::Ok, false)+ }++ Request::GetScanData => {+ let aps: Vec<AP> = backend::get_airodump_data().into_values().collect();+ let unlinked: Vec<Client> = backend::get_unlinked_clients().values().cloned().collect();+ let attacked = backend::get_attack_states();+ (+ Response::ScanData {+ aps,+ unlinked,+ attacked,+ },+ false,+ )+ }++ Request::StartDeauth {+ bssid,+ clients,+ software,+ } => {+ if let Some(ref clients) = clients+ && !clients.iter().all(|c| is_valid_mac(c))+ {+ return (err("invalid client MAC address"), false);+ }+ let iface = match backend::get_iface() {+ Some(iface) => iface,+ None => return (err("no interface selected"), false),+ };+ let ap = match backend::get_aps().get(&bssid).cloned() {+ Some(ap) => ap,+ None => return (err(format!("unknown access point {bssid}")), false),+ };+ if !is_valid_mac(&ap.bssid) {+ return (err("invalid access point BSSID"), false);+ }+ match backend::launch_deauth_attack(&iface, ap, clients, software) {+ Ok(()) => (Response::Ok, false),+ Err(e) => (err(e), false),+ }+ }++ Request::StopDeauth { bssid } => {+ backend::stop_deauth_attack(&bssid);+ (Response::Ok, false)+ }++ Request::StopAllDeauth => {+ backend::stop_all_deauth_attacks();+ (Response::Ok, false)+ }++ Request::GetCaptureChunk { offset } => match backend::get_capture_chunk(offset) {+ Ok((data, last)) => (Response::CaptureChunk { data, last }, false),+ Err(e) => (err(e), false),+ },++ Request::Shutdown => (Response::Ok, true),+ }+}diff --git a/crates/agent/src/validate.rs b/crates/agent/src/validate.rsnew file mode 100644index 0000000..98a9f47--- /dev/null+++ b/crates/agent/src/validate.rs@@ -0,0 +1,30 @@+//! Validators for values that cross the privilege boundary and end up as+//! arguments to root-run commands.++/// Validate a network interface name.+pub fn is_valid_interface_name(name: &str) -> bool {+ if name.is_empty() || name.len() > 15 {+ return false;+ }++ if name.starts_with('-') || name == "." || name == ".." {+ return false;+ }++ name.bytes()+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))+}++/// Validate a MAC address in the canonical `xx:xx:xx:xx:xx:xx` hexadecimal form.+pub fn is_valid_mac(mac: &str) -> bool {+ let mut groups = 0;++ for part in mac.split(':') {+ if part.len() != 2 || !part.bytes().all(|b| b.is_ascii_hexdigit()) {+ return false;+ }+ groups += 1;+ }++ groups == 6+}diff --git a/package/vendors.csv b/crates/agent/vendors.csvsimilarity index 100%rename from package/vendors.csvrename to crates/agent/vendors.csvdiff --git a/crates/common/Cargo.toml b/crates/common/Cargo.tomlnew file mode 100644index 0000000..d0cdc24--- /dev/null+++ b/crates/common/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "airgorah-common"+version.workspace = true+edition.workspace = true+license.workspace = true+description = "Shared types and IPC protocol between the airgorah GUI and its privileged agent"++[dependencies]+serde.workspace = true+serde_json.workspace = true+regex.workspace = true+which.workspace = truediff --git a/crates/common/src/channel.rs b/crates/common/src/channel.rsnew file mode 100644index 0000000..409858c--- /dev/null+++ b/crates/common/src/channel.rs@@ -0,0 +1,44 @@+//! Channel-filter validation. Pure logic, shared so the GUI can validate input+//! for UX and the agent can re-validate it as a trust boundary before the value+//! ever reaches a command line.++/// Check whether a comma-separated channel filter is valid for the selected bands.+pub fn is_valid_channel_filter(channel_filter: &str, ghz_2_4_but: bool, ghz_5_but: bool) -> bool {+ let channel_list: Vec<String> = channel_filter+ .split_terminator(',')+ .map(String::from)+ .collect();++ let mut channel_buf = vec![];++ if channel_filter.ends_with(',') {+ return false;+ }++ for channel_str in channel_list {+ let channel = match channel_str.parse::<u32>() {+ Ok(chan) => chan,+ Err(_) => return false,+ };++ if channel < 1 || (15..=35).contains(&channel) || channel > 165 {+ return false;+ }++ if (1..=14).contains(&channel) && !ghz_2_4_but {+ return false;+ }++ if (36..=165).contains(&channel) && !ghz_5_but {+ return false;+ }++ if channel_buf.contains(&channel) {+ return false;+ }++ channel_buf.push(channel);+ }++ true+}diff --git a/crates/common/src/deps.rs b/crates/common/src/deps.rsnew file mode 100644index 0000000..561278b--- /dev/null+++ b/crates/common/src/deps.rs@@ -0,0 +1,122 @@+//! Catalog of the external command-line tools airgorah relies on.+//!+//! A single source of truth: each tool is declared once, tagged with which+//! process runs it and whether it is required. Both the GUI and the agent derive+//! their required set from this list and check it *in their own environment* —+//! the agent runs as root with `/usr/sbin` on `PATH` and can see tools the+//! unprivileged GUI cannot, so the check must happen on each side.++/// Which airgorah process invokes a given tool.+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum Requirer {+ /// Only the unprivileged GUI (interface listing, handshake decryption).+ Gui,+ /// Only the privileged agent (monitor mode, scan, deauth, capture).+ Agent,+ /// Both processes — each checks it in its own `PATH`.+ Both,+}++/// An external tool and who needs it.+pub struct Tool {+ pub name: &'static str,+ pub requirer: Requirer,+ pub optional: bool,+}++// Optional tool names, referenced at their on-demand check sites.+pub const MDK4: &str = "mdk4";+pub const CRUNCH: &str = "crunch";+pub const SYSTEMCTL: &str = "systemctl";++/// Every external tool airgorah shells out to.+pub const TOOLS: &[Tool] = &[+ // Required.+ Tool {+ name: "sh",+ requirer: Requirer::Both,+ optional: false,+ },+ Tool {+ name: "iw",+ requirer: Requirer::Both,+ optional: false,+ },+ Tool {+ name: "awk",+ requirer: Requirer::Both,+ optional: false,+ },+ Tool {+ name: "aircrack-ng",+ requirer: Requirer::Both,+ optional: false,+ },+ Tool {+ name: "xterm",+ requirer: Requirer::Gui,+ optional: false,+ },+ Tool {+ name: "ip",+ requirer: Requirer::Agent,+ optional: false,+ },+ Tool {+ name: "airmon-ng",+ requirer: Requirer::Agent,+ optional: false,+ },+ Tool {+ name: "airodump-ng",+ requirer: Requirer::Agent,+ optional: false,+ },+ Tool {+ name: "aireplay-ng",+ requirer: Requirer::Agent,+ optional: false,+ },+ Tool {+ name: "mergecap",+ requirer: Requirer::Agent,+ optional: false,+ },+ Tool {+ name: "macchanger",+ requirer: Requirer::Agent,+ optional: false,+ },+ // Optional, checked on demand.+ Tool {+ name: MDK4,+ requirer: Requirer::Agent,+ optional: true,+ },+ Tool {+ name: CRUNCH,+ requirer: Requirer::Gui,+ optional: true,+ },+ Tool {+ name: SYSTEMCTL,+ requirer: Requirer::Both,+ optional: true,+ },+];++/// Whether a tool is available on the current process's `PATH`.+pub fn is_installed(name: &str) -> bool {+ which::which(name).is_ok()+}++/// The required tools for `who` that are not installed, checked in the calling+/// process's own `PATH`. Empty when everything required is present.+pub fn missing_required(who: Requirer) -> Vec<&'static str> {+ TOOLS+ .iter()+ .filter(|tool| !tool.optional && (tool.requirer == who || tool.requirer == Requirer::Both))+ .map(|tool| tool.name)+ .filter(|name| !is_installed(name))+ .collect()+}diff --git a/crates/common/src/handshake.rs b/crates/common/src/handshake.rsnew file mode 100644index 0000000..44eb6e2--- /dev/null+++ b/crates/common/src/handshake.rs@@ -0,0 +1,51 @@+//! Handshake detection via `aircrack-ng`.+//!+//! Shared because both sides need it against different files: the agent scans+//! the root-owned live/old captures to flag APs, while the GUI inspects+//! a user-selected capture before offering it for decryption. Reading a capture+//! and running `aircrack-ng` needs no privilege — only file access — so the logic+//! is identical on both sides.++use regex::Regex;+use std::process::Command;++/// Return `(bssid, essid)` for every AP that has at least one captured WPA+/// handshake in the given capture file(s).+pub fn get_handshakes<I, S>(args: I) -> std::io::Result<Vec<(String, String)>>+where+ I: IntoIterator<Item = S>,+ S: AsRef<std::ffi::OsStr>,+{+ let capture_output = Command::new("aircrack-ng").args(args).output()?;++ let output = String::from_utf8_lossy(&capture_output.stdout).to_string();++ // Pattern is a compile-time constant, so construction cannot fail.+ let re = Regex::new(r"\s+(\d+)\s+([\w:]+)\s+(.*)\s+WPA \((\d+)\s+handshake.*\)")+ .expect("valid handshake regex");++ let mut handshakes = vec![];++ for line in output.lines() {+ let caps = match re.captures(line) {+ Some(caps) => caps,+ None => continue,+ };++ let bssid = caps[2].to_string();+ let essid = caps[3].trim().to_string();+ let handshake_count = caps[4].to_string();++ if handshake_count.parse::<i32>().unwrap_or(0) > 0 {+ handshakes.push((+ bssid,+ match essid.is_empty() {+ true => "hidden".to_string(),+ false => essid,+ },+ ));+ }+ }++ Ok(handshakes)+}diff --git a/crates/common/src/ipc.rs b/crates/common/src/ipc.rsnew file mode 100644index 0000000..ed53f1e--- /dev/null+++ b/crates/common/src/ipc.rs@@ -0,0 +1,148 @@+//! The IPC contract between the GUI and the privileged agent.+//!+//! Wire format: a 4-byte big-endian length prefix followed by a JSON-encoded+//! [`Request`] or [`Response`].++use crate::types::*;+use serde::Serialize;+use serde::de::DeserializeOwned;+use std::io::{self, Read, Write};++/// Directory the agent creates (as root) to hold its listening socket.+pub const RUNTIME_DIR: &str = "/run/airgorah";++/// Hard cap on a single framed message, guarding against a bogus length prefix.+const MAX_MSG_LEN: usize = 64 * 1024 * 1024;++/// Per-instance socket path, keyed by the launching user's uid and the GUI's+/// process id. Each GUI instance gets its own agent and socket, so several+/// instances running at once (e.g. one per wireless card) do not collide.+pub fn socket_path(uid: u32, instance: u32) -> String {+ format!("{RUNTIME_DIR}/{uid}-{instance}.sock")+}++/// A command sent by the GUI to the agent.+#[derive(Debug, Serialize, serde::Deserialize)]+pub enum Request {+ /// First message on a new connection: negotiate the protocol version and+ /// trigger the agent's dependency check.+ Hello {+ version: String,+ },++ // --- interface ---+ // Interface enumeration and 5 GHz capability are unprivileged and handled+ // GUI-side, only monitor-mode control crosses the boundary.+ EnableMonitor {+ iface: String,+ kill_network_manager: bool,+ },+ SetMac {+ iface: String,+ mac: MacMode,+ },+ DisableMonitor {+ iface: String,+ },++ // --- scan ---+ StartScan {+ iface: String,+ ghz_2_4: bool,+ ghz_5: bool,+ channels: Option<String>,+ },+ StopScan,+ IsScanning,+ /// Drop the accumulated access-point / client data (the "restart" action).+ ResetScanData,+ /// Poll for the current merged scan snapshot (sent on the GUI's refresh timer).+ GetScanData,++ // --- attacks ---+ StartDeauth {+ bssid: String,+ clients: Option<Vec<String>>,+ software: AttackSoftware,+ },+ StopDeauth {+ bssid: String,+ },+ StopAllDeauth,++ // --- capture ---+ /// Read one chunk of the saved capture at `offset`; the GUI streams the file+ /// in bounded pieces so a long capture never has to fit in one frame.+ GetCaptureChunk {+ offset: u64,+ },++ /// Ask the agent to clean up and exit.+ Shutdown,+}++/// A reply from the agent to a [`Request`].+#[derive(Debug, Serialize, serde::Deserialize)]+pub enum Response {+ Ok,+ Error {+ message: String,+ },+ /// Reply to [`Request::Hello`]: the required tools the agent found missing+ /// (empty when everything it needs is present).+ Setup {+ missing_dependencies: Vec<String>,+ },+ /// The (possibly renamed) monitor-mode interface name.+ MonitorEnabled {+ iface: String,+ },+ Bool(bool),+ ScanData {+ aps: Vec<AP>,+ unlinked: Vec<Client>,+ attacked: Vec<AttackState>,+ },+ /// One chunk of the capture; `last` marks the final one.+ CaptureChunk {+ data: Vec<u8>,+ last: bool,+ },+}++/// Write a length-prefixed JSON frame.+pub fn write_msg<W: Write, T: Serialize>(w: &mut W, msg: &T) -> io::Result<()> {+ let data =+ serde_json::to_vec(msg).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;++ if data.len() > MAX_MSG_LEN {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "message exceeds maximum frame length",+ ));+ }++ w.write_all(&(data.len() as u32).to_be_bytes())?;+ w.write_all(&data)?;+ w.flush()+}++/// Read a length-prefixed JSON frame. Returns `UnexpectedEof` on a clean+/// disconnect, which the agent uses as its teardown trigger.+pub fn read_msg<R: Read, T: DeserializeOwned>(r: &mut R) -> io::Result<T> {+ let mut len_buf = [0u8; 4];+ r.read_exact(&mut len_buf)?;++ let len = u32::from_be_bytes(len_buf) as usize;+ if len > MAX_MSG_LEN {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "declared frame length exceeds maximum",+ ));+ }++ let mut buf = vec![0u8; len];+ r.read_exact(&mut buf)?;++ serde_json::from_slice(&buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))+}diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rsnew file mode 100644index 0000000..e1ab61f--- /dev/null+++ b/crates/common/src/lib.rs@@ -0,0 +1,16 @@+//! Shared building blocks between the unprivileged `airgorah` GUI and the+//! privileged `airgorah-agent` process.+//!+//! This crate contains only data and pure/utility logic: the wire types, the+//! IPC protocol and its framed-JSON codec, and a couple of utilities that both+//! sides need.++pub mod channel;+pub mod deps;+pub mod handshake;+pub mod ipc;+pub mod types;++pub use types::*;++pub const VERSION: &str = concat!("v", env!("CARGO_PKG_VERSION"));diff --git a/crates/common/src/types.rs b/crates/common/src/types.rsnew file mode 100644index 0000000..286bcfe--- /dev/null+++ b/crates/common/src/types.rs@@ -0,0 +1,110 @@+//! Wire types shared across the IPC boundary.+//!+//! Everything here derives `Serialize`/`Deserialize` so it can travel over the+//! agent socket. Types that hold live process handles (e.g. the agent's+//! `Child` processes) deliberately do *not* live here — they stay internal to+//! the agent and are projected onto the serializable [`AttackState`] for the+//! wire.++use serde::{Deserialize, Serialize};+use std::collections::HashMap;++/// Deauthentication tool the agent should drive.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub enum AttackSoftware {+ Aireplay,+ Mdk4,+}++/// How the MAC address of an interface should be set when entering monitor mode.+///+/// Resolved GUI-side from the user's [`Settings::mac_address`] and passed to the+/// agent as an explicit request parameter, so the agent never has to read the+/// user's configuration.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub enum MacMode {+ /// Randomize the MAC address (`macchanger -A`).+ Random,+ /// Restore the permanent hardware MAC (`macchanger -p`).+ Default,+ /// Set a specific MAC address (`macchanger -m <mac>`).+ Specific(String),+}++/// Serializable view of which clients of an AP are currently under attack.+///+/// The agent keeps the actual `Child` handles internally; this is the shape the+/// GUI receives so it can paint the affected rows.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub enum AttackTarget {+ /// A broadcast deauth against every client (`FF:FF:FF:FF:FF:FF`).+ All,+ /// A deauth targeting the listed client MAC addresses.+ Selection(Vec<String>),+}++/// A single ongoing deauth attack, as reported to the GUI.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct AttackState {+ pub ap: AP,+ pub target: AttackTarget,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct AP {+ pub essid: String,+ pub bssid: String,+ pub band: String,+ pub channel: String,+ pub speed: String,+ pub power: String,+ pub privacy: String,+ pub hidden: bool,+ pub handshake: bool,+ /// Path of a capture file the *GUI* saved this handshake to. This is GUI-side+ /// overlay state: the agent always leaves it `None` and the GUI fills it in+ /// from its own bookkeeping before display.+ pub saved_handshake: Option<String>,+ pub first_time_seen: String,+ pub last_time_seen: String,+ pub clients: HashMap<String, Client>,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Client {+ pub mac: String,+ pub packets: String,+ pub power: String,+ pub first_time_seen: String,+ pub last_time_seen: String,+ pub vendor: String,+ pub probes: String,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Settings {+ pub mac_address: String,+ pub display_hidden_ap: bool,+ pub kill_network_manager: bool,+}++impl Default for Settings {+ fn default() -> Self {+ Self {+ mac_address: "random".to_string(),+ display_hidden_ap: true,+ kill_network_manager: true,+ }+ }+}++impl Settings {+ /// Resolve the configured MAC preference into a wire [`MacMode`].+ pub fn mac_mode(&self) -> MacMode {+ match self.mac_address.as_str() {+ "random" => MacMode::Random,+ "default" => MacMode::Default,+ mac => MacMode::Specific(mac.to_string()),+ }+ }+}diff --git a/crates/gui/Cargo.toml b/crates/gui/Cargo.tomlnew file mode 100644index 0000000..7277857--- /dev/null+++ b/crates/gui/Cargo.toml@@ -0,0 +1,30 @@+[package]+name = "airgorah"+version.workspace = true+edition.workspace = true+license.workspace = true+description = "A WiFi security auditing software mainly based on aircrack-ng tools suite"+homepage.workspace = true+repository.workspace = true+documentation.workspace = true+keywords = ["networking", "pentest", "aircrack-ng", "gui", "linux"]+readme = "README.md"++[[bin]]+name = "airgorah"+path = "src/main.rs"++[dependencies]+airgorah-common.workspace = true+gtk4 = { version = "0.11", features = ["v4_6"] }+serde.workspace = true+serde_json.workspace = true+toml = "1"+regex.workspace = true+chrono = "0.4"+lazy_static.workspace = true+nix.workspace = true+ureq = { version = "3", features = ["json"] }+log.workspace = true+env_logger.workspace = true+thiserror.workspace = truediff --git a/icons/app_icon.png b/crates/gui/icons/app_icon.pngsimilarity index 100%rename from icons/app_icon.pngrename to crates/gui/icons/app_icon.pngdiff --git a/icons/capture.png b/crates/gui/icons/capture.pngsimilarity index 100%rename from icons/capture.pngrename to crates/gui/icons/capture.pngdiff --git a/icons/deauth.png b/crates/gui/icons/deauth.pngsimilarity index 100%rename from icons/deauth.pngrename to crates/gui/icons/deauth.pngdiff --git a/icons/stop.png b/crates/gui/icons/stop.pngsimilarity index 100%rename from icons/stop.pngrename to crates/gui/icons/stop.pngdiff --git a/crates/gui/src/backend/client.rs b/crates/gui/src/backend/client.rsnew file mode 100644index 0000000..0503bc9--- /dev/null+++ b/crates/gui/src/backend/client.rs@@ -0,0 +1,478 @@+//! IPC client++use crate::globals::*;+use airgorah_common::deps::{self, Requirer};+use airgorah_common::ipc::*;+use airgorah_common::types::{AP, AttackSoftware, AttackState, Client};++use lazy_static::lazy_static;+use nix::unistd::{geteuid, getuid};+use std::collections::HashMap;+use std::io::Write;+use std::os::unix::net::UnixStream;+use std::path::PathBuf;+use std::process::{Child, Command};+use std::sync::{Mutex, MutexGuard};+use std::time::{Duration, Instant};++/// Error surfaced from an agent interaction. Its `Display` carries the agent's+/// own error text, which the frontend shows in its dialogs.+#[derive(Debug, thiserror::Error)]+#[error("{0}")]+pub struct AgentError(pub String);++/// The live connection to the privileged agent. Holds the socket and keeps the+/// agent child process alive for the lifetime of the GUI.+struct AgentClient {+ stream: UnixStream,+ _child: Child,+}++impl AgentClient {+ fn exchange(&mut self, request: Request) -> Result<Response, AgentError> {+ exchange(&mut self.stream, request)+ }+}++/// Write a request and read the response on a raw stream.+fn exchange(stream: &mut UnixStream, request: Request) -> Result<Response, AgentError> {+ write_msg(stream, &request)+ .map_err(|e| AgentError(format!("failed to send request to agent: {e}")))?;+ read_msg(stream).map_err(|e| AgentError(format!("lost connection to agent: {e}")))+}++lazy_static! {+ static ref CLIENT: Mutex<Option<AgentClient>> = Mutex::new(None);+}++/// Send a request and get the raw response, or an error if the agent is gone.+fn request(request: Request) -> Result<Response, AgentError> {+ let mut guard = CLIENT.lock().unwrap();+ let client = guard+ .as_mut()+ .ok_or_else(|| AgentError("the privileged agent is not connected".to_string()))?;+ client.exchange(request)+}++/// Collapse a response that should just be an acknowledgement.+fn expect_ok(response: Response) -> Result<(), AgentError> {+ match response {+ Response::Ok => Ok(()),+ Response::Error { message } => Err(AgentError(message)),+ _ => Err(AgentError("unexpected response from agent".to_string())),+ }+}++// --------------------------------------------------------------------------+// Lifecycle+// --------------------------------------------------------------------------++/// Format the "missing required tools" error shown to the user. Both the GUI's+/// own startup check and the agent's `Hello` reply feed through here.+fn missing_deps_error<S: AsRef<str>>(missing: &[S]) -> AgentError {+ let list = missing+ .iter()+ .map(AsRef::as_ref)+ .collect::<Vec<_>>()+ .join(", ");+ AgentError(format!("Missing required dependencies: {list}"))+}++/// Startup initialization that needs no privilege: load settings and warn if the+/// GUI is (pointlessly) running as root. The privileged agent is intentionally+/// *not* started here — see [`ensure_agent`] — but we verify it is installed so a+/// broken install fails clearly at launch rather than only on the first scan.+/// Locating the binary does not run it and does not escalate.+pub fn init() -> Result<(), AgentError> {+ if geteuid().is_root() {+ log::warn!(+ "running the airgorah GUI as root is discouraged and does not work under Wayland"+ );+ }++ super::load_settings();++ agent_binary_path()?;++ let missing = deps::missing_required(Requirer::Gui);+ if !missing.is_empty() {+ return Err(missing_deps_error(&missing));+ }++ Ok(())+}++/// Ensure the privileged agent is running and connected, launching it (via+/// pkexec) on first use and performing the version/dependency handshake.+///+/// This is the single escalation point, it is called only when the user commits+/// to a privileged action.+pub fn ensure_agent() -> Result<(), AgentError> {+ if CLIENT.lock().unwrap().is_some() {+ return Ok(());+ }++ let uid = getuid().as_raw();+ // Key the socket on our pid so multiple GUI instances don't collide. The+ // agent derives the same id from its parent pid (it is exec'd by pkexec, or+ // spawned directly, so its parent is this GUI), so we need not pass it.+ let sock = socket_path(uid, std::process::id());++ // Spawn + connect without holding the CLIENT lock: this may block on the+ // polkit prompt. Only the GTK main thread calls this, so there is no race.+ let mut child = spawn_agent()?;++ match connect_agent(&sock, &mut child) {+ Ok(stream) => {+ *CLIENT.lock().unwrap() = Some(AgentClient {+ stream,+ _child: child,+ });+ Ok(())+ }+ Err(e) => {+ child.kill().ok();+ child.wait().ok();+ Err(e)+ }+ }+}++/// Connect to the freshly spawned agent and run the version/dependency check.+fn connect_agent(sock: &str, child: &mut Child) -> Result<UnixStream, AgentError> {+ let mut stream = connect_with_timeout(sock, child)?;++ match exchange(+ &mut stream,+ Request::Hello {+ version: VERSION.to_string(),+ },+ )? {+ Response::Setup {+ missing_dependencies,+ } => {+ if !missing_dependencies.is_empty() {+ return Err(missing_deps_error(&missing_dependencies));+ }+ }+ Response::Error { message } => return Err(AgentError(message)),+ _ => return Err(AgentError("unexpected response to hello".to_string())),+ }++ Ok(stream)+}++/// Ask the agent to tear down and disconnect. Dropping the connection would also+/// trigger cleanup agent-side (via socket EOF); sending `Shutdown` is the tidy+/// path.+pub fn app_cleanup() {+ if let Some(mut client) = CLIENT.lock().unwrap().take() {+ client.exchange(Request::Shutdown).ok();+ }+}++fn spawn_agent() -> Result<Child, AgentError> {+ let agent = agent_binary_path()?;++ // The agent needs no arguments: it derives the uid from PKEXEC_UID (else+ // getuid()) and the instance id from its parent pid (this GUI).+ let mut command = if geteuid().is_root() {+ // GUI already privileged (e.g. launched with sudo on X11): run the agent+ // directly. Clear any inherited PKEXEC_UID so it resolves the uid from+ // getuid() (0), matching the socket path the GUI connects to.+ let mut command = Command::new(&agent);+ command.env_remove("PKEXEC_UID");+ command+ } else {+ // Normal case: escalate only the agent, via polkit.+ let mut command = Command::new("pkexec");+ command.arg(&agent);+ command+ };++ command+ .spawn()+ .map_err(|e| AgentError(format!("failed to launch privileged agent: {e}")))+}++fn agent_binary_path() -> Result<PathBuf, AgentError> {+ // The agent must live next to the GUI (both the dev build and the package ship+ // them in the same directory).+ let exe = std::env::current_exe()+ .map_err(|e| AgentError(format!("could not locate the running executable: {e}")))?;++ let candidate = exe+ .parent()+ .ok_or_else(|| AgentError("the running executable has no parent directory".to_string()))?+ .join("airgorah-agent");++ if !candidate.is_file() {+ return Err(AgentError(+ "could not locate the 'airgorah-agent' binary next to the GUI".to_string(),+ ));+ }++ Ok(candidate)+}++fn connect_with_timeout(sock: &str, child: &mut Child) -> Result<UnixStream, AgentError> {+ let deadline = Instant::now() + Duration::from_secs(120);++ loop {+ if let Ok(stream) = UnixStream::connect(sock) {+ return Ok(stream);+ }++ // Fail fast if pkexec/the agent already exited (e.g. auth cancelled).+ if let Ok(Some(status)) = child.try_wait() {+ return Err(AgentError(format!(+ "the privileged agent exited before accepting a connection ({status}), authentication may have been cancelled"+ )));+ }++ if Instant::now() >= deadline {+ return Err(AgentError(+ "timed out waiting for the privileged agent".to_string(),+ ));+ }++ std::thread::sleep(Duration::from_millis(100));+ }+}++// --------------------------------------------------------------------------+// Interface+// --------------------------------------------------------------------------++pub fn enable_monitor_mode(iface: &str) -> Result<String, AgentError> {+ let kill_network_manager = super::get_settings().kill_network_manager;++ match request(Request::EnableMonitor {+ iface: iface.to_string(),+ kill_network_manager,+ })? {+ Response::MonitorEnabled { iface } => Ok(iface),+ Response::Error { message } => Err(AgentError(message)),+ _ => Err(AgentError("unexpected response from agent".to_string())),+ }+}++pub fn set_mac_address(iface: &str) -> Result<(), AgentError> {+ let mac = super::get_settings().mac_mode();+ expect_ok(request(Request::SetMac {+ iface: iface.to_string(),+ mac,+ })?)+}++pub fn disable_monitor_mode(iface: &str) -> Result<(), AgentError> {+ expect_ok(request(Request::DisableMonitor {+ iface: iface.to_string(),+ })?)+}++/// The currently selected monitor interface (GUI-side copy).+pub fn get_iface() -> Option<String> {+ IFACE.lock().unwrap().clone()+}++pub fn set_iface(iface: String) {+ IFACE.lock().unwrap().replace(iface);+}++// --------------------------------------------------------------------------+// Scan+// --------------------------------------------------------------------------++pub fn is_scan_process() -> bool {+ matches!(request(Request::IsScanning), Ok(Response::Bool(true)))+}++pub fn set_scan_process(+ iface: &str,+ ghz_2_4: bool,+ ghz_5: bool,+ channel_filter: Option<String>,+) -> Result<(), AgentError> {+ expect_ok(request(Request::StartScan {+ iface: iface.to_string(),+ ghz_2_4,+ ghz_5,+ channels: channel_filter,+ })?)+}++pub fn stop_scan_process() -> Result<(), AgentError> {+ expect_ok(request(Request::StopScan)?)+}++/// Drop accumulated scan data on both sides (the "restart" action).+pub fn reset_scan_data() {+ request(Request::ResetScanData).ok();+ get_aps().clear();+ get_unlinked_clients().clear();+ get_attack_pool().clear();+ SAVED_HANDSHAKES.lock().unwrap().clear();+}++/// Poll the agent for the current scan snapshot, refresh the local caches, and+/// return the access-point map (matching the old `get_airodump_data`).+pub fn get_airodump_data() -> HashMap<String, AP> {+ let response = match request(Request::GetScanData) {+ Ok(response) => response,+ Err(_) => return get_aps().clone(),+ };++ let (aps_vec, unlinked, attacked) = match response {+ Response::ScanData {+ aps,+ unlinked,+ attacked,+ } => (aps, unlinked, attacked),+ _ => return get_aps().clone(),+ };++ // GUI-side enrichment: merge the saved-handshake overlay onto the snapshot.+ // Vendors are already resolved by the agent, so there is nothing else to fill.+ let overlay = SAVED_HANDSHAKES.lock().unwrap().clone();++ let mut aps_map = HashMap::with_capacity(aps_vec.len());+ for mut ap in aps_vec {+ if let Some(path) = overlay.get(&ap.bssid) {+ ap.saved_handshake = Some(path.clone());+ }+ aps_map.insert(ap.bssid.clone(), ap);+ }++ let mut unlinked_map = HashMap::with_capacity(unlinked.len());+ for client in unlinked {+ unlinked_map.insert(client.mac.clone(), client);+ }++ let mut pool = HashMap::with_capacity(attacked.len());+ for state in attacked {+ pool.insert(state.ap.bssid.clone(), state);+ }++ *get_aps() = aps_map.clone();+ *get_unlinked_clients() = unlinked_map;+ *get_attack_pool() = pool;++ aps_map+}++pub fn get_aps() -> MutexGuard<'static, HashMap<String, AP>> {+ APS.lock().unwrap()+}++pub fn get_unlinked_clients() -> MutexGuard<'static, HashMap<String, Client>> {+ UNLINKED_CLIENTS.lock().unwrap()+}++pub fn get_attack_pool() -> MutexGuard<'static, HashMap<String, AttackState>> {+ ATTACK_POOL.lock().unwrap()+}++/// Record that every currently-captured handshake has been saved to `path`.+/// Replaces the old direct mutation of the AP map so the mark survives the next+/// snapshot refresh (it is stored in the GUI-side overlay).+pub fn mark_handshakes_saved(path: &str) {+ let mut overlay = SAVED_HANDSHAKES.lock().unwrap();+ let mut aps = get_aps();++ for (bssid, ap) in aps.iter_mut() {+ if ap.handshake {+ overlay.insert(bssid.clone(), path.to_string());+ ap.saved_handshake = Some(path.to_string());+ }+ }+}++// --------------------------------------------------------------------------+// Attacks+// --------------------------------------------------------------------------++pub fn launch_deauth_attack(+ _iface: &str,+ ap: AP,+ specific_clients: Option<Vec<String>>,+ software: AttackSoftware,+) -> Result<(), AgentError> {+ expect_ok(request(Request::StartDeauth {+ bssid: ap.bssid,+ clients: specific_clients,+ software,+ })?)+}++pub fn stop_deauth_attack(bssid: &str) {+ request(Request::StopDeauth {+ bssid: bssid.to_string(),+ })+ .ok();+}++// --------------------------------------------------------------------------+// Capture+// --------------------------------------------------------------------------++/// Stream the accumulated capture from the agent and write it to `path` as the+/// user (the agent never writes to a user-chosen path as root), pulling it in+/// bounded chunks so a long capture never has to be held whole in memory.+pub fn save_capture(path: &str) -> Result<(), AgentError> {+ // Create the file lazily, so a failed transfer leaves no empty file behind.+ let mut file: Option<std::fs::File> = None;+ let mut offset: u64 = 0;++ loop {+ match request(Request::GetCaptureChunk { offset })? {+ Response::CaptureChunk { data, last } => {+ let file = match file {+ Some(ref mut file) => file,+ None => file.insert(+ std::fs::File::create(path)+ .map_err(|e| AgentError(format!("failed to write capture: {e}")))?,+ ),+ };++ file.write_all(&data)+ .map_err(|e| AgentError(format!("failed to write capture: {e}")))?;+ offset += data.len() as u64;++ if last {+ break;+ }+ }+ Response::Error { message } => return Err(AgentError(message)),+ _ => return Err(AgentError("unexpected response from agent".to_string())),+ }+ }++ log::info!("capture saved to '{path}'");++ Ok(())+}++// --------------------------------------------------------------------------+// Misc (unprivileged, same machine)+// --------------------------------------------------------------------------++/// Check if a new version is available.+pub fn check_update(current_version: &str) -> Option<String> {+ let url = "https://api.github.com/repos/martin-olivier/airgorah/releases/latest";++ if let Ok(mut response) = ureq::get(url).call()+ && let Ok(json) = response.body_mut().read_json::<serde_json::Value>()+ && json["tag_name"] != current_version+ {+ let new_version = json["tag_name"].as_str().unwrap_or("unknown").to_owned();++ log::info!("a new version is available: \"{new_version}\"");++ return Some(new_version);+ }++ log::info!("airgorah is up to date");++ None+}diff --git a/src/backend/decrypt.rs b/crates/gui/src/backend/decrypt.rssimilarity index 100%rename from src/backend/decrypt.rsrename to crates/gui/src/backend/decrypt.rsdiff --git a/crates/gui/src/backend/iface.rs b/crates/gui/src/backend/iface.rsnew file mode 100644index 0000000..3278152--- /dev/null+++ b/crates/gui/src/backend/iface.rs@@ -0,0 +1,52 @@+//! Unprivileged interface queries, run directly by the GUI.+//!+//! Listing interfaces (`iw dev`) and probing 5 GHz capability (sysfs + `iw phy`)+//! need no privilege, so they stay in the GUI. Keeping them here — rather than+//! behind the agent — is what lets the interface picker open and populate+//! without ever escalating; the agent is only started once the user commits to+//! a privileged action (putting a card into monitor mode).++use super::AgentError;+use std::process::Command;++/// Get the available wireless interfaces.+pub fn get_interfaces() -> Result<Vec<String>, AgentError> {+ let cmd = Command::new("sh")+ .args(["-c", "iw dev | awk '$1==\"Interface\"{print $2}'"])+ .output()+ .map_err(|e| AgentError(format!("failed to list interfaces: {e}")))?;++ if !cmd.status.success() {+ return Err(AgentError("failed to retrieve interfaces list".to_string()));+ }++ let out = String::from_utf8_lossy(&cmd.stdout);++ Ok(out.split_terminator('\n').map(String::from).collect())+}++/// Check if an interface supports 5 GHz.+pub fn is_5ghz_supported(iface: &str) -> Result<bool, AgentError> {+ let phy_path = format!("/sys/class/net/{iface}/phy80211");++ let phy_link = std::fs::read_link(&phy_path)+ .map_err(|e| AgentError(format!("could not read '{phy_path}': {e}")))?;++ let phy_name = phy_link+ .file_name()+ .and_then(|name| name.to_str())+ .ok_or_else(|| AgentError("could not parse PHY name".to_string()))?;++ let check_band_cmd = Command::new("iw")+ .args(["phy", phy_name, "info"])+ .output()+ .map_err(|e| AgentError(format!("failed to query PHY '{phy_name}': {e}")))?;++ if !check_band_cmd.status.success() {+ return Err(AgentError(format!("PHY '{phy_name}' could not be found")));+ }++ let output = String::from_utf8_lossy(&check_band_cmd.stdout);++ Ok(output.contains("5200 MHz") || output.contains("5200.0 MHz"))+}diff --git a/crates/gui/src/backend/mod.rs b/crates/gui/src/backend/mod.rsnew file mode 100644index 0000000..f1a73bb--- /dev/null+++ b/crates/gui/src/backend/mod.rs@@ -0,0 +1,18 @@+//! GUI-side backend facade.++mod client;+mod iface;+mod report;++pub mod decrypt;+pub mod settings;++pub use client::*;+pub use decrypt::*;+pub use iface::*;+pub use report::*;+pub use settings::*;++pub use airgorah_common::channel::is_valid_channel_filter;+pub use airgorah_common::deps;+pub use airgorah_common::handshake::get_handshakes;diff --git a/crates/gui/src/backend/report.rs b/crates/gui/src/backend/report.rsnew file mode 100644index 0000000..850eeff--- /dev/null+++ b/crates/gui/src/backend/report.rs@@ -0,0 +1,45 @@+use super::{get_aps, get_unlinked_clients};+use airgorah_common::types::{AP, Client};++use serde::Serialize;+use std::fs::File;+use std::io::Write;++#[derive(Debug, Serialize)]+struct Report {+ pub access_points: Vec<AP>,+ pub unlinked_clients: Vec<Client>,+}++#[derive(thiserror::Error, Debug)]+pub enum CapError {+ #[error("Input/Output error: {0}")]+ IoError(#[from] std::io::Error),++ #[error("Json error: {0}")]+ JsonError(#[from] serde_json::Error),+}++/// Save a JSON report of the current scan snapshot. Serializes the GUI's local+/// caches, so no privileged access is needed.+pub fn save_report(path: &str) -> Result<(), CapError> {+ let access_points = get_aps().values().cloned().collect::<Vec<AP>>();+ let unlinked_clients = get_unlinked_clients()+ .values()+ .cloned()+ .collect::<Vec<Client>>();++ let report = Report {+ access_points,+ unlinked_clients,+ };++ let json_data = serde_json::to_string::<Report>(&report)?;++ let mut file = File::create(path)?;+ file.write_all(json_data.as_bytes())?;++ log::info!("report saved to '{path}'");++ Ok(())+}diff --git a/crates/gui/src/backend/settings.rs b/crates/gui/src/backend/settings.rsnew file mode 100644index 0000000..8879423--- /dev/null+++ b/crates/gui/src/backend/settings.rs@@ -0,0 +1,61 @@+use crate::globals::*;+use airgorah_common::deps;+use airgorah_common::types::Settings;++use std::path::PathBuf;++/// Per-user config path (`$XDG_CONFIG_HOME/airgorah/config.toml`, falling back to+/// `~/.config/...`).+fn user_config_path() -> Option<PathBuf> {+ let base = std::env::var_os("XDG_CONFIG_HOME")+ .map(PathBuf::from)+ .filter(|p| p.is_absolute())+ .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;++ Some(base.join("airgorah").join("config.toml"))+}++/// Load settings from the user config file, falling back to the built-in+/// defaults when it does not exist yet.+pub fn load_settings() {+ let mut settings = Settings::default();++ if let Some(path) = user_config_path()+ && let Ok(content) = std::fs::read_to_string(&path)+ && let Ok(user) = toml::from_str::<Settings>(&content)+ {+ settings = user;+ }++ if settings.kill_network_manager && !deps::is_installed(deps::SYSTEMCTL) {+ settings.kill_network_manager = false;+ }++ log::debug!("settings loaded");++ *SETTINGS.lock().unwrap() = settings;+}++/// Save settings to the user config file.+pub fn save_settings(mut settings: Settings) {+ if settings.kill_network_manager && !deps::is_installed(deps::SYSTEMCTL) {+ settings.kill_network_manager = false;+ }++ if let Some(path) = user_config_path() {+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir).ok();+ }+ if let Ok(toml_settings) = toml::to_string(&settings) {+ std::fs::write(&path, toml_settings).ok();+ log::debug!("settings saved into '{}'", path.display());+ }+ }++ *SETTINGS.lock().unwrap() = settings;+}++/// Get the current settings.+pub fn get_settings() -> Settings {+ SETTINGS.lock().unwrap().clone()+}diff --git a/src/frontend/connections/app.rs b/crates/gui/src/frontend/connections/app.rssimilarity index 97%rename from src/frontend/connections/app.rsrename to crates/gui/src/frontend/connections/app.rsindex 41e85bb..79d812f 100755--- a/src/frontend/connections/app.rs+++ b/crates/gui/src/frontend/connections/app.rs@@ -714,12 +714,12 @@ fn start_app_refresh(app_data: Rc<AppData>) {};let background_color = match backend::get_attack_pool().get(&bssid) {- Some((_, attack_target)) => match &attack_target {- AttackedClients::All(_) => gdk::RGBA::RED,- AttackedClients::Selection(selection) => {+ Some(attack_state) => match &attack_state.target {+ AttackTarget::All => gdk::RGBA::RED,+ AttackTarget::Selection(selection) => {let mut color = gdk::RGBA::new(0.0, 0.0, 0.0, 0.0);- for (sel, _) in selection.iter() {+ for sel in selection.iter() {if sel == cli.mac.as_str() {color = gdk::RGBA::RED;}@@ -821,26 +821,6 @@ fn start_app_refresh(app_data: Rc<AppData>) {);}-fn start_handshake_refresh() {- std::thread::spawn(|| {- loop {- backend::update_handshakes().ok();-- std::thread::sleep(Duration::from_millis(1500));- }- });-}--fn start_vendor_refresh() {- std::thread::spawn(|| {- loop {- backend::update_vendors();-- std::thread::sleep(Duration::from_millis(500));- }- });-}-fn start_update_checker() {globals::UPDATE_PROC.lock()@@ -950,11 +930,7 @@ fn connect_capture_button(app_data: Rc<AppData>) {);}- for ap in backend::get_aps().values_mut() {- if ap.handshake {- ap.saved_handshake = Some(path.to_owned());- }- }+ backend::mark_handshakes_saved(&path);app_data.decrypt_gui.show(Some((path, bssid)));}@@ -986,8 +962,6 @@ pub fn connect(app: &Application, app_data: Rc<AppData>) {start_app_refresh(app_data.clone());- start_handshake_refresh();- start_vendor_refresh();start_update_checker();connect_hopping_button(app_data.clone());diff --git a/src/frontend/connections/deauth.rs b/crates/gui/src/frontend/connections/deauth.rssimilarity index 97%rename from src/frontend/connections/deauth.rsrename to crates/gui/src/frontend/connections/deauth.rsindex 047411a..8ec4cbc 100755--- a/src/frontend/connections/deauth.rs+++ b/crates/gui/src/frontend/connections/deauth.rs@@ -123,7 +123,9 @@ fn connect_attack_but(app_data: Rc<AppData>) {false => AttackSoftware::Mdk4,};- if attack_software == AttackSoftware::Mdk4 && !backend::has_dependency("mdk4") {+ if attack_software == AttackSoftware::Mdk4+ && !backend::deps::is_installed(backend::deps::MDK4)+ {return ErrorDialog::spawn(&app_data.deauth_gui.window,"Missing dependency",diff --git a/src/frontend/connections/decrypt.rs b/crates/gui/src/frontend/connections/decrypt.rssimilarity index 99%rename from src/frontend/connections/decrypt.rsrename to crates/gui/src/frontend/connections/decrypt.rsindex 0c2456e..40bf290 100755--- a/src/frontend/connections/decrypt.rs+++ b/crates/gui/src/frontend/connections/decrypt.rs@@ -356,7 +356,7 @@ fn connect_decrypt_button(app_data: Rc<AppData>) {let stack = app_data.decrypt_gui.stack.visible_child_name().unwrap();- if stack == "bruteforce" && !backend::has_dependency("crunch") {+ if stack == "bruteforce" && !backend::deps::is_installed(backend::deps::CRUNCH) {let err_msg = "\"crunch\" is not installed on your system, could not generate a wordlist from a charset";return ErrorDialog::spawn(&app_data.decrypt_gui.window, "Failed to run decryption", err_msg);}diff --git a/src/frontend/connections/interface.rs b/crates/gui/src/frontend/connections/interface.rssimilarity index 92%rename from src/frontend/connections/interface.rsrename to crates/gui/src/frontend/connections/interface.rsindex 4e27416..69380bb 100644--- a/src/frontend/connections/interface.rs+++ b/crates/gui/src/frontend/connections/interface.rs@@ -73,6 +73,15 @@ fn connect_interface_select(app_data: Rc<AppData>) {};let iface = list_store_get!(app_data.interface_gui.interface_model, &iter, 0, String);+ // First privileged action: start the agent now (prompts for auth once).+ if let Err(e) = backend::ensure_agent() {+ return ErrorDialog::spawn(+ &app_data.interface_gui.window,+ "Failed to start privileged agent",+ &e.to_string(),+ );+ }+match backend::enable_monitor_mode(&iface) {Ok(iface) => {if let Err(e) = backend::set_mac_address(&iface) {diff --git a/src/frontend/connections/mod.rs b/crates/gui/src/frontend/connections/mod.rssimilarity index 100%rename from src/frontend/connections/mod.rsrename to crates/gui/src/frontend/connections/mod.rsdiff --git a/src/frontend/connections/scan.rs b/crates/gui/src/frontend/connections/scan.rssimilarity index 97%rename from src/frontend/connections/scan.rsrename to crates/gui/src/frontend/connections/scan.rsindex eca1c8f..15b23df 100644--- a/src/frontend/connections/scan.rs+++ b/crates/gui/src/frontend/connections/scan.rs@@ -68,8 +68,7 @@ fn connect_restart_button(app_data: Rc<AppData>) {app_data,move |_| {backend::stop_scan_process().ok();- backend::get_aps().clear();- backend::get_unlinked_clients().clear();+ backend::reset_scan_data();app_data.app_gui.aps_model.clear();app_data.app_gui.cli_model.clear();@@ -132,11 +131,7 @@ fn connect_export_button(app_data: Rc<AppData>) {);}- for ap in backend::get_aps().values_mut() {- if ap.handshake {- ap.saved_handshake = Some(path.to_owned());- }- }+ backend::mark_handshakes_saved(&path);}if was_scanning {diff --git a/src/frontend/connections/settings.rs b/crates/gui/src/frontend/connections/settings.rssimilarity index 98%rename from src/frontend/connections/settings.rsrename to crates/gui/src/frontend/connections/settings.rsindex f5543de..a8e6b35 100644--- a/src/frontend/connections/settings.rs+++ b/crates/gui/src/frontend/connections/settings.rs@@ -105,7 +105,7 @@ fn connect_save_but(app_data: Rc<AppData>) {}pub fn connect(app_data: Rc<AppData>) {- if !backend::has_dependency("systemctl") {+ if !backend::deps::is_installed(backend::deps::SYSTEMCTL) {app_data.settings_gui.kill_network_managerdiff --git a/src/frontend/interfaces/app.rs b/crates/gui/src/frontend/interfaces/app.rssimilarity index 100%rename from src/frontend/interfaces/app.rsrename to crates/gui/src/frontend/interfaces/app.rsdiff --git a/src/frontend/interfaces/deauth.rs b/crates/gui/src/frontend/interfaces/deauth.rssimilarity index 100%rename from src/frontend/interfaces/deauth.rsrename to crates/gui/src/frontend/interfaces/deauth.rsdiff --git a/src/frontend/interfaces/decrypt.rs b/crates/gui/src/frontend/interfaces/decrypt.rssimilarity index 100%rename from src/frontend/interfaces/decrypt.rsrename to crates/gui/src/frontend/interfaces/decrypt.rsdiff --git a/src/frontend/interfaces/interface.rs b/crates/gui/src/frontend/interfaces/interface.rssimilarity index 100%rename from src/frontend/interfaces/interface.rsrename to crates/gui/src/frontend/interfaces/interface.rsdiff --git a/src/frontend/interfaces/mod.rs b/crates/gui/src/frontend/interfaces/mod.rssimilarity index 100%rename from src/frontend/interfaces/mod.rsrename to crates/gui/src/frontend/interfaces/mod.rsdiff --git a/src/frontend/interfaces/settings.rs b/crates/gui/src/frontend/interfaces/settings.rssimilarity index 100%rename from src/frontend/interfaces/settings.rsrename to crates/gui/src/frontend/interfaces/settings.rsdiff --git a/src/frontend/mod.rs b/crates/gui/src/frontend/mod.rssimilarity index 92%rename from src/frontend/mod.rsrename to crates/gui/src/frontend/mod.rsindex 2512810..53f592e 100644--- a/src/frontend/mod.rs+++ b/crates/gui/src/frontend/mod.rs@@ -17,7 +17,7 @@ pub fn build_ui(app: &Application) {gui_data.app_gui.show();- if let Err(e) = backend::app_setup() {+ if let Err(e) = backend::init() {PanicDialog::spawn(&gui_data.app_gui.window, &e.to_string())}}diff --git a/src/frontend/widgets/dialog.rs b/crates/gui/src/frontend/widgets/dialog.rssimilarity index 100%rename from src/frontend/widgets/dialog.rsrename to crates/gui/src/frontend/widgets/dialog.rsdiff --git a/src/frontend/widgets/icon_button.rs b/crates/gui/src/frontend/widgets/icon_button.rssimilarity index 100%rename from src/frontend/widgets/icon_button.rsrename to crates/gui/src/frontend/widgets/icon_button.rsdiff --git a/src/frontend/widgets/mod.rs b/crates/gui/src/frontend/widgets/mod.rssimilarity index 100%rename from src/frontend/widgets/mod.rsrename to crates/gui/src/frontend/widgets/mod.rsdiff --git a/crates/gui/src/globals.rs b/crates/gui/src/globals.rsnew file mode 100644index 0000000..b888b86--- /dev/null+++ b/crates/gui/src/globals.rs@@ -0,0 +1,35 @@+use airgorah_common::types::{AP, AttackState, Client, Settings};++use lazy_static::lazy_static;+use std::collections::HashMap;+use std::sync::Mutex;+use std::thread::JoinHandle;++pub static APP_ID: &str = "com.molivier.airgorah";+pub use airgorah_common::VERSION;++pub static APP_ICON: &[u8] =+ include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/icons/app_icon.png"));+pub static DEAUTH_ICON: &[u8] =+ include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/icons/deauth.png"));+pub static STOP_ICON: &[u8] =+ include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/icons/stop.png"));+pub static CAPTURE_ICON: &[u8] =+ include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/icons/capture.png"));++lazy_static! {+ pub static ref IFACE: Mutex<Option<String>> = Mutex::new(None);+ pub static ref UPDATE_PROC: Mutex<Option<JoinHandle<bool>>> = Mutex::new(None);++ // Local mirror of the agent's scan data, refreshed from each `GetScanData` snapshot.+ 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<HashMap<String, AttackState>> = Mutex::new(HashMap::new());++ /// GUI-side overlay: which APs have had their handshake saved to which file.+ /// Merged onto incoming snapshots for display (the agent knows nothing of it).+ pub static ref SAVED_HANDSHAKES: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());++ pub static ref SETTINGS: Mutex<Settings> = Mutex::new(Settings::default());+ pub static ref NEW_VERSION: Mutex<Option<String>> = Mutex::new(None);+}diff --git a/src/main.rs b/crates/gui/src/main.rssimilarity index 100%rename from src/main.rsrename to crates/gui/src/main.rsdiff --git a/crates/gui/src/types.rs b/crates/gui/src/types.rsnew file mode 100644index 0000000..b8f9b1d--- /dev/null+++ b/crates/gui/src/types.rs@@ -0,0 +1,15 @@+//! GUI-facing type definitions and re-exports.++pub use airgorah_common::types::{AP, AttackSoftware, AttackTarget, Settings};++pub struct BruteforceCharsetParams {+ pub lowercase: bool,+ pub uppercase: bool,+ pub numbers: bool,+ pub symbols: bool,+}++pub enum BruteforceCharset {+ Params(BruteforceCharsetParams),+ Specific(String),+}diff --git a/package/.desktop b/package/.desktopindex 519b3aa..e18a772 100644--- a/package/.desktop+++ b/package/.desktop@@ -1,9 +1,9 @@[Desktop Entry]Name=AirgorahComment=A WiFi security auditing software mainly based on aircrack-ng tools suite-Exec=pkexec airgorah+Exec=airgorahIcon=/usr/share/pixmaps/airgorah.png-ApplicationId=com.molivier.airgorah-Categories=Network;Monitor;Utility;GTK;+Categories=Network;Monitor;GTK;+StartupWMClass=com.molivier.airgorahType=ApplicationTerminal=falsediff --git a/package/.policy b/package/.policyindex d4d2fd1..a051a72 100644--- a/package/.policy+++ b/package/.policy@@ -3,16 +3,16 @@"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN""http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd"><policyconfig>- <action id="org.freedesktop.policykit.pkexec.airgorah">- <description>Run Airgorah</description>- <message>Authentication is required to run Airgorah</message>- <icon_name>accessories-text-editor</icon_name>+ <action id="org.freedesktop.policykit.pkexec.airgorah-agent">+ <description>Run the Airgorah privileged agent</description>+ <message>Authentication is required to start Airgorah's privileged agent</message>+ <icon_name>network-wireless</icon_name><defaults><allow_any>auth_admin</allow_any><allow_inactive>auth_admin</allow_inactive><allow_active>auth_admin</allow_active></defaults>- <annotate key="org.freedesktop.policykit.exec.path">/usr/bin/airgorah</annotate>+ <annotate key="org.freedesktop.policykit.exec.path">/usr/bin/airgorah-agent</annotate><annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate></action></policyconfig>\ No newline at end of filediff --git a/package/config.toml b/package/config.tomldeleted file mode 100644index 44471bb..0000000--- a/package/config.toml+++ /dev/null@@ -1,3 +0,0 @@-mac_address = "random"-display_hidden_ap = true-kill_network_manager = true\ No newline at end of filediff --git a/src/backend/app.rs b/src/backend/app.rsdeleted file mode 100755index e220c3b..0000000--- a/src/backend/app.rs+++ /dev/null@@ -1,94 +0,0 @@-use super::*;--#[derive(thiserror::Error, Debug)]-pub enum AppError {- #[error("Could not setup Ctrl-C (SIGINT) handler: {0}")]- SigintHandler(#[from] ctrlc::Error),-- #[error("Airgorah need root privilege to run")]- NotRoot,-- #[error("Missing required dependency: {0}")]- MissingDependency(String),-}--/// Check if the user is root, load settings, and check if all the required dependencies are installed-pub fn app_setup() -> Result<(), AppError> {- app_cleanup();-- ctrlc::set_handler(move || {- app_cleanup();- std::process::exit(1);- })?;-- if sudo::check() != sudo::RunningAs::Root {- return Err(AppError::NotRoot);- }-- load_settings();-- check_required_dependencies(&[- "sh",- "ip",- "iw",- "awk",- "xterm",- "airmon-ng",- "airodump-ng",- "aireplay-ng",- "aircrack-ng",- "mergecap",- "macchanger",- ])-}--/// Stop the scan process, kill all the attack process, and remove all the files created by the app-pub fn app_cleanup() {- stop_scan_process().ok();- stop_all_deauth_attacks();-- if let Some(ref iface) = get_iface() {- disable_monitor_mode(iface).ok();- }-- 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();-}--/// Check if a dependency is installed-pub fn has_dependency(dep: &str) -> bool {- which::which(dep).is_ok()-}--/// Check if all the required dependencies are installed-pub fn check_required_dependencies(deps: &[&str]) -> Result<(), AppError> {- for dep in deps {- if !has_dependency(dep) {- return Err(AppError::MissingDependency(dep.to_string()));- }- }- Ok(())-}--/// Check if a new version is available-pub fn check_update(current_version: &str) -> Option<String> {- let url = "https://api.github.com/repos/martin-olivier/airgorah/releases/latest";-- if let Ok(mut response) = ureq::get(url).call()- && let Ok(json) = response.body_mut().read_json::<serde_json::Value>()- && json["tag_name"] != current_version- {- let new_version = json["tag_name"].as_str().unwrap_or("unknown").to_owned();-- log::info!("a new version is available: \"{new_version}\"");-- return Some(new_version);- }-- log::info!("airgorah is up to date");-- None-}diff --git a/src/backend/capture.rs b/src/backend/capture.rsdeleted file mode 100755index 8f6f65f..0000000--- a/src/backend/capture.rs+++ /dev/null@@ -1,116 +0,0 @@-use super::*;-use crate::types::*;--use regex::Regex;-use serde::Serialize;-use std::fs::File;-use std::io::Write;-use std::process::Command;--#[derive(Debug, Serialize)]-struct Report {- pub access_points: Vec<AP>,- pub unlinked_clients: Vec<Client>,-}--#[derive(thiserror::Error, Debug)]-pub enum CapError {- #[error("Input/Output error: {0}")]- IoError(#[from] std::io::Error),-- #[error("Regex error: {0}")]- BadRegex(#[from] regex::Error),-- #[error("Json error: {0}")]- JsonError(#[from] serde_json::Error),-}--/// Update the handshake capture status of all APs-pub fn update_handshakes() -> Result<(), CapError> {- let handshakes = get_handshakes([- &(get_live_scan_path() + get_cap_ext()),- &(get_old_scan_path() + get_cap_ext()),- ])?;-- let mut aps = get_aps();-- for (bssid, _) in handshakes {- if let Some(ap) = aps.get_mut(&bssid) {- ap.handshake = true;- }- }-- log::trace!("handshakes updated");-- Ok(())-}--/// Get the access points infos of the handshakes contained in the capture file-pub fn get_handshakes<I, S>(args: I) -> Result<Vec<(String, String)>, CapError>-where- I: IntoIterator<Item = S>,- S: AsRef<std::ffi::OsStr>,-{- let capture_output = Command::new("aircrack-ng").args(args).output()?;-- let output = String::from_utf8_lossy(&capture_output.stdout).to_string();-- let re = Regex::new(r"\s+(\d+)\s+([\w:]+)\s+(.*)\s+WPA \((\d+)\s+handshake.*\)")?;-- let mut handshakes = vec![];-- for line in output.lines() {- let caps = match re.captures(line) {- Some(caps) => caps,- None => continue,- };-- let bssid = caps[2].to_string();- let essid = caps[3].trim().to_string();- let handshake_count = caps[4].to_string();-- if handshake_count.parse::<i32>().unwrap_or(0) > 0 {- handshakes.push((- bssid,- match essid.is_empty() {- true => "hidden".to_string(),- false => essid,- },- ));- }- }-- Ok(handshakes)-}--/// Save the current capture to a file-pub fn save_capture(path: &str) -> Result<(), CapError> {- std::fs::copy(get_old_scan_path() + get_cap_ext(), path)?;-- log::info!("capture saved to '{path}'");-- Ok(())-}--/// Save the capture report to a file-pub fn save_report(path: &str) -> Result<(), CapError> {- let access_points = get_aps().values().cloned().collect::<Vec<AP>>();- let unlinked_clients = get_unlinked_clients()- .values()- .cloned()- .collect::<Vec<Client>>();-- let report = Report {- access_points,- unlinked_clients,- };-- let json_data = serde_json::to_string::<Report>(&report)?;-- let mut file = File::create(path)?;- file.write_all(json_data.as_bytes())?;-- log::info!("report saved to '{path}'");-- Ok(())-}diff --git a/src/backend/settings.rs b/src/backend/settings.rsdeleted file mode 100644index e0137e2..0000000--- a/src/backend/settings.rs+++ /dev/null@@ -1,41 +0,0 @@-use crate::globals::*;-use crate::types::*;--use std::path::Path;--/// Load settings from the config file, otherwise use default settings-pub fn load_settings() {- if Path::new(CONFIG_PATH).exists() {- let config = std::fs::read_to_string(CONFIG_PATH).unwrap_or_default();- let mut settings: Settings = toml::from_str(&config).unwrap_or_default();-- if settings.kill_network_manager && !super::has_dependency("systemctl") {- settings.kill_network_manager = false;- }-- log::debug!("settings loaded from '{CONFIG_PATH}'");-- *SETTINGS.lock().unwrap() = settings;- }-}--/// Save settings to the config file-pub fn save_settings(mut settings: Settings) {- if settings.kill_network_manager && !super::has_dependency("systemctl") {- settings.kill_network_manager = false;- }-- if Path::new(CONFIG_PATH).exists()- && let Ok(toml_settings) = toml::to_string(&settings)- {- std::fs::write(CONFIG_PATH, toml_settings).ok();-- log::debug!("settings saved into '{CONFIG_PATH}'");- }- *SETTINGS.lock().unwrap() = settings;-}--/// Get the current settings-pub fn get_settings() -> Settings {- SETTINGS.lock().unwrap().clone()-}diff --git a/src/backend/vendors.rs b/src/backend/vendors.rsdeleted file mode 100644index 927e50a..0000000--- a/src/backend/vendors.rs+++ /dev/null@@ -1,38 +0,0 @@-use crate::globals::*;--use std::collections::HashMap;--include!(concat!(env!("OUT_DIR"), "/vendors.rs"));--pub fn find_vendor(mac: &str) -> String {- let mut vendors = VENDORS_CACHE.lock().unwrap();-- match vendors.get(mac) {- Some(vendor) => vendor.clone(),- None => {- vendors.insert(mac.to_string(), String::new());-- String::new()- }- }-}--pub fn update_vendors() {- let vendors_cache_copy = VENDORS_CACHE.lock().unwrap().clone();-- for (mac, vendor) in vendors_cache_copy {- if vendor.is_empty() {- let mut mac_to_find = mac[..13].to_string();- let mut vendor_name = String::from("Unknown");-- while !mac_to_find.is_empty() {- if let Some(item) = VENDORS.get(mac_to_find.as_str()) {- vendor_name = item.to_string();- break;- }- mac_to_find.pop();- }- VENDORS_CACHE.lock().unwrap().insert(mac, vendor_name);- }- }-}diff --git a/src/globals.rs b/src/globals.rsdeleted file mode 100644index 27a6eed..0000000--- a/src/globals.rs+++ /dev/null@@ -1,37 +0,0 @@-use crate::types::*;--use lazy_static::lazy_static;-use std::collections::HashMap;-use std::process::Child;-use std::sync::Mutex;-use std::thread::JoinHandle;--pub static APP_ID: &str = "com.molivier.airgorah";-pub static VERSION: &str = "v0.7.4";--pub static LIVE_SCAN_PATH: &str = "/tmp/airgorah_live_scan";-pub static OLD_SCAN_PATH: &str = "/tmp/airgorah_old_scan";-pub static MERGE_SCAN_PATH: &str = "/tmp/airgorah_merge_scan";--pub static CONFIG_PATH: &str = "/etc/airgorah/config.toml";--pub static APP_ICON: &[u8] = include_bytes!("../icons/app_icon.png");-pub static DEAUTH_ICON: &[u8] = include_bytes!("../icons/deauth.png");-pub static STOP_ICON: &[u8] = include_bytes!("../icons/stop.png");-pub static CAPTURE_ICON: &[u8] = include_bytes!("../icons/capture.png");--pub type AttackPool = HashMap<String, (AP, AttackedClients)>;--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 UPDATE_PROC: Mutex<Option<JoinHandle<bool>>> = Mutex::new(None);- pub static ref SCAN_PROC: Mutex<Option<Child>> = 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());- pub static ref VENDORS_CACHE: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());- pub static ref SETTINGS: Mutex<Settings> = Mutex::new(Settings::default());- pub static ref NEW_VERSION: Mutex<Option<String>> = Mutex::new(None);- pub static ref SERVICES_TO_RESTORE: Mutex<Vec<String>> = Mutex::new(vec![]);-}diff --git a/src/types.rs b/src/types.rsdeleted file mode 100644index b3048c3..0000000--- a/src/types.rs+++ /dev/null@@ -1,71 +0,0 @@-use serde::{Deserialize, Serialize};-use std::collections::HashMap;-use std::process::Child;--pub enum AttackedClients {- All(Child),- Selection(Vec<(String, Child)>),-}--#[derive(PartialEq)]-pub enum AttackSoftware {- Aireplay,- Mdk4,-}--pub struct BruteforceCharsetParams {- pub lowercase: bool,- pub uppercase: bool,- pub numbers: bool,- pub symbols: bool,-}--pub enum BruteforceCharset {- Params(BruteforceCharsetParams),- Specific(String),-}--#[derive(Clone, Debug, Serialize, Deserialize)]-pub struct AP {- pub essid: String,- pub bssid: String,- pub band: String,- pub channel: String,- pub speed: String,- pub power: String,- pub privacy: String,- pub hidden: bool,- pub handshake: bool,- pub saved_handshake: Option<String>,- pub first_time_seen: String,- pub last_time_seen: String,- pub clients: HashMap<String, Client>,-}--#[derive(Clone, Debug, Serialize, Deserialize)]-pub struct Client {- pub mac: String,- pub packets: String,- pub power: String,- pub first_time_seen: String,- pub last_time_seen: String,- pub vendor: String,- pub probes: String,-}--#[derive(Clone, Debug, Serialize, Deserialize)]-pub struct Settings {- pub mac_address: String,- pub display_hidden_ap: bool,- pub kill_network_manager: bool,-}--impl Default for Settings {- fn default() -> Self {- Self {- mac_address: "random".to_string(),- display_hidden_ap: true,- kill_network_manager: true,- }- }-}