//! Headless `wifi_lab crack` subcommand: crack one capture file with no UI, //! no radio and no root. The capture file is hc22000 text (one `WPA*01*` / //! `WPA*02*` line per capture, hashcat -m 22000); the first line that parses //! is the target, everything else is ignored. //! //! Exit codes: 0 password found, 1 keyspace exhausted, 2 usage/IO/backend //! error (backend = `Event::CrackError`, e.g. GPU device lost). use std::io::Write; use std::path::PathBuf; use std::time::{Duration, Instant}; use crate::attack::{self, Attack}; use crate::common::Event; use crate::crypto::{self, CrackTarget}; /// Owned, clap-free view of the `crack` subcommand flags (main.rs converts /// its derived `CrackArgs` 1:1 into this so the CLI logic stays testable). pub struct CliCrack { /// Path to the hc22000 capture file. pub capture: String, /// Attack mode: "wordlist" | "rules" | "bruteforce". pub mode: String, /// Wordlist path (wordlist-family modes). pub wordlist: Option, /// Rules file path (rules mode). pub rules: Option, /// Bruteforce-ish minimum length. pub min: usize, /// Bruteforce-ish maximum length. pub max: usize, /// Hybrid: wordlist × append-charset sweep (requires `wordlist`). pub hybrid: bool, pub lower: bool, pub upper: bool, pub digits: bool, pub special: bool, /// Force the CPU backend (also disables PMK-cache writes). pub cpu: bool, } /// Union of the toggled charset presets; when nothing is toggled the /// default is lower+digits (the most common password soup). fn cli_charset(args: &CliCrack) -> Vec { let (mut lower, mut digits) = (args.lower, args.digits); if !args.lower && !args.upper && !args.digits && !args.special { lower = true; digits = true; } attack::charset::compose(lower, args.upper, digits, args.special, &[]) } fn build_attack(args: &CliCrack) -> Result { let wordlist = |what: &str| -> Result { args.wordlist .clone() .map(PathBuf::from) .ok_or_else(|| format!("error: --wordlist is required for {what} mode")) }; if args.hybrid { return Ok(Attack::Hybrid { wordlist: wordlist("hybrid")?, charset: cli_charset(args), min: args.min, max: args.max, }); } match args.mode.as_str() { "rules" => Ok(Attack::Rules { wordlist: wordlist("rules")?, rules: args .rules .clone() .map(PathBuf::from) .ok_or_else(|| "error: --rules is required for rules mode".to_string())?, }), "bruteforce" => Ok(Attack::Bruteforce { charset: cli_charset(args), min: args.min, max: args.max, freq_order: true, }), _ => Ok(Attack::Wordlist(wordlist("wordlist")?)), } } /// First crackable target in an hc22000 file: the bare `WPA*` prefix hashcat /// emits is stripped (`crypto::parse_hc22000` takes the bare form). fn first_target(path: &str) -> Result { let text = std::fs::read_to_string(path) .map_err(|e| format!("error: cannot read capture file {path}: {e}"))?; for line in text.lines() { let stripped = line.strip_prefix("WPA*").unwrap_or(line); if let Ok(target) = crypto::parse_hc22000(stripped) { return Ok(target); } } Err(format!("error: no crackable WPA* line in {path}")) } /// Run the crack to completion on the calling thread. Progress prints are /// throttled to one line per 2 s; all engine `Log` lines pass through. pub fn run_crack_cli(args: CliCrack, out: &mut dyn Write) -> i32 { let target = match first_target(&args.capture) { Ok(t) => t, Err(msg) => { let _ = writeln!(out, "{msg}"); return 2; } }; let attack = match build_attack(&args) { Ok(a) => a, Err(msg) => { let _ = writeln!(out, "{msg}"); return 2; } }; if let Err(e) = attack.validate() { let _ = writeln!(out, "error: {e:#}"); return 2; } let _ = writeln!(out, "target: {}", target.describe()); let _ = writeln!(out, "attack: {}", attack.describe()); let (tx, rx) = crossbeam_channel::unbounded(); let _stop = attack::spawn_crack(target.describe(), target, attack, 0, tx, args.cpu); crack_event_loop(&rx, out) } /// Consume crack-job `Event`s until the job terminates; returns the process /// exit code: 0 password found, 1 keyspace exhausted, 2 error. Extracted /// from `run_crack_cli` so the verdict logic is testable without a real /// crack worker. /// /// `Event::CrackError` (backend failure — NOT exhaustion) prints its reason /// with the same `error:` prefix as other errors and forces exit 2 even if /// a `CrackStopped { found: false }` follows (the error supersedes the /// stop verdict, unless a password was already reported). Capture events /// (handshakes/PMKIDs, incl. partial M2+M3 pairs) carry no crack verdict /// here — CLI targets come from the capture file, not from events — and /// are ignored. fn crack_event_loop(rx: &crossbeam_channel::Receiver, out: &mut dyn Write) -> i32 { let mut found = false; let mut exit = 1; let mut last = Instant::now() - Duration::from_secs(3); for ev in rx { match ev { Event::CrackProgress { done, hps, total } => { if last.elapsed() >= Duration::from_secs(2) { last = Instant::now(); match total { Some(t) => { let _ = writeln!(out, "progress: {done}/{t} @ {hps:.0} H/s"); } None => { let _ = writeln!(out, "progress: {done} @ {hps:.0} H/s"); } } } } Event::Log(line) => { let _ = writeln!(out, "{line}"); } Event::Error(line) => { let _ = writeln!(out, "error: {line}"); exit = 2; } Event::CrackError { reason } => { let _ = writeln!(out, "error: {reason}"); exit = 2; } Event::CrackFound { password } => { let _ = writeln!(out, "FOUND: {password}"); found = true; } Event::CrackStopped { found: f } => { if found || f { return 0; } return if exit == 2 { 2 } else { 1 }; } _ => {} } } // Channel closed without a terminator (worker panicked) — treat as error. let _ = writeln!(out, "error: cracker vanished without a CrackStopped"); 2 } #[cfg(test)] mod tests { use super::*; use crate::common::MacAddr; /// The fabricator writes a dummy MIC, so the UI's own capture is NOT /// crackable as-is. Build on its frame layout (MIC at offset 81..97, /// key_ver 2) and recompute a REAL MIC for the mock cracker's password /// (the private `MOCK_PASSWORD` const in ui/cracker.rs — value pinned /// here so the test trips loudly if the mock password ever changes). fn crackable_capture() -> crate::common::HandshakeCapture { const MOCK_PW: &str = "testnet2024!"; let ap = MacAddr([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]); let client = MacAddr([0x11, 0x22, 0x33, 0x44, 0x55, 0x66]); let mut cap = crate::ui::mock::fabricate_handshake(ap, client, "testap", 7); let pmk = crypto::pmk(MOCK_PW.as_bytes(), b"testap"); let ptk = crypto::ptk(&pmk, &ap, &client, &cap.anonce, &cap.snonce); let mic = crypto::mic_on_zeroed(&ptk, &crypto::zeroed_eapol(&cap.eapol_m2), cap.key_ver); cap = crate::common::HandshakeCapture::new( ap, client, "testap".to_string(), cap.anonce, cap.snonce, mic, cap.eapol_m2, cap.key_ver, ); cap } #[test] fn cli_crack_finds_fabricated() { let dir = std::env::temp_dir().join(format!( "wifi_lab-cli-test-{}-{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("clock") .as_nanos() )); std::fs::create_dir_all(&dir).expect("tempdir"); let capture = dir.join("cap.hc22000"); let wordlist = dir.join("words.txt"); let cap = crackable_capture(); let line = crate::handshake::handshake_hc22000(&cap); std::fs::write( &capture, format!("junk line not hc22000\nWPA*99*bogus\n{line}\n"), ) .expect("write capture"); std::fs::write(&wordlist, "not-the-password\nhunter2\ntestnet2024!\n") .expect("write wordlist"); let args = CliCrack { capture: capture.to_string_lossy().into_owned(), mode: "wordlist".to_string(), wordlist: Some(wordlist.to_string_lossy().into_owned()), rules: None, min: 8, max: 12, hybrid: false, lower: false, upper: false, digits: false, special: false, cpu: true, // deterministic CPU + no PMK-cache writes from tests }; let mut buf = Vec::new(); let ret = run_crack_cli(args, &mut buf); let text = String::from_utf8_lossy(&buf); let _ = std::fs::remove_dir_all(&dir); assert_eq!(ret, 0, "expected exit 0, output:\n{text}"); assert!(text.contains("FOUND: testnet2024!"), "output:\n{text}"); } /// Drive `crack_event_loop` with a scripted event stream (real channel, /// no crack worker) and return (exit code, captured output). fn run_scripted(events: Vec) -> (i32, String) { let (tx, rx) = crossbeam_channel::unbounded(); for ev in events { tx.send(ev).expect("send scripted event"); } drop(tx); let mut buf = Vec::new(); let ret = crack_event_loop(&rx, &mut buf); (ret, String::from_utf8_lossy(&buf).into_owned()) } #[test] fn cli_crack_error_event_exits_2_with_reason() { // Backend failure (GPU device lost): reason surfaces with the same // `error:` prefix as other errors, and a following exhausted-verdict // CrackStopped must NOT downgrade the exit code to 1. let (ret, text) = run_scripted(vec![ Event::CrackError { reason: "gpu: device lost".to_string(), }, Event::CrackStopped { found: false }, ]); assert_eq!(ret, 2, "output:\n{text}"); assert!(text.contains("error: gpu: device lost"), "output:\n{text}"); // A password already reported before the failure still wins: the // run recovered the passphrase, the tail error cannot un-find it. let (ret, text) = run_scripted(vec![ Event::CrackFound { password: "s3cret".to_string(), }, Event::CrackError { reason: "gpu: dispatch timeout".to_string(), }, Event::CrackStopped { found: false }, ]); assert_eq!(ret, 0, "output:\n{text}"); assert!(text.contains("FOUND: s3cret"), "output:\n{text}"); } #[test] fn cli_handshake_partial_event_ignored() { // Capture events carry no crack verdict for the CLI (targets come // from the capture file): a partial M2+M3 event mid-stream must not // disturb progress/found/stopped handling. let cap = crackable_capture(); let (ret, text) = run_scripted(vec![ Event::HandshakePartial(Box::new(cap)), Event::CrackFound { password: "testnet2024!".to_string(), }, Event::CrackStopped { found: true }, ]); assert_eq!(ret, 0, "output:\n{text}"); assert!(text.contains("FOUND: testnet2024!"), "output:\n{text}"); // Exhaustion after a partial event is still a plain exit 1. let (ret, text) = run_scripted(vec![ Event::HandshakePartial(Box::new(crackable_capture())), Event::CrackStopped { found: false }, ]); assert_eq!(ret, 1, "output:\n{text}"); } #[test] fn cli_crack_missing_files_exit_2() { let mut buf = Vec::new(); let args = CliCrack { capture: "/nonexistent/cap.hc22000".to_string(), mode: "wordlist".to_string(), wordlist: Some("/nonexistent/words.txt".to_string()), rules: None, min: 8, max: 12, hybrid: false, lower: false, upper: false, digits: false, special: false, cpu: true, }; let ret = run_crack_cli(args, &mut buf); let text = String::from_utf8_lossy(&buf); assert_eq!(ret, 2); assert!(text.contains("cannot read capture file"), "output:\n{text}"); // Capture fine (fabricated), wordlist missing → still exit 2. let dir = std::env::temp_dir().join(format!("wifi_lab-cli-err-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("tempdir"); let capture = dir.join("cap.hc22000"); let line = crate::handshake::handshake_hc22000(&crackable_capture()); std::fs::write(&capture, format!("{line}\n")).expect("write capture"); let args = CliCrack { capture: capture.to_string_lossy().into_owned(), mode: "wordlist".to_string(), wordlist: Some("/nonexistent/words.txt".to_string()), rules: None, min: 8, max: 12, hybrid: false, lower: false, upper: false, digits: false, special: false, cpu: true, }; let mut buf = Vec::new(); let ret = run_crack_cli(args, &mut buf); let text = String::from_utf8_lossy(&buf); let _ = std::fs::remove_dir_all(&dir); assert_eq!(ret, 2); assert!(text.contains("cannot open wordlist"), "output:\n{text}"); } }