forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiB87ed271Tahinli1 month ago23 commits

cli.rs298 lines, 10.6 KiBHistoryRawDownload
1//! Headless `wifilab 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 error.
7
8use std::io::Write;
9use std::path::PathBuf;
10use std::time::{Duration, Instant};
11
12use crate::attack::{self, Attack};
13use crate::common::Event;
14use crate::crypto::{self, CrackTarget};
15
16/// Owned, clap-free view of the `crack` subcommand flags (main.rs converts
17/// its derived `CrackArgs` 1:1 into this so the CLI logic stays testable).
18pub struct CliCrack {
19 /// Path to the hc22000 capture file.
20 pub capture: String,
21 /// Attack mode: "wordlist" | "rules" | "bruteforce".
22 pub mode: String,
23 /// Wordlist path (wordlist-family modes).
24 pub wordlist: Option<String>,
25 /// Rules file path (rules mode).
26 pub rules: Option<String>,
27 /// Bruteforce-ish minimum length.
28 pub min: usize,
29 /// Bruteforce-ish maximum length.
30 pub max: usize,
31 /// Hybrid: wordlist × append-charset sweep (requires `wordlist`).
32 pub hybrid: bool,
33 pub lower: bool,
34 pub upper: bool,
35 pub digits: bool,
36 pub special: bool,
37 /// Force the CPU backend (also disables PMK-cache writes).
38 pub cpu: bool,
39}
40
41/// Union of the toggled charset presets; when nothing is toggled the
42/// default is lower+digits (the most common password soup).
43fn cli_charset(args: &CliCrack) -> Vec<u8> {
44 let (mut lower, mut digits) = (args.lower, args.digits);
45 if !args.lower && !args.upper && !args.digits && !args.special {
46 lower = true;
47 digits = true;
48 }
49 attack::charset::compose(lower, args.upper, digits, args.special, &[])
50}
51
52fn build_attack(args: &CliCrack) -> Result<Attack, String> {
53 let wordlist = |what: &str| -> Result<PathBuf, String> {
54 args.wordlist
55 .clone()
56 .map(PathBuf::from)
57 .ok_or_else(|| format!("error: --wordlist is required for {what} mode"))
58 };
59 if args.hybrid {
60 return Ok(Attack::Hybrid {
61 wordlist: wordlist("hybrid")?,
62 charset: cli_charset(args),
63 min: args.min,
64 max: args.max,
65 });
66 }
67 match args.mode.as_str() {
68 "rules" => Ok(Attack::Rules {
69 wordlist: wordlist("rules")?,
70 rules: args
71 .rules
72 .clone()
73 .map(PathBuf::from)
74 .ok_or_else(|| "error: --rules is required for rules mode".to_string())?,
75 }),
76 "bruteforce" => Ok(Attack::Bruteforce {
77 charset: cli_charset(args),
78 min: args.min,
79 max: args.max,
80 freq_order: true,
81 }),
82 _ => Ok(Attack::Wordlist(wordlist("wordlist")?)),
83 }
84}
85
86/// First crackable target in an hc22000 file: the bare `WPA*` prefix hashcat
87/// emits is stripped (`crypto::parse_hc22000` takes the bare form).
88fn first_target(path: &str) -> Result<CrackTarget, String> {
89 let text = std::fs::read_to_string(path)
90 .map_err(|e| format!("error: cannot read capture file {path}: {e}"))?;
91 for line in text.lines() {
92 let stripped = line.strip_prefix("WPA*").unwrap_or(line);
93 if let Ok(target) = crypto::parse_hc22000(stripped) {
94 return Ok(target);
95 }
96 }
97 Err(format!("error: no crackable WPA* line in {path}"))
98}
99
100/// Run the crack to completion on the calling thread. Progress prints are
101/// throttled to one line per 2 s; all engine `Log` lines pass through.
102pub fn run_crack_cli(args: CliCrack, out: &mut dyn Write) -> i32 {
103 let target = match first_target(&args.capture) {
104 Ok(t) => t,
105 Err(msg) => {
106 let _ = writeln!(out, "{msg}");
107 return 2;
108 }
109 };
110 let attack = match build_attack(&args) {
111 Ok(a) => a,
112 Err(msg) => {
113 let _ = writeln!(out, "{msg}");
114 return 2;
115 }
116 };
117 if let Err(e) = attack.validate() {
118 let _ = writeln!(out, "error: {e:#}");
119 return 2;
120 }
121 let _ = writeln!(out, "target: {}", target.describe());
122 let _ = writeln!(out, "attack: {}", attack.describe());
123
124 let (tx, rx) = crossbeam_channel::unbounded();
125 let _stop = attack::spawn_crack(target.describe(), target, attack, 0, tx, args.cpu);
126
127 let mut found = false;
128 let mut exit = 1;
129 let mut last = Instant::now() - Duration::from_secs(3);
130 for ev in rx {
131 match ev {
132 Event::CrackProgress { done, hps, total } => {
133 if last.elapsed() >= Duration::from_secs(2) {
134 last = Instant::now();
135 match total {
136 Some(t) => {
137 let _ = writeln!(out, "progress: {done}/{t} @ {hps:.0} H/s");
138 }
139 None => {
140 let _ = writeln!(out, "progress: {done} @ {hps:.0} H/s");
141 }
142 }
143 }
144 }
145 Event::Log(line) => {
146 let _ = writeln!(out, "{line}");
147 }
148 Event::Error(line) => {
149 let _ = writeln!(out, "error: {line}");
150 exit = 2;
151 }
152 Event::CrackFound { password } => {
153 let _ = writeln!(out, "FOUND: {password}");
154 found = true;
155 }
156 Event::CrackStopped { found: f } => {
157 if found || f {
158 return 0;
159 }
160 return if exit == 2 { 2 } else { 1 };
161 }
162 _ => {}
163 }
164 }
165 // Channel closed without a terminator (worker panicked) — treat as error.
166 let _ = writeln!(out, "error: cracker vanished without a CrackStopped");
167 2
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173 use crate::common::MacAddr;
174
175 /// The fabricator writes a dummy MIC, so the UI's own capture is NOT
176 /// crackable as-is. Build on its frame layout (MIC at offset 81..97,
177 /// key_ver 2) and recompute a REAL MIC for the mock cracker's password
178 /// (the private `MOCK_PASSWORD` const in ui/cracker.rs — value pinned
179 /// here so the test trips loudly if the mock password ever changes).
180 fn crackable_capture() -> crate::common::HandshakeCapture {
181 const MOCK_PW: &str = "parafin2024!";
182 let ap = MacAddr([0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]);
183 let client = MacAddr([0x11, 0x22, 0x33, 0x44, 0x55, 0x66]);
184 let mut cap = crate::ui::mock::fabricate_handshake(ap, client, "testap", 7);
185 let pmk = crypto::pmk(MOCK_PW.as_bytes(), b"testap");
186 let ptk = crypto::ptk(&pmk, &ap, &client, &cap.anonce, &cap.snonce);
187 let mic = crypto::mic(&ptk, &cap.eapol_m2, cap.key_ver);
188 cap = crate::common::HandshakeCapture::new(
189 ap,
190 client,
191 "testap".to_string(),
192 cap.anonce,
193 cap.snonce,
194 mic,
195 cap.eapol_m2,
196 cap.key_ver,
197 );
198 let target = CrackTarget::Handshake(cap.clone());
199 assert!(crypto::verify(&target, MOCK_PW.as_bytes()));
200 cap
201 }
202
203 #[test]
204 fn cli_crack_finds_fabricated() {
205 let dir = std::env::temp_dir().join(format!(
206 "wifilab-cli-test-{}-{}",
207 std::process::id(),
208 std::time::SystemTime::now()
209 .duration_since(std::time::UNIX_EPOCH)
210 .expect("clock")
211 .as_nanos()
212 ));
213 std::fs::create_dir_all(&dir).expect("tempdir");
214 let capture = dir.join("cap.hc22000");
215 let wordlist = dir.join("words.txt");
216
217 let cap = crackable_capture();
218 let line = crate::handshake::handshake_hc22000(&cap);
219 std::fs::write(&capture, format!("junk line not hc22000\nWPA*99*bogus\n{line}\n"))
220 .expect("write capture");
221 std::fs::write(&wordlist, "not-the-password\nhunter2\nparafin2024!\n")
222 .expect("write wordlist");
223
224 let args = CliCrack {
225 capture: capture.to_string_lossy().into_owned(),
226 mode: "wordlist".to_string(),
227 wordlist: Some(wordlist.to_string_lossy().into_owned()),
228 rules: None,
229 min: 8,
230 max: 12,
231 hybrid: false,
232 lower: false,
233 upper: false,
234 digits: false,
235 special: false,
236 cpu: true, // deterministic CPU + no PMK-cache writes from tests
237 };
238 let mut buf = Vec::new();
239 let ret = run_crack_cli(args, &mut buf);
240 let text = String::from_utf8_lossy(&buf);
241 let _ = std::fs::remove_dir_all(&dir);
242 assert_eq!(ret, 0, "expected exit 0, output:\n{text}");
243 assert!(text.contains("FOUND: parafin2024!"), "output:\n{text}");
244 }
245
246 #[test]
247 fn cli_crack_missing_files_exit_2() {
248 let mut buf = Vec::new();
249 let args = CliCrack {
250 capture: "/nonexistent/cap.hc22000".to_string(),
251 mode: "wordlist".to_string(),
252 wordlist: Some("/nonexistent/words.txt".to_string()),
253 rules: None,
254 min: 8,
255 max: 12,
256 hybrid: false,
257 lower: false,
258 upper: false,
259 digits: false,
260 special: false,
261 cpu: true,
262 };
263 let ret = run_crack_cli(args, &mut buf);
264 let text = String::from_utf8_lossy(&buf);
265 assert_eq!(ret, 2);
266 assert!(text.contains("cannot read capture file"), "output:\n{text}");
267
268 // Capture fine (fabricated), wordlist missing → still exit 2.
269 let dir = std::env::temp_dir().join(format!(
270 "wifilab-cli-err-{}",
271 std::process::id()
272 ));
273 std::fs::create_dir_all(&dir).expect("tempdir");
274 let capture = dir.join("cap.hc22000");
275 let line = crate::handshake::handshake_hc22000(&crackable_capture());
276 std::fs::write(&capture, format!("{line}\n")).expect("write capture");
277 let args = CliCrack {
278 capture: capture.to_string_lossy().into_owned(),
279 mode: "wordlist".to_string(),
280 wordlist: Some("/nonexistent/words.txt".to_string()),
281 rules: None,
282 min: 8,
283 max: 12,
284 hybrid: false,
285 lower: false,
286 upper: false,
287 digits: false,
288 special: false,
289 cpu: true,
290 };
291 let mut buf = Vec::new();
292 let ret = run_crack_cli(args, &mut buf);
293 let text = String::from_utf8_lossy(&buf);
294 let _ = std::fs::remove_dir_all(&dir);
295 assert_eq!(ret, 2);
296 assert!(text.contains("cannot open wordlist"), "output:\n{text}");
297 }
298}