//! Persistent UI-side data under `~/wifi_lab`: //! - `labels.json` — user-assigned names by MAC (APs and clients share one //! namespace; a MAC is unique). //! - `captures.jsonl` — every complete handshake / PMKID capture, one JSON //! line each, appended as they arrive and reloaded at startup (the //! cracker keeps working across restarts without re-attacking). //! //! UI-only data — the privileged service never touches it. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use crate::common::{HandshakeCapture, MacAddr, PmkidCapture}; /// `~/wifi_lab`. When HOME is unset the store lives under the system temp /// dir (stable absolute path, independent of the caller's cwd) and a /// warning is logged. pub fn data_dir() -> PathBuf { data_dir_impl(std::env::var_os("HOME").as_deref(), &std::env::temp_dir()) } /// Split out of [`data_dir`] for tests: `home` is the raw HOME value, /// `tmp` the fallback base when HOME is unset/empty. fn data_dir_impl(home: Option<&std::ffi::OsStr>, tmp: &Path) -> PathBuf { let base = match home { Some(h) if !h.is_empty() => PathBuf::from(h), _ => { eprintln!( "wifi_lab: HOME is unset — data dir is {} (stable path, but outside any home)", tmp.join("wifi_lab").display() ); return tmp.join("wifi_lab"); } }; let new = base.join("wifi_lab"); let old = base.join("wifilab"); // One-time move from the pre-rename location. Racing instances (or a // partial earlier migration) can make the target appear between the // check and the rename: rename unconditionally and treat "target // exists" as a finished migration, not an error. if old.exists() { match std::fs::rename(&old, &new) { Ok(()) => {} Err(e) if new.exists() => { let _ = e; // lost the race — the target is the live store } Err(e) => eprintln!( "wifi_lab: could not migrate {} → {} ({e}); starting fresh at the new path", old.display(), new.display() ), } } new } /// Atomically replace `path` with `body`: write to a unique sibling tmp /// file (`.tmp.-`), fsync the file, rename over the /// target, then fsync the containing directory so the rename itself is /// durable. A crash between the steps can leave the tmp file behind — /// [`cleanup_stale_tmp`] removes it on the next load. fn write_atomic(path: &Path, body: &str) -> Result<()> { use std::io::Write as _; let dir = path.parent().expect("store path has a parent"); std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_nanos()) .unwrap_or(0); let name = path .file_name() .and_then(|n| n.to_str()) .expect("store path has a file name"); let tmp = path.with_file_name(format!("{name}.tmp.{}-{nanos}", std::process::id())); let write_result = (|| -> Result<()> { let mut f = std::fs::File::create(&tmp).with_context(|| format!("creating {}", tmp.display()))?; f.write_all(body.as_bytes()) .with_context(|| format!("writing {}", tmp.display()))?; f.sync_all() .with_context(|| format!("fsyncing {}", tmp.display()))?; Ok(()) })(); if let Err(e) = write_result { let _ = std::fs::remove_file(&tmp); return Err(e); } std::fs::rename(&tmp, path) .with_context(|| format!("renaming {} → {}", tmp.display(), path.display()))?; std::fs::File::open(dir) .and_then(|d| d.sync_all()) .with_context(|| format!("fsyncing {}", dir.display()))?; Ok(()) } /// Remove stale `.tmp.*` siblings of `path` left over from a crashed /// atomic write. Called on every load; failures are ignored (a read-only /// dir must not break loading). fn cleanup_stale_tmp(path: &Path) { let Some(dir) = path.parent() else { return }; let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return; }; let prefix = format!("{name}.tmp."); let Ok(entries) = std::fs::read_dir(dir) else { return; }; for entry in entries.flatten() { let stale = entry .file_name() .to_str() .is_some_and(|n| n.starts_with(&prefix)); if stale { let _ = std::fs::remove_file(entry.path()); } } } fn labels_path() -> PathBuf { data_dir().join("labels.json") } fn captures_path() -> PathBuf { data_dir().join("captures.jsonl") } fn session_path() -> PathBuf { data_dir().join("crack-session.json") } /// One persisted capture (tagged JSON line in `captures.jsonl`). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum StoredCapture { Handshake(HandshakeCapture), Pmkid(PmkidCapture), } impl StoredCapture { /// Display identity used for dedup on load. fn id(&self) -> String { match self { StoredCapture::Handshake(h) => format!("hs:{}:{}", h.ap, h.client), StoredCapture::Pmkid(p) => format!("pmkid:{}", p.ap), } } } fn load_labels_from(path: &Path) -> Result> { cleanup_stale_tmp(path); let raw = match std::fs::read_to_string(path) { Ok(s) => s, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { return Ok(BTreeMap::new()); } Err(e) => return Err(e).context("reading labels.json"), }; let by_str: BTreeMap = serde_json::from_str(&raw).context("parsing labels.json")?; let mut out = BTreeMap::new(); for (mac, label) in by_str { let mac: MacAddr = mac .parse() .with_context(|| format!("bad MAC key {mac:?}"))?; if !label.is_empty() { out.insert(mac, label); } } Ok(out) } /// Load all labels; a missing file is an empty store, a corrupt one is an /// error (callers log it and start empty rather than clobbering). pub fn load() -> Result> { load_labels_from(&labels_path()) } fn save_labels_to(path: &Path, labels: &BTreeMap) -> Result<()> { let by_str: BTreeMap = labels.iter().map(|(mac, l)| (mac.to_string(), l)).collect(); let body = serde_json::to_string_pretty(&by_str).expect("string map serialization"); write_atomic(path, &body) } /// Persist the whole label map (labels are few; rewriting is cheap, made /// crash-safe by [`write_atomic`]). pub fn save(labels: &BTreeMap) -> Result<()> { save_labels_to(&labels_path(), labels) } fn append_capture_to(path: &Path, cap: &StoredCapture) -> Result<()> { let dir = path.parent().expect("captures path has a parent"); std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; use std::io::Write as _; let mut f = std::fs::OpenOptions::new() .create(true) .append(true) .open(path) .with_context(|| format!("opening {}", path.display()))?; let line = serde_json::to_string(cap).context("serializing capture")?; writeln!(f, "{line}").with_context(|| format!("appending to {}", path.display())) } /// Append one capture to `captures.jsonl`. Called the moment a capture /// arrives — the file survives a crash right after. pub fn append_capture(cap: &StoredCapture) -> Result<()> { append_capture_to(&captures_path(), cap) } fn load_captures_from(path: &Path) -> Result> { let raw = match std::fs::read_to_string(path) { Ok(s) => s, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), Err(e) => return Err(e).context("reading captures.jsonl"), }; let mut seen = std::collections::BTreeSet::new(); let mut out = Vec::new(); for (n, line) in raw.lines().enumerate() { let line = line.trim(); if line.is_empty() { continue; } match serde_json::from_str::(line) { Ok(cap) => { if seen.insert(cap.id()) { out.push(cap); } } // One corrupt line must not kill the whole archive. Err(e) => eprintln!( "wifi_lab: skipping corrupt captures.jsonl line {}: {e}", n + 1 ), } } Ok(out) } /// Load every stored capture (deduped by AP/client identity). A corrupt /// FILE is an error; individual corrupt lines are skipped. pub fn load_captures() -> Result> { load_captures_from(&captures_path()) } // --------------------------------------------------------------------------- // Crack session (resume): the interrupted run's position, so a later start // — in this or a future session — continues instead of restarting. // --------------------------------------------------------------------------- /// Current on-disk session format. v2: `done` is an exact RAW stream /// position — resume seeks/skips past exactly the already-verified /// candidates for every attack mode (see `attack.rs` position plumbing). pub const SESSION_VERSION: u32 = 2; /// Older files carry no `version` field: they are v1. fn default_version() -> u32 { 1 } /// A stopped (not finished) crack run: which capture, which attack, how /// far it had gotten. Written throttle-throttled on progress and once on /// stop; deleted when the run finds the password or exhausts the space. /// /// Version semantics: v1 (no `version` field) counted YIELDED candidates /// in `done`, which drifted from the raw stream once the PMK cache skipped /// entries or rules/hybrid filtered candidates — resuming best-effort may /// REDO some work but never skips untried candidates. v2 counts exact raw /// positions; resume is exact (`never redo, never skip`) for wordlist / /// rules / hybrid / bruteforce / rainbow. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CrackSession { /// File format version; [`SESSION_VERSION`] for newly written files. #[serde(default = "default_version")] pub version: u32, pub capture: StoredCapture, pub attack: crate::attack::Attack, /// Candidates verified so far (resume seeks/skips past these); a raw /// stream position in v2 files (see above). pub done: u64, /// Worst-case total of the run (see the ETA plumbing), when countable. pub total: Option, } impl CrackSession { /// A v2 session for the interrupted run. pub fn new( capture: StoredCapture, attack: crate::attack::Attack, done: u64, total: Option, ) -> Self { CrackSession { version: SESSION_VERSION, capture, attack, done, total, } } } fn save_session_to(path: &Path, session: &CrackSession) -> Result<()> { let json = serde_json::to_string_pretty(session).context("serializing crack session")?; write_atomic(path, &json) } /// Persist the session (crash-safe via [`write_atomic`]). pub fn save_session(session: &CrackSession) -> Result<()> { save_session_to(&session_path(), session) } fn load_session_from(path: &Path) -> Result> { cleanup_stale_tmp(path); match std::fs::read_to_string(path) { Ok(s) => Ok(Some( serde_json::from_str(&s).context("parsing crack-session.json")?, )), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e).context("reading crack-session.json"), } } /// Load the saved session; `None` when no run was interrupted. A corrupt /// file is an error (callers log it and start fresh rather than resuming /// garbage). pub fn load_session() -> Result> { load_session_from(&session_path()) } /// Drop the saved session (run found/exhausted, or user discarded). /// Missing file is fine. pub fn clear_session() -> Result<()> { match std::fs::remove_file(session_path()) { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(e) => Err(e).context("removing crack-session.json"), } } // --------------------------------------------------------------------------- // Per-SSID PMK cache: `~/wifi_lab/cache/.pmk` in rainbow text // format — PMKs computed on earlier CPU runs are reusable for ANY capture // of the same SSID without re-running PBKDF2. // --------------------------------------------------------------------------- /// `~/wifi_lab/cache` — created on use by the cache readers/writers. pub fn cache_dir() -> PathBuf { data_dir().join("cache") } /// Cache table path for one SSID: lowercase hex of the raw SSID bytes + /// `.pmk` (filesystem-safe for arbitrary SSID encodings). pub fn cache_file(ssid: &str) -> PathBuf { let hex: String = ssid.bytes().map(|b| format!("{b:02x}")).collect(); cache_dir().join(format!("{hex}.pmk")) } // --------------------------------------------------------------------------- // Crack profiles + recent wordlists (`~/wifi_lab/profiles.json`): user-saved // attack setups for one-click reuse on the cracker page. // --------------------------------------------------------------------------- /// One saved attack setup (mode/wl/rules as the cracker page fields). #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct CrackProfile { pub name: String, pub mode: String, pub wordlist: String, pub rules: Option, } /// The whole profiles file: saved presets + MRU wordlist list (cap 5). #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct Profiles { pub profiles: Vec, pub recent_wordlists: Vec, } fn profiles_path() -> PathBuf { data_dir().join("profiles.json") } fn load_profiles_from(path: &Path) -> Result { cleanup_stale_tmp(path); match std::fs::read_to_string(path) { Ok(s) => match serde_json::from_str::(&s) { Ok(p) => Ok(p), Err(e) => { eprintln!("wifi_lab: profiles.json unreadable ({e}), starting fresh"); Ok(Profiles::default()) } }, Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Profiles::default()), Err(e) => Err(e).context("reading profiles.json"), } } /// Load profiles; missing or unparseable file starts empty (never clobbers). pub fn load_profiles() -> Result { load_profiles_from(&profiles_path()) } fn save_profiles_to(path: &Path, p: &Profiles) -> Result<()> { let body = serde_json::to_string_pretty(p).context("serializing profiles")?; write_atomic(path, &body) } /// Persist profiles (crash-safe via [`write_atomic`]). pub fn save_profiles(p: &Profiles) -> Result<()> { save_profiles_to(&profiles_path(), p) } /// MRU-insert a wordlist path at the front of `recent_wordlists`, deduped, /// capped at 5. pub fn remember_wordlist(p: &mut Profiles, path: &str) { p.recent_wordlists.retain(|w| w != path); p.recent_wordlists.insert(0, path.to_string()); p.recent_wordlists.truncate(5); } #[cfg(test)] mod tests { use super::*; fn tmp(name: &str) -> PathBuf { std::env::temp_dir().join(format!("wifi_lab-store-test-{}-{name}", std::process::id())) } #[test] fn labels_roundtrip() { let dir = tmp("labels"); let path = dir.join("labels.json"); let mac: MacAddr = "aa:bb:cc:dd:ee:ff".parse().unwrap(); let mut labels = BTreeMap::new(); labels.insert(mac, "living room".to_string()); save_labels_to(&path, &labels).unwrap(); let back = load_labels_from(&path).unwrap(); assert_eq!(back.get(&mac).map(String::as_str), Some("living room")); let _ = std::fs::remove_dir_all(&dir); } #[test] fn labels_missing_file_is_empty() { let back = load_labels_from(&tmp("nope").join("labels.json")).unwrap(); assert!(back.is_empty()); } #[test] fn session_roundtrip_and_missing() { let dir = tmp("session"); let path = dir.join("crack-session.json"); assert!(load_session_from(&path).unwrap().is_none()); let session = CrackSession::new( StoredCapture::Pmkid(PmkidCapture { ap: "aa:bb:cc:dd:ee:ff".parse().unwrap(), client: "11:22:33:44:55:66".parse().unwrap(), essid: "testnet".into(), pmkid: [7u8; 16], }), crate::attack::Attack::Bruteforce { charset: b"01".to_vec(), min: 8, max: 10, freq_order: true, }, 12_345, Some(1_114_100), ); assert_eq!(session.version, SESSION_VERSION); save_session_to(&path, &session).unwrap(); let back = load_session_from(&path).unwrap().expect("saved"); assert_eq!(back, session); let _ = std::fs::remove_dir_all(&dir); } #[test] fn session_v1_file_loads_with_version_1() { // Files written before the version field existed (no "version" // key) must still parse: best-effort resume (may redo some work, // never skips untried candidates). let dir = tmp("session-v1"); let path = dir.join("crack-session.json"); std::fs::create_dir_all(&dir).unwrap(); // Field shapes are what the current serializers emit (v1 and v2 // differ ONLY in the added `version` key): MACs serialize as // 6-byte arrays, Attack as an externally-tagged enum. let v1 = serde_json::json!({ "capture": { "kind": "pmkid", "ap": [170, 187, 204, 221, 238, 255], "client": [17, 34, 51, 68, 85, 102], "essid": "testnet", "pmkid": [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7], }, "attack": { "Bruteforce": { "charset": [48, 49], "min": 8, "max": 10, "freq_order": false } }, "done": 4242u64, "total": null, }); std::fs::write(&path, serde_json::to_string(&v1).unwrap()).unwrap(); let back = load_session_from(&path).unwrap().expect("v1 parses"); assert_eq!(back.version, 1); assert_eq!(back.done, 4242); assert_eq!(back.total, None); let _ = std::fs::remove_dir_all(&dir); } #[test] fn stale_tmp_files_cleaned_on_load() { let dir = tmp("tmpc"); let path = dir.join("labels.json"); let mac: MacAddr = "aa:bb:cc:dd:ee:ff".parse().unwrap(); let mut labels = BTreeMap::new(); labels.insert(mac, "x".to_string()); save_labels_to(&path, &labels).unwrap(); // No tmp file survives a successful save. let left: Vec<_> = std::fs::read_dir(&dir) .unwrap() .flatten() .map(|e| e.file_name().to_string_lossy().into_owned()) .collect(); assert_eq!(left, vec!["labels.json"], "save leaves no tmp: {left:?}"); // Crashed-write leftovers are removed by the next load, labels // still load fine, and unrelated files are untouched. std::fs::write(dir.join("labels.json.tmp.1-2"), "partial junk").unwrap(); std::fs::write(dir.join("other.tmp.1-2"), "not ours").unwrap(); let back = load_labels_from(&path).unwrap(); assert_eq!(back.get(&mac).map(String::as_str), Some("x")); let left: Vec<_> = std::fs::read_dir(&dir) .unwrap() .flatten() .map(|e| e.file_name().to_string_lossy().into_owned()) .collect(); assert!(left.contains(&"labels.json".to_string())); assert!( left.contains(&"other.tmp.1-2".to_string()), "unrelated kept" ); assert!( !left.iter().any(|n| n.starts_with("labels.json.tmp.")), "stale gone: {left:?}" ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn data_dir_home_unset_uses_tmp_base() { let got = data_dir_impl(None, Path::new("/tmpbase")); assert_eq!(got, PathBuf::from("/tmpbase/wifi_lab")); let got = data_dir_impl(Some(std::ffi::OsStr::new("")), Path::new("/tmpbase")); assert_eq!(got, PathBuf::from("/tmpbase/wifi_lab")); } #[test] fn data_dir_migration_and_race() { let dir = tmp("datadir"); let home = dir.join("home"); // Migration: old `wifilab` moves to `wifi_lab`. std::fs::create_dir_all(home.join("wifilab/sub")).unwrap(); std::fs::write(home.join("wifilab/sub/f.json"), "{}").unwrap(); let got = data_dir_impl(Some(home.as_os_str()), Path::new("/tmpbase")); assert_eq!(got, home.join("wifi_lab")); assert!(home.join("wifi_lab/sub/f.json").is_file()); assert!(!home.join("wifilab").exists()); // Race: both exist (a second instance already created the target). // The rename fails; the target wins, no error, old dir left alone. std::fs::create_dir_all(home.join("wifilab")).unwrap(); std::fs::write(home.join("wifilab/stale.marker"), "x").unwrap(); let got = data_dir_impl(Some(home.as_os_str()), Path::new("/tmpbase")); assert_eq!(got, home.join("wifi_lab")); assert!(home.join("wifi_lab").is_dir()); // Neither outcome is an error; the function must not panic. let _ = std::fs::remove_dir_all(&dir); } #[test] fn captures_append_and_load_dedups() { let dir = tmp("caps"); let path = dir.join("captures.jsonl"); let pm = PmkidCapture { ap: "aa:bb:cc:dd:ee:ff".parse().unwrap(), client: "11:22:33:44:55:66".parse().unwrap(), essid: "testnet".into(), pmkid: [7u8; 16], }; let hs = HandshakeCapture::new( "aa:bb:cc:dd:ee:ff".parse().unwrap(), "11:22:33:44:55:66".parse().unwrap(), "testnet".into(), [1u8; 32], [2u8; 32], [3u8; 16], vec![9u8; 8], 2, ); let cap_pm = StoredCapture::Pmkid(pm.clone()); let cap_hs = StoredCapture::Handshake(hs.clone()); append_capture_to(&path, &cap_pm).unwrap(); append_capture_to(&path, &cap_pm).unwrap(); // duplicate line on disk append_capture_to(&path, &cap_hs).unwrap(); // One corrupt line must not kill the rest. std::fs::write( &path, format!("{}{{not json}}\n", std::fs::read_to_string(&path).unwrap()), ) .unwrap(); let back = load_captures_from(&path).unwrap(); assert_eq!(back, vec![cap_pm, cap_hs]); let _ = std::fs::remove_dir_all(&dir); } #[test] fn captures_missing_file_is_empty() { let back = load_captures_from(&tmp("nope").join("captures.jsonl")).unwrap(); assert!(back.is_empty()); } #[test] fn profiles_roundtrip_and_missing() { let dir = tmp("profiles"); let path = dir.join("profiles.json"); // Missing file = empty store. assert_eq!(load_profiles_from(&path).unwrap().profiles.len(), 0); let mut p = Profiles { profiles: vec![ CrackProfile { name: "wl:rockyou".into(), mode: "wordlist".into(), wordlist: "/usr/share/wordlists/rockyou.txt".into(), rules: None, }, CrackProfile { name: "rules:corp".into(), mode: "rules".into(), wordlist: "/home/x/wl.txt".into(), rules: Some("/home/x/best64.rule".into()), }, ], recent_wordlists: vec!["/a.txt".into(), "/b.txt".into()], }; p.recent_wordlists.insert(0, "/c.txt".into()); save_profiles_to(&path, &p).unwrap(); let back = load_profiles_from(&path).unwrap(); assert_eq!(back.profiles.len(), 2); assert_eq!(back.profiles[0].name, "wl:rockyou"); assert_eq!( back.profiles[1].rules.as_deref(), Some("/home/x/best64.rule") ); assert_eq!(back.recent_wordlists, p.recent_wordlists); // Unparseable file = empty store, no error (never clobbered). std::fs::write(&path, "{{not json").unwrap(); let back = load_profiles_from(&path).unwrap(); assert!(back.profiles.is_empty() && back.recent_wordlists.is_empty()); let _ = std::fs::remove_dir_all(&dir); } #[test] fn remember_wordlist_front_insert_dedup_cap5() { let mut p = Profiles::default(); for w in ["/a", "/b", "/c", "/d", "/e", "/a"] { remember_wordlist(&mut p, w); } // "/a" re-remembered: moves to front, no duplicate. assert_eq!(p.recent_wordlists, vec!["/a", "/e", "/d", "/c", "/b"]); // Sixth distinct path evicts the oldest. remember_wordlist(&mut p, "/f"); assert_eq!(p.recent_wordlists, vec!["/f", "/a", "/e", "/d", "/c"]); } #[test] fn cache_file_hex_naming() { let p = cache_file("testnet"); assert_eq!( p.file_name().unwrap().to_str().unwrap(), "746573746e6574.pmk" ); // Hex is lowercase and 2 chars per byte; non-ASCII bytes safe. let p2 = cache_file("aé"); assert_eq!(p2.file_name().unwrap().to_str().unwrap(), "61c3a9.pmk"); assert_eq!(p.parent().unwrap(), cache_dir()); } }