forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

pcapin.rs432 lines, 15.6 KiBHistoryRawDownload
1//! libpcap capture-file importer: extracts crackable captures (4-way
2//! handshakes and PMKIDs) from a `.pcap`/`.cap` file.
3//!
4//! Supported linktypes: 127 (`DLT_IEEE802_11_RADIO`, frames carry a
5//! radiotap header that is stripped via [`crate::radiotap::strip`]) and
6//! 105 (`DLT_IEEE802_11`, raw 802.11). Both byte orders of the file magic
7//! are accepted; every other linktype is rejected with an error naming it.
8//!
9//! Two in-memory passes over the frames:
10//! 1. beacons / probe-responses → bssid → essid map
11//! ([`crate::dot11::parse_beacon_or_probe`]);
12//! 2. data frames → [`crate::dot11::parse_eapol`] →
13//! [`crate::dot11::parse_eapol_key`]: 4-way messages feed a
14//! [`crate::handshake::Tracker`] (essid from the pass-1 map); M1-shaped
15//! keys additionally get their `key_data` scanned for a PMKID KDE via
16//! [`crate::pmkid::extract_pmkid`].
17//!
18//! A capture whose AP's essid never appears in pass 1 cannot be cracked
19//! (the essid is the PBKDF2 salt): it is skipped and the count is logged
20//! through `tracing::warn!`.
21
22use std::collections::BTreeMap;
23use std::io::{self, ErrorKind};
24use std::path::Path;
25
26use anyhow::{Context, Result, bail};
27use byteorder::{BigEndian as BE, LittleEndian as LE, ReadBytesExt};
28
29use crate::common::{ImportedCapture, MacAddr, PmkidCapture};
30use crate::dot11::{self, eapol_4way_msg, parse_eapol, parse_eapol_key};
31use crate::handshake::Tracker;
32
33const MAGIC_LE: u32 = 0xa1b2_c3d4;
34const MAGIC_BE: u32 = 0xd4c3_b2a1;
35
36/// DLT_IEEE802_11_RADIO (radiotap-prefixed) and DLT_IEEE802_11 (raw).
37const LINKTYPE_RADIOTAP: u32 = 127;
38const LINKTYPE_RAW_80211: u32 = 105;
39
40/// Read the frame payloads out of a pcap file, validating the global
41/// header. Timestamps and per-frame orig_len are not needed by the import
42/// path, so frames come back as bare byte vectors.
43pub(crate) fn frames(path: &Path) -> io::Result<(u32, Vec<Vec<u8>>)> {
44 let buf = std::fs::read(path)?;
45 if buf.len() < 24 {
46 return Err(io::Error::new(
47 ErrorKind::InvalidData,
48 "pcap: file smaller than the 24-byte global header",
49 ));
50 }
51 let mut cur = io::Cursor::new(&buf[..]);
52 let magic = cur.read_u32::<LE>()?;
53 let big_endian = match magic {
54 MAGIC_LE => false,
55 MAGIC_BE => true,
56 _ => {
57 return Err(io::Error::new(
58 ErrorKind::InvalidData,
59 format!("pcap: bad magic 0x{magic:08x}"),
60 ));
61 }
62 };
63 macro_rules! read_u16 {
64 ($c:expr) => {
65 if big_endian {
66 $c.read_u16::<BE>()
67 } else {
68 $c.read_u16::<LE>()
69 }
70 };
71 }
72 macro_rules! read_u32 {
73 ($c:expr) => {
74 if big_endian {
75 $c.read_u32::<BE>()
76 } else {
77 $c.read_u32::<LE>()
78 }
79 };
80 }
81 let _version_major = read_u16!(&mut cur)?;
82 let _version_minor = read_u16!(&mut cur)?;
83 cur.set_position(16);
84 let _snaplen = read_u32!(&mut cur)?;
85 let linktype = read_u32!(&mut cur)?;
86
87 let mut out = Vec::new();
88 loop {
89 let pos = cur.position() as usize;
90 if buf.len() - pos < 16 {
91 break; // clean EOF or trailing partial record header
92 }
93 let _ts_sec = read_u32!(&mut cur)?;
94 let _ts_usec = read_u32!(&mut cur)?;
95 let incl_len = read_u32!(&mut cur)? as usize;
96 let _orig_len = read_u32!(&mut cur)?;
97 let start = cur.position() as usize;
98 let end = start.saturating_add(incl_len);
99 if end > buf.len() {
100 return Err(io::Error::new(
101 ErrorKind::UnexpectedEof,
102 format!("pcap: packet at offset {pos} truncated ({incl_len} bytes declared)"),
103 ));
104 }
105 out.push(buf[start..end].to_vec());
106 cur.set_position(end as u64);
107 }
108 Ok((linktype, out))
109}
110
111/// Extract crackable captures from a pcap file (linktype 127 radiotap or
112/// 105 raw 802.11). Returns handshakes completed by the on-wire replay
113/// rules and PMKIDs found in M1 key-data. Captures whose AP essid is not
114/// resolvable from the file's beacons/probe-responses are skipped (a
115/// `tracing::warn!` reports the count).
116pub fn extract(path: &Path) -> Result<Vec<ImportedCapture>> {
117 let (linktype, raw_frames) =
118 frames(path).with_context(|| format!("reading pcap {}", path.display()))?;
119 if linktype != LINKTYPE_RADIOTAP && linktype != LINKTYPE_RAW_80211 {
120 bail!(
121 "pcap {}: unsupported linktype {linktype} (need 127 radiotap or 105 raw 802.11)",
122 path.display()
123 );
124 }
125
126 // Strip the radiotap prefix where the linktype demands it.
127 let mut dot11_frames: Vec<&[u8]> = Vec::with_capacity(raw_frames.len());
128 let mut strip_failures = 0u32;
129 for f in &raw_frames {
130 if linktype == LINKTYPE_RADIOTAP {
131 match crate::radiotap::strip(f) {
132 Some((_meta, body)) => dot11_frames.push(body),
133 None => strip_failures += 1,
134 }
135 } else {
136 dot11_frames.push(f);
137 }
138 }
139 if strip_failures > 0 {
140 tracing::warn!(
141 "pcap import: {strip_failures} frames with malformed radiotap headers skipped"
142 );
143 }
144
145 // Pass 1: bssid → essid map from beacons and probe responses.
146 let mut essids: BTreeMap<MacAddr, String> = BTreeMap::new();
147 for f in &dot11_frames {
148 if let Some(info) = dot11::parse_beacon_or_probe(f)
149 && let Some(ssid) = info.ssid
150 && !ssid.is_empty()
151 {
152 essids.entry(info.bssid).or_insert(ssid);
153 }
154 }
155
156 // Pass 2: EAPOL through the handshake tracker + PMKID KDE scan.
157 let (tx, rx) = crossbeam_channel::unbounded();
158 let mut tracker = Tracker::new();
159 let mut captures: Vec<ImportedCapture> = Vec::new();
160 let mut skipped_no_essid = 0u32;
161 for f in &dot11_frames {
162 let Some((bssid, ap_sender, eapol)) = parse_eapol(f) else {
163 continue;
164 };
165 let Some(key) = parse_eapol_key(eapol) else {
166 continue;
167 };
168 if eapol_4way_msg(&key) == 0 {
169 continue;
170 }
171 let Some((sta_ap, sta)) = dot11::data_endpoints(f) else {
172 continue;
173 };
174 debug_assert_eq!(sta_ap, bssid);
175 let essid = essids.get(&bssid).cloned().unwrap_or_default();
176 if essid.is_empty() {
177 // Track lightly but nothing crackable can come out; count the
178 // skip once a completion/PMKID actually appears below.
179 }
180 // PMKID lives in the M1 key-data (AP → station message).
181 if ap_sender
182 && eapol_4way_msg(&key) == 1
183 && let Some(pmkid) = crate::pmkid::extract_pmkid(key.key_data)
184 {
185 if essid.is_empty() {
186 skipped_no_essid += 1;
187 } else {
188 captures.push(ImportedCapture::Pmkid(PmkidCapture {
189 ap: bssid,
190 client: sta,
191 essid: essid.clone(),
192 pmkid,
193 }));
194 }
195 }
196 if let Some(cap) = tracker.ingest(bssid, sta, &essid, &key, &tx) {
197 captures.push(ImportedCapture::Handshake(Box::new(cap)));
198 }
199 }
200 // Drain progress events; the tracker still emits them for state
201 // consistency but the importer has no UI to notify.
202 while rx.try_recv().is_ok() {}
203 if skipped_no_essid > 0 {
204 tracing::warn!(
205 "pcap import: {skipped_no_essid} PMKID capture(s) skipped — AP essid not resolvable from the file"
206 );
207 }
208 Ok(captures)
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214 use crate::pcapout::{self, PcapWriter};
215 use byteorder::{LittleEndian as LE, WriteBytesExt};
216
217 fn mac(bytes: [u8; 6]) -> MacAddr {
218 MacAddr(bytes)
219 }
220
221 const BSSID: [u8; 6] = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
222 const CLIENT: [u8; 6] = [0x66, 0x55, 0x44, 0x33, 0x22, 0x11];
223
224 #[test]
225 fn pcap_roundtrip_frame_bytes() {
226 let dir = std::env::temp_dir().join(format!(
227 "wifi_lab-pcapin-test-{}-roundtrip",
228 std::process::id()
229 ));
230 std::fs::create_dir_all(&dir).unwrap();
231 let path = dir.join("roundtrip.pcap");
232 let frames_in: Vec<Vec<u8>> = vec![
233 b"fake frame one".to_vec(),
234 vec![0, 1, 2, 3, 250, 251, 252, 253],
235 vec![0xaa; 100],
236 ];
237 {
238 let mut w: PcapWriter = pcapout::create(&path).unwrap();
239 for f in &frames_in {
240 w.append(f).unwrap();
241 }
242 w.finish().unwrap();
243 }
244 let (linktype, frames_out) = frames(&path).unwrap();
245 assert_eq!(linktype, 127);
246 assert_eq!(frames_out, frames_in);
247 let _ = std::fs::remove_dir_all(&dir);
248 }
249
250 #[test]
251 fn extract_rejects_ethernet_linktype() {
252 let dir = std::env::temp_dir().join(format!(
253 "wifi_lab-pcapin-test-{}-linktype",
254 std::process::id()
255 ));
256 std::fs::create_dir_all(&dir).unwrap();
257 let path = dir.join("eth.pcap");
258 let mut buf: Vec<u8> = Vec::new();
259 buf.write_u32::<LE>(MAGIC_LE).unwrap();
260 buf.write_u16::<LE>(2).unwrap();
261 buf.write_u16::<LE>(4).unwrap();
262 buf.write_i32::<LE>(0).unwrap();
263 buf.write_u32::<LE>(0).unwrap();
264 buf.write_u32::<LE>(65535).unwrap();
265 buf.write_u32::<LE>(1).unwrap(); // DLT_EN10MB
266 std::fs::write(&path, &buf).unwrap();
267 let err = extract(&path).unwrap_err();
268 let msg = format!("{err}");
269 assert!(
270 msg.contains("linktype 1"),
271 "error must name the linktype: {msg}"
272 );
273 let _ = std::fs::remove_dir_all(&dir);
274 }
275
276 /// Minimal 8-byte radiotap header (version 0, len 8, no fields) — the
277 /// spool file declares linktype 127, so every frame is radiotap-prefixed
278 /// exactly as it is when the scanner writes what the raw socket read.
279 const RADIOTAP_HDR: [u8; 8] = [0x00, 0x00, 0x08, 0x00, 0, 0, 0, 0];
280
281 fn radiotap_wrap(frame: Vec<u8>) -> Vec<u8> {
282 let mut v = RADIOTAP_HDR.to_vec();
283 v.extend_from_slice(&frame);
284 v
285 }
286
287 /// 802.11 beacon for `BSSID` advertising essid "testap" (no security IEs).
288 fn test_beacon() -> Vec<u8> {
289 let mut v = Vec::new();
290 // fc: type 0 subtype 8 (beacon)
291 v.extend_from_slice(&[0x80, 0x00]);
292 v.extend_from_slice(&[0x00, 0x00]); // duration
293 v.extend_from_slice(&MacAddr::BROADCAST.0); // addr1
294 v.extend_from_slice(&BSSID); // addr2 transmitter
295 v.extend_from_slice(&BSSID); // addr3 bssid
296 v.extend_from_slice(&[0x00, 0x00]); // seq
297 v.extend_from_slice(&[0x00; 8]); // timestamp
298 v.extend_from_slice(&100u16.to_le_bytes()); // interval
299 v.extend_from_slice(&[0x01, 0x04]); // capability (ESS)
300 v.extend_from_slice(&[0x00, 0x06]); // SSID IE
301 v.extend_from_slice(b"testap");
302 v
303 }
304
305 /// EAPOL-Key frame bytes (starting at the EAPOL version byte).
306 /// m1: ack set, mic flag clear; m2: mic flag set, ack clear.
307 fn eapol_key(m1: bool, replay: u64, nonce: [u8; 32], mic: [u8; 16]) -> Vec<u8> {
308 let mut v = Vec::with_capacity(99);
309 v.push(2); // eapol version
310 v.push(3); // type: EAPOL-Key
311 v.extend_from_slice(&95u16.to_be_bytes()); // length of key descriptor
312 v.push(2); // descriptor type: RSN key
313 let mut key_info: u16 = 0x0002; // key_ver 2 (AES), kept small
314 if m1 {
315 key_info |= 1 << 7; // key_ack
316 } else {
317 key_info |= 1 << 8; // key_mic
318 }
319 v.extend_from_slice(&key_info.to_be_bytes());
320 v.extend_from_slice(&16u16.to_be_bytes()); // key length
321 v.extend_from_slice(&replay.to_be_bytes());
322 v.extend_from_slice(&nonce);
323 v.extend_from_slice(&[0; 16]); // iv
324 v.extend_from_slice(&[0; 8]); // rsc
325 v.extend_from_slice(&[0; 8]); // id
326 v.extend_from_slice(&mic);
327 v.extend_from_slice(&0u16.to_be_bytes()); // key_data_len
328 v
329 }
330
331 /// Full 802.11 data frame (24-byte header) carrying an EAPOL-Key.
332 /// `from_ap`: AP → station (FromDS) vs station → AP (ToDS).
333 fn build_eapol_frame(from_ap: bool, eapol: &[u8]) -> Vec<u8> {
334 let mut v = Vec::new();
335 // fc: type 2 subtype 0 (data); ToDS / FromDS.
336 let fc: u16 = if from_ap { 0x0208 } else { 0x0108 };
337 v.extend_from_slice(&fc.to_le_bytes());
338 v.extend_from_slice(&[0x00, 0x00]); // duration
339 if from_ap {
340 v.extend_from_slice(&CLIENT); // addr1 = station
341 v.extend_from_slice(&BSSID); // addr2 = bssid
342 v.extend_from_slice(&BSSID); // addr3
343 } else {
344 v.extend_from_slice(&BSSID); // addr1 = bssid
345 v.extend_from_slice(&CLIENT); // addr2 = station
346 v.extend_from_slice(&BSSID); // addr3
347 }
348 v.extend_from_slice(&[0x10, 0x00]); // seq
349 v.extend_from_slice(&[0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x88, 0x8e]); // LLC SNAP EAPOL
350 v.extend_from_slice(eapol);
351 v
352 }
353
354 #[test]
355 fn extract_imports_handshake_e2e() {
356 let dir =
357 std::env::temp_dir().join(format!("wifi_lab-pcapin-test-{}-e2e", std::process::id()));
358 std::fs::create_dir_all(&dir).unwrap();
359 let path = dir.join("import.pcap");
360
361 let mut anonce = [0u8; 32];
362 anonce[0] = 0xaa;
363 let mut snonce = [0u8; 32];
364 snonce[0] = 0xbb;
365 let mut mic = [0u8; 16];
366 mic[0] = 0xcc;
367
368 let frames = vec![
369 radiotap_wrap(test_beacon()),
370 radiotap_wrap(build_eapol_frame(
371 true,
372 &eapol_key(true, 7, anonce, [0; 16]),
373 )),
374 radiotap_wrap(build_eapol_frame(false, &eapol_key(false, 8, snonce, mic))),
375 ];
376 {
377 let mut w = pcapout::create(&path).unwrap();
378 for f in &frames {
379 w.append(f).unwrap();
380 }
381 w.finish().unwrap();
382 }
383
384 let caps = extract(&path).unwrap();
385 assert_eq!(caps.len(), 1, "expected exactly one capture, got {caps:?}");
386 match &caps[0] {
387 ImportedCapture::Handshake(h) => {
388 assert_eq!(h.ap, mac(BSSID));
389 assert_eq!(h.client, mac(CLIENT));
390 assert_eq!(h.essid, "testap");
391 assert_eq!(h.anonce, anonce);
392 assert_eq!(h.snonce, snonce);
393 }
394 other => panic!("expected handshake capture, got {other:?}"),
395 }
396 let _ = std::fs::remove_dir_all(&dir);
397 }
398
399 #[test]
400 fn extract_skips_handshake_without_essid() {
401 let dir = std::env::temp_dir().join(format!(
402 "wifi_lab-pcapin-test-{}-noessid",
403 std::process::id()
404 ));
405 std::fs::create_dir_all(&dir).unwrap();
406 let path = dir.join("noessid.pcap");
407 let mut anonce = [0u8; 32];
408 anonce[0] = 0xaa;
409 let mut snonce = [0u8; 32];
410 snonce[0] = 0xbb;
411 let mut mic = [0u8; 16];
412 mic[0] = 0xcc;
413 // No beacon in the file → essid unresolvable → no capture.
414 let frames = vec![
415 radiotap_wrap(build_eapol_frame(
416 true,
417 &eapol_key(true, 1, anonce, [0; 16]),
418 )),
419 radiotap_wrap(build_eapol_frame(false, &eapol_key(false, 2, snonce, mic))),
420 ];
421 {
422 let mut w = pcapout::create(&path).unwrap();
423 for f in &frames {
424 w.append(f).unwrap();
425 }
426 w.finish().unwrap();
427 }
428 let caps = extract(&path).unwrap();
429 assert!(caps.is_empty());
430 let _ = std::fs::remove_dir_all(&dir);
431 }
432}