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