forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

cli.rs382 lines, 14.2 KiBHistoryRawDownload
1//! Headless `wifi_lab crack` subcommand: crack one capture file with no UI,
2//! no radio and no root. The capture file is hc22000 text (one `WPA*01*` /
3//! `WPA*02*` line per capture, hashcat -m 22000); the first line that parses
4//! is the target, everything else is ignored.
5//!
6//! Exit codes: 0 password found, 1 keyspace exhausted, 2 usage/IO/backend
7//! error (backend = `Event::CrackError`, e.g. GPU device lost).
8
9use std::io::Write;
10use std::path::PathBuf;
11use std::time::{Duration, Instant};
12
13use crate::attack::{self, Attack};
14use crate::common::Event;
15use crate::crypto::{self, CrackTarget};
16
17/// Owned, clap-free view of the `crack` subcommand flags (main.rs converts
18/// its derived `CrackArgs` 1:1 into this so the CLI logic stays testable).
19pub struct CliCrack {
20 /// Path to the hc22000 capture file.
21 pub capture: String,
22 /// Attack mode: "wordlist" | "rules" | "bruteforce".
23 pub mode: String,
24 /// Wordlist path (wordlist-family modes).
25 pub wordlist: Option<String>,
26 /// Rules file path (rules mode).
27 pub rules: Option<String>,
28 /// Bruteforce-ish minimum length.
29 pub min: usize,
30 /// Bruteforce-ish maximum length.
31 pub max: usize,
32 /// Hybrid: wordlist × append-charset sweep (requires `wordlist`).
33 pub hybrid: bool,
34 pub lower: bool,
35 pub upper: bool,
36 pub digits: bool,
37 pub special: bool,
38 /// Force the CPU backend (also disables PMK-cache writes).
39 pub cpu: bool,
40}
41
42/// Union of the toggled charset presets; when nothing is toggled the
43/// default is lower+digits (the most common password soup).
44fn cli_charset(args: &CliCrack) -> Vec<u8> {
45 let (mut lower, mut digits) = (args.lower, args.digits);
46 if !args.lower && !args.upper && !args.digits && !args.special {
47 lower = true;
48 digits = true;
49 }
50 attack::charset::compose(lower, args.upper, digits, args.special, &[])
51}
52
53fn build_attack(args: &CliCrack) -> Result<Attack, String> {
54 let wordlist = |what: &str| -> Result<PathBuf, String> {
55 args.wordlist
56 .clone()
57 .map(PathBuf::from)
58 .ok_or_else(|| format!("error: --wordlist is required for {what} mode"))
59 };
60 if args.hybrid {
61 return Ok(Attack::Hybrid {
62 wordlist: wordlist("hybrid")?,
63 charset: cli_charset(args),
64 min: args.min,
65 max: args.max,
66 });
67 }
68 match args.mode.as_str() {
69 "rules" => Ok(Attack::Rules {
70 wordlist: wordlist("rules")?,
71 rules: args
72 .rules
73 .clone()
74 .map(PathBuf::from)
75 .ok_or_else(|| "error: --rules is required for rules mode".to_string())?,
76 }),
77 "bruteforce" => Ok(Attack::Bruteforce {
78 charset: cli_charset(args),
79 min: args.min,
80 max: args.max,
81 freq_order: true,
82 }),
83 _ => Ok(Attack::Wordlist(wordlist("wordlist")?)),
84 }
85}
86
87/// First crackable target in an hc22000 file: the bare `WPA*` prefix hashcat
88/// emits is stripped (`crypto::parse_hc22000` takes the bare form).
89fn first_target(path: &str) -> Result<CrackTarget, String> {
90 let text = std::fs::read_to_string(path)
91 .map_err(|e| format!("error: cannot read capture file {path}: {e}"))?;
92 for line in text.lines() {
93 let stripped = line.strip_prefix("WPA*").unwrap_or(line);
94 if let Ok(target) = crypto::parse_hc22000(stripped) {
95 return Ok(target);
96 }
97 }
98 Err(format!("error: no crackable WPA* line in {path}"))
99}
100
101/// Run the crack to completion on the calling thread. Progress prints are
102/// throttled to one line per 2 s; all engine `Log` lines pass through.
103pub fn run_crack_cli(args: CliCrack, out: &mut dyn Write) -> i32 {
104 let target = match first_target(&args.capture) {
105 Ok(t) => t,
106 Err(msg) => {
107 let _ = writeln!(out, "{msg}");
108 return 2;
109 }
110 };
111 let attack = match build_attack(&args) {
112 Ok(a) => a,
113 Err(msg) => {
114 let _ = writeln!(out, "{msg}");
115 return 2;
116 }
117 };
118 if let Err(e) = attack.validate() {
119 let _ = writeln!(out, "error: {e:#}");
120 return 2;
121 }
122 let _ = writeln!(out, "target: {}", target.describe());
123 let _ = writeln!(out, "attack: {}", attack.describe());
124
125 let (tx, rx) = crossbeam_channel::unbounded();
126 let _stop = attack::spawn_crack(target.describe(), target, attack, 0, tx, args.cpu);
127 crack_event_loop(&rx, out)
128}
129
130/// Consume crack-job `Event`s until the job terminates; returns the process
131/// exit code: 0 password found, 1 keyspace exhausted, 2 error. Extracted
132/// from `run_crack_cli` so the verdict logic is testable without a real
133/// crack worker.
134///
135/// `Event::CrackError` (backend failure — NOT exhaustion) prints its reason
136/// with the same `error:` prefix as other errors and forces exit 2 even if
137/// a `CrackStopped { found: false }` follows (the error supersedes the
138/// stop verdict, unless a password was already reported). Capture events
139/// (handshakes/PMKIDs, incl. partial M2+M3 pairs) carry no crack verdict
140/// here — CLI targets come from the capture file, not from events — and
141/// are ignored.
142fn crack_event_loop(rx: &crossbeam_channel::Receiver<Event>, out: &mut dyn Write) -> i32 {
143 let mut found = false;
144 let mut exit = 1;
145 let mut last = Instant::now() - Duration::from_secs(3);
146 for ev in rx {
147 match ev {
148 Event::CrackProgress { done, hps, total } => {
149 if last.elapsed() >= Duration::from_secs(2) {
150 last = Instant::now();
151 match total {
152 Some(t) => {
153 let _ = writeln!(out, "progress: {done}/{t} @ {hps:.0} H/s");
154 }
155 None => {
156 let _ = writeln!(out, "progress: {done} @ {hps:.0} H/s");
157 }
158 }
159 }
160 }
161 Event::Log(line) => {
162 let _ = writeln!(out, "{line}");
163 }
164 Event::Error(line) => {
165 let _ = writeln!(out, "error: {line}");
166 exit = 2;
167 }
168 Event::CrackError { reason } => {
169 let _ = writeln!(out, "error: {reason}");
170 exit = 2;
171 }
172 Event::CrackFound { password } => {
173 let _ = writeln!(out, "FOUND: {password}");
174 found = true;
175 }
176 Event::CrackStopped { found: f } => {
177 if found || f {
178 return 0;
179 }
180 return if exit == 2 { 2 } else { 1 };
181 }
182 _ => {}
183 }
184 }
185 // Channel closed without a terminator (worker panicked) — treat as error.
186 let _ = writeln!(out, "error: cracker vanished without a CrackStopped");
187 2
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use crate::common::MacAddr;
194
195 /// The fabricator writes a dummy MIC, so the UI's own capture is NOT
196 /// crackable as-is. Build on its frame layout (MIC at offset 81..97,
197 /// key_ver 2) and recompute a REAL MIC for the mock cracker's password
198 /// (the private `MOCK_PASSWORD` const in ui/cracker.rs — value pinned
199 /// here so the test trips loudly if the mock password ever changes).
200 fn crackable_capture() -> crate::common::HandshakeCapture {
201 const MOCK_PW: &str = "testnet2024!";
202 let ap = MacAddr([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]);
203 let client = MacAddr([0x11, 0x22, 0x33, 0x44, 0x55, 0x66]);
204 let mut cap = crate::ui::mock::fabricate_handshake(ap, client, "testap", 7);
205 let pmk = crypto::pmk(MOCK_PW.as_bytes(), b"testap");
206 let ptk = crypto::ptk(&pmk, &ap, &client, &cap.anonce, &cap.snonce);
207 let mic = crypto::mic_on_zeroed(&ptk, &crypto::zeroed_eapol(&cap.eapol_m2), cap.key_ver);
208 cap = crate::common::HandshakeCapture::new(
209 ap,
210 client,
211 "testap".to_string(),
212 cap.anonce,
213 cap.snonce,
214 mic,
215 cap.eapol_m2,
216 cap.key_ver,
217 );
218 cap
219 }
220
221 #[test]
222 fn cli_crack_finds_fabricated() {
223 let dir = std::env::temp_dir().join(format!(
224 "wifi_lab-cli-test-{}-{}",
225 std::process::id(),
226 std::time::SystemTime::now()
227 .duration_since(std::time::UNIX_EPOCH)
228 .expect("clock")
229 .as_nanos()
230 ));
231 std::fs::create_dir_all(&dir).expect("tempdir");
232 let capture = dir.join("cap.hc22000");
233 let wordlist = dir.join("words.txt");
234
235 let cap = crackable_capture();
236 let line = crate::handshake::handshake_hc22000(&cap);
237 std::fs::write(
238 &capture,
239 format!("junk line not hc22000\nWPA*99*bogus\n{line}\n"),
240 )
241 .expect("write capture");
242 std::fs::write(&wordlist, "not-the-password\nhunter2\ntestnet2024!\n")
243 .expect("write wordlist");
244
245 let args = CliCrack {
246 capture: capture.to_string_lossy().into_owned(),
247 mode: "wordlist".to_string(),
248 wordlist: Some(wordlist.to_string_lossy().into_owned()),
249 rules: None,
250 min: 8,
251 max: 12,
252 hybrid: false,
253 lower: false,
254 upper: false,
255 digits: false,
256 special: false,
257 cpu: true, // deterministic CPU + no PMK-cache writes from tests
258 };
259 let mut buf = Vec::new();
260 let ret = run_crack_cli(args, &mut buf);
261 let text = String::from_utf8_lossy(&buf);
262 let _ = std::fs::remove_dir_all(&dir);
263 assert_eq!(ret, 0, "expected exit 0, output:\n{text}");
264 assert!(text.contains("FOUND: testnet2024!"), "output:\n{text}");
265 }
266
267 /// Drive `crack_event_loop` with a scripted event stream (real channel,
268 /// no crack worker) and return (exit code, captured output).
269 fn run_scripted(events: Vec<Event>) -> (i32, String) {
270 let (tx, rx) = crossbeam_channel::unbounded();
271 for ev in events {
272 tx.send(ev).expect("send scripted event");
273 }
274 drop(tx);
275 let mut buf = Vec::new();
276 let ret = crack_event_loop(&rx, &mut buf);
277 (ret, String::from_utf8_lossy(&buf).into_owned())
278 }
279
280 #[test]
281 fn cli_crack_error_event_exits_2_with_reason() {
282 // Backend failure (GPU device lost): reason surfaces with the same
283 // `error:` prefix as other errors, and a following exhausted-verdict
284 // CrackStopped must NOT downgrade the exit code to 1.
285 let (ret, text) = run_scripted(vec![
286 Event::CrackError {
287 reason: "gpu: device lost".to_string(),
288 },
289 Event::CrackStopped { found: false },
290 ]);
291 assert_eq!(ret, 2, "output:\n{text}");
292 assert!(text.contains("error: gpu: device lost"), "output:\n{text}");
293
294 // A password already reported before the failure still wins: the
295 // run recovered the passphrase, the tail error cannot un-find it.
296 let (ret, text) = run_scripted(vec![
297 Event::CrackFound {
298 password: "s3cret".to_string(),
299 },
300 Event::CrackError {
301 reason: "gpu: dispatch timeout".to_string(),
302 },
303 Event::CrackStopped { found: false },
304 ]);
305 assert_eq!(ret, 0, "output:\n{text}");
306 assert!(text.contains("FOUND: s3cret"), "output:\n{text}");
307 }
308
309 #[test]
310 fn cli_handshake_partial_event_ignored() {
311 // Capture events carry no crack verdict for the CLI (targets come
312 // from the capture file): a partial M2+M3 event mid-stream must not
313 // disturb progress/found/stopped handling.
314 let cap = crackable_capture();
315 let (ret, text) = run_scripted(vec![
316 Event::HandshakePartial(Box::new(cap)),
317 Event::CrackFound {
318 password: "testnet2024!".to_string(),
319 },
320 Event::CrackStopped { found: true },
321 ]);
322 assert_eq!(ret, 0, "output:\n{text}");
323 assert!(text.contains("FOUND: testnet2024!"), "output:\n{text}");
324
325 // Exhaustion after a partial event is still a plain exit 1.
326 let (ret, text) = run_scripted(vec![
327 Event::HandshakePartial(Box::new(crackable_capture())),
328 Event::CrackStopped { found: false },
329 ]);
330 assert_eq!(ret, 1, "output:\n{text}");
331 }
332
333 #[test]
334 fn cli_crack_missing_files_exit_2() {
335 let mut buf = Vec::new();
336 let args = CliCrack {
337 capture: "/nonexistent/cap.hc22000".to_string(),
338 mode: "wordlist".to_string(),
339 wordlist: Some("/nonexistent/words.txt".to_string()),
340 rules: None,
341 min: 8,
342 max: 12,
343 hybrid: false,
344 lower: false,
345 upper: false,
346 digits: false,
347 special: false,
348 cpu: true,
349 };
350 let ret = run_crack_cli(args, &mut buf);
351 let text = String::from_utf8_lossy(&buf);
352 assert_eq!(ret, 2);
353 assert!(text.contains("cannot read capture file"), "output:\n{text}");
354
355 // Capture fine (fabricated), wordlist missing → still exit 2.
356 let dir = std::env::temp_dir().join(format!("wifi_lab-cli-err-{}", std::process::id()));
357 std::fs::create_dir_all(&dir).expect("tempdir");
358 let capture = dir.join("cap.hc22000");
359 let line = crate::handshake::handshake_hc22000(&crackable_capture());
360 std::fs::write(&capture, format!("{line}\n")).expect("write capture");
361 let args = CliCrack {
362 capture: capture.to_string_lossy().into_owned(),
363 mode: "wordlist".to_string(),
364 wordlist: Some("/nonexistent/words.txt".to_string()),
365 rules: None,
366 min: 8,
367 max: 12,
368 hybrid: false,
369 lower: false,
370 upper: false,
371 digits: false,
372 special: false,
373 cpu: true,
374 };
375 let mut buf = Vec::new();
376 let ret = run_crack_cli(args, &mut buf);
377 let text = String::from_utf8_lossy(&buf);
378 let _ = std::fs::remove_dir_all(&dir);
379 assert_eq!(ret, 2);
380 assert!(text.contains("cannot open wordlist"), "output:\n{text}");
381 }
382}