forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

dot11.rs1001 lines, 35.7 KiBHistoryRawDownload
1//! 802.11 MAC frame parsing and building.
2//!
3//! Zero-copy where possible; all reads are bounds-checked through `get`.
4//! Frames here never carry an FCS (the driver appends it on TX, and monitor
5//! captures may or may not include one — parsers simply ignore trailing
6//! bytes beyond what they need).
7
8use crate::common::{Akm, MacAddr, Security};
9
10/// LLC/SNAP header prefixing an EAPOL payload inside a data frame.
11const SNAP_EAPOL: [u8; 8] = [0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x88, 0x8e];
12
13pub(crate) const IE_SSID: u8 = 0;
14const IE_DS_PARAM: u8 = 3;
15const IE_RSN: u8 = 48;
16pub(crate) const IE_VENDOR: u8 = 221;
17
18/// Microsoft (WPA) vendor IE OUI+type prefix.
19const WPA_OUI: [u8; 4] = [0x00, 0x50, 0xf2, 0x01];
20
21const CAP_PRIVACY: u16 = 0x0010;
22
23/// Duration value used on injected management frames.
24pub const INJECT_DURATION: u16 = 314;
25
26// ---------------------------------------------------------------------------
27// little helpers (all bounds-checked)
28// ---------------------------------------------------------------------------
29
30fn u16le(f: &[u8], o: usize) -> Option<u16> {
31 Some(u16::from_le_bytes(f.get(o..o + 2)?.try_into().ok()?))
32}
33
34fn mac_at(f: &[u8], o: usize) -> Option<MacAddr> {
35 Some(MacAddr(f.get(o..o + 6)?.try_into().ok()?))
36}
37
38/// (type, subtype) from the frame-control field.
39fn type_subtype(fc: u16) -> (u16, u16) {
40 ((fc >> 2) & 3, (fc >> 4) & 0xf)
41}
42
43/// Walk information elements starting at `cur`, invoking `f(id, body)`.
44/// Stops cleanly on a truncated trailing IE.
45fn walk_ies<T>(f: &[u8], mut cur: usize, mut cb: T)
46where
47 T: FnMut(u8, &[u8]),
48{
49 while let Some(body_len) = f.get(cur + 1).map(|&l| l as usize) {
50 let Some(body) = f.get(cur + 2..cur + 2 + body_len) else {
51 break;
52 };
53 cb(f[cur], body);
54 cur += 2 + body_len;
55 }
56}
57
58// ---------------------------------------------------------------------------
59// parsed metadata
60// ---------------------------------------------------------------------------
61
62pub struct MgmtInfo {
63 pub bssid: MacAddr,
64 pub ssid: Option<String>, // None if hidden/zero-len
65 pub channel: Option<u8>, // DS parameter set IE
66 pub security: Security, // from RSN/WPA IEs + capability privacy bit
67 /// AKM suites from the RSN/WPA IE; empty for open/WEP or unparsed frames.
68 pub akms: Vec<Akm>,
69}
70
71/// Map an RSN AKM suite type byte to `Akm`.
72fn akm_from_type(t: u8) -> Akm {
73 match t {
74 2 => Akm::Psk,
75 8 => Akm::Sae,
76 18 => Akm::Owe,
77 4 => Akm::FtPsk,
78 6 => Akm::PskSha256,
79 1 => Akm::OneX,
80 other => Akm::Other(other),
81 }
82}
83
84/// Walk the AKM suite list of an RSN IE body, collecting mapped `Akm`s.
85/// Layout: version(2) group(4) pairwise_cnt(2) pairwise[4n] akm_cnt(2) akm[4m].
86fn rsn_akms(body: &[u8], out: &mut Vec<Akm>) {
87 let Some(pair_cnt) = u16le(body, 6).map(|c| c as usize) else {
88 return;
89 };
90 let mut o = 8usize + 4 * pair_cnt;
91 let Some(akm_cnt) = u16le(body, o).map(|c| c as usize) else {
92 return;
93 };
94 o += 2;
95 for i in 0..akm_cnt {
96 let Some(suite) = body.get(o + 4 * i..o + 4 * i + 4) else {
97 break;
98 };
99 out.push(akm_from_type(suite[3]));
100 }
101}
102
103/// True if the RSN IE body lists AKM suite 00:0f:ac:8 (SAE → WPA3).
104fn rsn_has_akm(body: &[u8], akm_type: u8) -> bool {
105 // layout: version(2) group(4) pairwise_cnt(2) pairwise[4n]
106 // akm_cnt(2) akm[4m] ...
107 let Some(pair_cnt) = u16le(body, 6).map(|c| c as usize) else {
108 return false;
109 };
110 let mut o = 8usize + 4 * pair_cnt;
111 let Some(akm_cnt) = u16le(body, o).map(|c| c as usize) else {
112 return false;
113 };
114 o += 2;
115 for i in 0..akm_cnt {
116 let Some(suite) = body.get(o + 4 * i..o + 4 * i + 4) else {
117 break;
118 };
119 if suite[0] == 0x00 && suite[1] == 0x0f && suite[2] == 0xac && suite[3] == akm_type {
120 return true;
121 }
122 }
123 false
124}
125
126// ---------------------------------------------------------------------------
127// management frame parsers
128// ---------------------------------------------------------------------------
129
130/// Parse beacon OR probe-response; None for other/broken frames.
131pub fn parse_beacon_or_probe(f: &[u8]) -> Option<MgmtInfo> {
132 let fc = u16le(f, 0)?;
133 let (ty, st) = type_subtype(fc);
134 if ty != 0 || (st != 8 && st != 5) {
135 return None;
136 }
137 // fixed params: timestamp(8) interval(2) capability(2) after 24B header
138 let cap = u16le(f, 34)?;
139
140 let mut ssid = None;
141 let mut channel = None;
142 let mut has_rsn = false;
143 let mut has_sae = false;
144 let mut has_wpa = false;
145 let mut akms = Vec::new();
146 walk_ies(f, 36, |id, body| match id {
147 IE_SSID => {
148 if !body.is_empty() {
149 ssid = Some(String::from_utf8_lossy(body).into_owned());
150 }
151 }
152 IE_DS_PARAM => {
153 channel = body.first().copied();
154 }
155 IE_RSN => {
156 has_rsn = true;
157 has_sae |= rsn_has_akm(body, 8);
158 rsn_akms(body, &mut akms);
159 }
160 IE_VENDOR if body.len() >= 4 && body[..4] == WPA_OUI => {
161 has_wpa = true;
162 // WPA1 vendor IE: only PSK key management exists.
163 akms.push(Akm::Psk);
164 }
165 _ => {}
166 });
167
168 let security = if has_rsn {
169 if has_sae {
170 Security::Wpa3
171 } else {
172 Security::Wpa2
173 }
174 } else if has_wpa {
175 Security::Wpa
176 } else if cap & CAP_PRIVACY != 0 {
177 Security::Wep
178 } else {
179 Security::Open
180 };
181
182 // An AP advertising WPA (vendor IE) AND WPA2 (RSN IE, e.g. mixed or
183 // transition mode) otherwise surfaces PSK twice. First-seen order wins.
184 let mut uniq: Vec<Akm> = Vec::with_capacity(akms.len());
185 for a in akms {
186 if !uniq.contains(&a) {
187 uniq.push(a);
188 }
189 }
190 let akms = uniq;
191
192 Some(MgmtInfo {
193 bssid: mac_at(f, 16)?,
194 ssid,
195 channel,
196 security,
197 akms,
198 })
199}
200
201/// Parse probe-request → Some((sta, ssid of probe)); None on broadcast
202/// (zero-len SSID) yields `(sta, None)`. Non-probe frames → None.
203pub fn parse_probe_req(f: &[u8]) -> Option<(MacAddr, Option<String>)> {
204 let fc = u16le(f, 0)?;
205 if type_subtype(fc) != (0, 4) {
206 return None;
207 }
208 let sta = mac_at(f, 10)?;
209 let mut ssid = None;
210 walk_ies(f, 24, |id, body| {
211 if id == IE_SSID && !body.is_empty() {
212 ssid = Some(String::from_utf8_lossy(body).into_owned());
213 }
214 });
215 if f.len() < 24 {
216 return None;
217 }
218 Some((sta, ssid))
219}
220
221// ---------------------------------------------------------------------------
222// device correlation (pairing rotated/randomized MACs of one radio)
223// ---------------------------------------------------------------------------
224
225/// 12-bit per-transmitter sequence number (bytes 22-24, high nibble is the
226/// fragment number). A device's sequence counter survives MAC rotation, so
227/// near-continuity between two MACs' frames is a strong pairing witness.
228pub fn seq_of(f: &[u8]) -> Option<u16> {
229 Some(u16le(f, 22)? >> 4)
230}
231
232fn fnv_add(h: &mut u32, b: u8) {
233 *h ^= b as u32;
234 *h = h.wrapping_mul(0x0100_0193);
235}
236
237/// Ordered-IE device fingerprint (probe/assoc request frames): FNV-1a over
238/// the (tag, len) sequence, plus full payloads of the rate tags and the
239/// OUI+type tuple of vendor IEs. Stable per driver/firmware build and
240/// independent of the station's (possibly randomized) MAC and of which
241/// SSIDs it is probing. Different drivers of the same model usually share
242/// it, so it is a *probable* witness, not identity — pair it with UUID-E or
243/// sequence continuity for certainty.
244pub fn ie_fingerprint(f: &[u8], ie_off: usize) -> Option<u32> {
245 let mut h = 0x811c_9dc5u32;
246 let mut n = 0u32;
247 walk_ies(f, ie_off, |id, body| {
248 fnv_add(&mut h, id);
249 // SSID tag: content-agnostic. Directed and wildcard probes of the
250 // same radio alternate freely and differ only in this length; the
251 // probed-network signal comes from the group's SSID set instead.
252 if id != IE_SSID {
253 fnv_add(&mut h, body.len() as u8);
254 }
255 match id {
256 // rates + extended rates: full payload is model-specific
257 1 | 50 => body.iter().for_each(|&b| fnv_add(&mut h, b)),
258 // vendor IE: OUI+type+len, not the (device-varying) payload
259 IE_VENDOR if body.len() >= 4 => body[..4].iter().for_each(|&b| fnv_add(&mut h, b)),
260 _ => {}
261 }
262 n += 1;
263 });
264 (n > 0).then_some(h)
265}
266
267/// WPS UUID-E (attribute 0x1047) from a WPS vendor IE, if present. A stable
268/// per-device identifier leaked in probe requests by devices with WPS on —
269/// an exact pairing witness across MAC rotation.
270pub fn wps_uuid_e(f: &[u8], ie_off: usize) -> Option<[u8; 16]> {
271 // WPS vendor IE: OUI 00:50:f2, type 0x04; attributes are BE (id, len).
272 const WPS_OUI: [u8; 4] = [0x00, 0x50, 0xf2, 0x04];
273 const ATTR_UUID_E: u16 = 0x1047;
274 let mut out = None;
275 walk_ies(f, ie_off, |id, body| {
276 if id != IE_VENDOR || body.len() < 4 || body[..4] != WPS_OUI {
277 return;
278 }
279 let mut cur = 4;
280 while cur + 4 <= body.len() {
281 let attr = u16::from_be_bytes([body[cur], body[cur + 1]]);
282 let len = u16::from_be_bytes([body[cur + 2], body[cur + 3]]) as usize;
283 let Some(val) = body.get(cur + 4..cur + 4 + len) else {
284 break;
285 };
286 if attr == ATTR_UUID_E && len == 16 {
287 out = Some(val.try_into().expect("len checked"));
288 }
289 cur += 4 + len;
290 }
291 });
292 out
293}
294
295/// Device-correlation material parsed from a probe request.
296#[derive(Clone, Debug, PartialEq, Eq)]
297pub struct ProbeIdent {
298 pub sta: MacAddr,
299 pub ssid: Option<String>, // None for the wildcard probe
300 pub fingerprint: u32,
301 pub uuid: Option<[u8; 16]>,
302}
303
304/// Same, from an association/reassociation request (adds the target bssid).
305#[derive(Clone, Debug, PartialEq, Eq)]
306pub struct AssocIdent {
307 pub sta: MacAddr,
308 pub bssid: MacAddr,
309 pub ssid: Option<String>,
310 pub fingerprint: u32,
311 pub uuid: Option<[u8; 16]>,
312}
313
314/// Probe request with device-correlation material; None for other frames or
315/// probes with an empty/malformed IE chain (fingerprint impossible).
316pub fn parse_probe_ident(f: &[u8]) -> Option<ProbeIdent> {
317 let fc = u16le(f, 0)?;
318 if type_subtype(fc) != (0, 4) {
319 return None;
320 }
321 let sta = mac_at(f, 10)?;
322 let fingerprint = ie_fingerprint(f, 24)?;
323 let mut ssid = None;
324 walk_ies(f, 24, |id, body| {
325 if id == IE_SSID && !body.is_empty() {
326 ssid = Some(String::from_utf8_lossy(body).into_owned());
327 }
328 });
329 let uuid = wps_uuid_e(f, 24);
330 Some(ProbeIdent {
331 sta,
332 ssid,
333 fingerprint,
334 uuid,
335 })
336}
337
338/// Assoc/reassoc request with device-correlation material; None for other
339/// frames. SSID is None for hidden (empty/NUL-padded) networks.
340pub fn parse_assoc_ident(f: &[u8]) -> Option<AssocIdent> {
341 let fc = u16le(f, 0)?;
342 let (ty, st) = type_subtype(fc);
343 if ty != 0 || st > 1 {
344 return None;
345 }
346 let ie_off = if st == 0 { 28 } else { 34 };
347 if f.len() < ie_off {
348 return None;
349 }
350 let bssid = mac_at(f, 4)?;
351 let sta = mac_at(f, 10)?;
352 let fingerprint = ie_fingerprint(f, ie_off)?;
353 let mut ssid = None;
354 walk_ies(f, ie_off, |id, body| {
355 if id == IE_SSID {
356 let meaningful = body.iter().take_while(|&&b| b != 0).count();
357 if meaningful > 0 {
358 ssid = Some(String::from_utf8_lossy(&body[..meaningful]).into_owned());
359 }
360 }
361 });
362 let uuid = wps_uuid_e(f, ie_off);
363 Some(AssocIdent {
364 sta,
365 bssid,
366 ssid,
367 fingerprint,
368 uuid,
369 })
370}
371
372/// Parse deauth/disassoc → (from-ap MacAddr as transmitter, target addr1).
373pub fn parse_deauth(f: &[u8]) -> Option<(MacAddr, MacAddr)> {
374 let fc = u16le(f, 0)?;
375 let (ty, st) = type_subtype(fc);
376 if ty != 0 || (st != 12 && st != 10) {
377 return None;
378 }
379 Some((mac_at(f, 10)?, mac_at(f, 4)?))
380}
381
382// ---------------------------------------------------------------------------
383// data frames
384// ---------------------------------------------------------------------------
385
386/// Header length of a data frame: 24 base, +6 for addr4 in WDS
387/// (ToDS && FromDS), +2 for QoS control on QoS data subtypes.
388fn data_hdr_len(fc: u16) -> usize {
389 let mut n = 24;
390 if fc & 0x0100 != 0 && fc & 0x0200 != 0 {
391 n += 6; // addr4 (WDS)
392 }
393 if fc & 0x0080 != 0 {
394 n += 2; // QoS control
395 }
396 n
397}
398
399/// Extract (bssid, station) that best describes a data frame's endpoints
400/// using ToDS/FromDS bits. None for mgmt/ctrl frames.
401pub fn data_endpoints(f: &[u8]) -> Option<(MacAddr, MacAddr)> {
402 let fc = u16le(f, 0)?;
403 if type_subtype(fc).0 != 2 {
404 return None;
405 }
406 let to_ds = fc & 0x0100 != 0;
407 let from_ds = fc & 0x0200 != 0;
408 Some(match (to_ds, from_ds) {
409 // IBSS / ad-hoc: bssid in addr3, station is the transmitter.
410 (false, false) => (mac_at(f, 16)?, mac_at(f, 10)?),
411 // AP → STA: bssid is addr2, station is addr1.
412 (false, true) => (mac_at(f, 10)?, mac_at(f, 4)?),
413 // STA → AP: bssid is addr1, station is addr2.
414 (true, false) => (mac_at(f, 4)?, mac_at(f, 10)?),
415 // WDS: addr1=RA, addr2=TA, addr4=SA.
416 (true, true) => (mac_at(f, 10)?, mac_at(f, 24)?),
417 })
418}
419
420/// If frame carries an EAPOL-Key payload (LLC/SNAP 88-8e in a data frame),
421/// return (bssid, station_is_ap_sender, eapol_bytes).
422pub fn parse_eapol(f: &[u8]) -> Option<(MacAddr, bool, &[u8])> {
423 let fc = u16le(f, 0)?;
424 if type_subtype(fc).0 != 2 {
425 return None;
426 }
427 let to_ds = fc & 0x0100 != 0;
428 let from_ds = fc & 0x0200 != 0;
429 let hdr = data_hdr_len(fc);
430 if *f.get(hdr..hdr + 8)? != SNAP_EAPOL {
431 return None;
432 }
433 let eapol = f.get(hdr + 8..)?;
434 let (bssid, ap_sender) = match (to_ds, from_ds) {
435 (false, false) => (mac_at(f, 16)?, false),
436 (false, true) => (mac_at(f, 10)?, true),
437 (true, false) => (mac_at(f, 4)?, false),
438 (true, true) => (mac_at(f, 10)?, true),
439 };
440 Some((bssid, ap_sender, eapol))
441}
442
443// ---------------------------------------------------------------------------
444// EAPOL-Key
445// ---------------------------------------------------------------------------
446
447pub struct EapolKey<'a> {
448 pub key_ver: u8, // bits 0..3 of key_info (descriptor version)
449 pub install: bool, // bit6
450 pub key_ack: bool, // bit7
451 pub key_mic: bool, // bit8
452 pub secure: bool, // bit9
453 pub replay_counter: u64,
454 pub nonce: [u8; 32],
455 pub mic: [u8; 16], // raw mic field (or RSN IE scan for pmkid)
456 pub key_data: &'a [u8], // RSN IE / KDEs (PMKID: 00-0f-ac:4)
457 pub raw: &'a [u8], // full eapol frame starting at version byte
458}
459
460/// Parse an EAPOL-Key frame. Frame offsets (descriptor body starts at 4):
461/// key_info 5..7, replay 9..17, nonce 17..49, iv 49..65, rsc 65..73,
462/// id 73..81, mic 81..97, key_data_len 97..99, key_data 99..
463pub fn parse_eapol_key(eapol: &[u8]) -> Option<EapolKey<'_>> {
464 // eapol header(4) + 95-byte key descriptor fixed part = 99 minimum
465 if eapol.len() < 99 {
466 return None;
467 }
468 if eapol[1] != 3 {
469 return None; // not an EAPOL-Key packet
470 }
471 let key_info = u16::from_be_bytes([eapol[5], eapol[6]]);
472 let key_data_len = u16::from_be_bytes([eapol[97], eapol[98]]) as usize;
473 let key_data = &eapol[99..eapol.len().min(99 + key_data_len)];
474 Some(EapolKey {
475 key_ver: (key_info & 0x7) as u8,
476 install: key_info & (1 << 6) != 0,
477 key_ack: key_info & (1 << 7) != 0,
478 key_mic: key_info & (1 << 8) != 0,
479 secure: key_info & (1 << 9) != 0,
480 replay_counter: u64::from_be_bytes(eapol[9..17].try_into().ok()?),
481 nonce: eapol[17..49].try_into().ok()?,
482 mic: eapol[81..97].try_into().ok()?,
483 key_data,
484 raw: eapol,
485 })
486}
487
488/// 1..=4 4way message number derived from flags, 0 if not an EAPOL-Key.
489pub fn eapol_4way_msg(k: &EapolKey) -> u8 {
490 // descriptor type 2 = RSN key, 254 = legacy WPA key
491 if !(k.raw.len() > 4 && (k.raw[4] == 2 || k.raw[4] == 254)) {
492 return 0;
493 }
494 if k.key_ack && !k.key_mic {
495 1 // M1: ack, no mic
496 } else if k.key_ack && k.key_mic && k.install {
497 3 // M3: ack+mic+install
498 } else if !k.key_ack && k.key_mic && k.secure {
499 4 // M4: mic+secure, no ack
500 } else if !k.key_ack && k.key_mic && !k.secure {
501 2 // M2: mic, no ack, not secure yet
502 } else {
503 0
504 }
505}
506
507// ---------------------------------------------------------------------------
508// frame builders (full 802.11 frame, NO radiotap — caller prepends INJECT_HDR)
509// ---------------------------------------------------------------------------
510
511fn hdr3(fc_lo: u8, addr1: &MacAddr, addr2: &MacAddr, addr3: &MacAddr, seq: u16) -> Vec<u8> {
512 let mut v = Vec::with_capacity(24);
513 v.extend_from_slice(&[fc_lo, 0x00]);
514 v.extend_from_slice(&INJECT_DURATION.to_le_bytes());
515 v.extend_from_slice(&addr1.0);
516 v.extend_from_slice(&addr2.0);
517 v.extend_from_slice(&addr3.0);
518 v.extend_from_slice(&(seq << 4).to_le_bytes()); // seq control: seq in bits 4..16
519 v
520}
521
522pub fn build_deauth(ap: &MacAddr, target: &MacAddr, reason: u16) -> Vec<u8> {
523 let mut v = hdr3(0xC0, target, ap, ap, 0);
524 v.extend_from_slice(&reason.to_le_bytes());
525 v
526}
527
528/// Probe request sta → broadcast: empty `ssid` = wildcard (every AP on
529/// the channel should answer with a probe response), otherwise directed.
530/// Used by the injection canary: a response proves injected frames
531/// actually radiate.
532pub fn build_probe_req(ssid: &[u8], sa: &MacAddr) -> Vec<u8> {
533 let mut v = hdr3(0x40, &MacAddr::BROADCAST, sa, &MacAddr::BROADCAST, 0);
534 v.push(IE_SSID);
535 v.push(ssid.len().min(32) as u8);
536 v.extend_from_slice(&ssid[..ssid.len().min(32)]);
537 v.extend_from_slice(&[0x01, 0x04, 0x82, 0x84, 0x8b, 0x96]); // supported rates
538 v
539}
540
541/// Open-system authentication request sta → ap (algo 0, transaction 1).
542pub fn build_auth_open(ap: &MacAddr, sta: &MacAddr, seq: u16) -> Vec<u8> {
543 let mut v = hdr3(0xB0, ap, sta, ap, seq);
544 v.extend_from_slice(&0u16.to_le_bytes()); // auth algorithm: open system
545 v.extend_from_slice(&1u16.to_le_bytes()); // transaction sequence
546 v.extend_from_slice(&0u16.to_le_bytes()); // status
547 v
548}
549
550/// Association request sta → ap: capability + listen interval + SSID IE.
551pub fn build_assoc_req(ap: &MacAddr, sta: &MacAddr, ssid: &[u8]) -> Vec<u8> {
552 let mut v = hdr3(0x00, ap, sta, ap, 0);
553 v.extend_from_slice(&0x0431u16.to_le_bytes()); // capability (ESS | short preamble ...)
554 v.extend_from_slice(&10u16.to_le_bytes()); // listen interval
555 v.push(IE_SSID);
556 v.push(ssid.len().min(32) as u8);
557 v.extend_from_slice(&ssid[..ssid.len().min(32)]);
558 v
559}
560
561// ---------------------------------------------------------------------------
562// tests
563// ---------------------------------------------------------------------------
564
565#[cfg(test)]
566mod tests {
567 use super::*;
568
569 const AP: MacAddr = MacAddr([0x24, 0x65, 0x11, 0xaa, 0xbb, 0xcc]);
570 const STA: MacAddr = MacAddr([0x9c, 0xef, 0xd5, 0x11, 0x22, 0x33]);
571
572 fn ie(id: u8, body: &[u8]) -> Vec<u8> {
573 let mut v = vec![id, body.len() as u8];
574 v.extend_from_slice(body);
575 v
576 }
577
578 fn rsn_ie(akm_type: u8) -> Vec<u8> {
579 // version 1, group CCMP, 1×pairwise CCMP, 1×AKM, rsn caps 0
580 let mut b = vec![
581 0x01, 0x00, // version
582 0x00, 0x0f, 0xac, 0x04, // group cipher CCMP
583 0x01, 0x00, // pairwise count
584 0x00, 0x0f, 0xac, 0x04, // pairwise CCMP
585 0x01, 0x00, // akm count
586 0x00, 0x0f, 0xac, akm_type, // PSK=2 / SAE=8
587 0x00, 0x00, // rsn capabilities
588 ];
589 ie(IE_RSN, &b.split_off(0))
590 }
591
592 /// FCS-free beacon as it would appear after radiotap is stripped:
593 /// SSID "testnet", channel 6, WPA2 (RSN, AKM PSK), privacy bit set.
594 fn testnet_beacon() -> Vec<u8> {
595 let mut v = vec![0x80, 0x00]; // FC: beacon
596 v.extend_from_slice(&[0x00, 0x00]); // duration
597 v.extend_from_slice(&MacAddr::BROADCAST.0); // addr1
598 v.extend_from_slice(&AP.0); // addr2 = transmitter
599 v.extend_from_slice(&AP.0); // addr3 = bssid
600 v.extend_from_slice(&[0x00, 0x00]); // seq
601 v.extend_from_slice(&[0x00; 8]); // timestamp
602 v.extend_from_slice(&100u16.to_le_bytes()); // beacon interval
603 v.extend_from_slice(&0x0411u16.to_le_bytes()); // capability: ESS | privacy | short preamble
604 v.extend_from_slice(&ie(IE_SSID, b"testnet"));
605 v.extend_from_slice(&ie(1, &[0x82, 0x84, 0x8b, 0x96])); // supported rates
606 v.extend_from_slice(&ie(IE_DS_PARAM, &[6])); // channel 6
607 v.extend_from_slice(&ie(5, &[0x00, 0x01, 0x00, 0x00])); // TIM
608 v.extend_from_slice(&rsn_ie(2));
609 v
610 }
611
612 #[test]
613 fn testnet_beacon_parses_to_wpa2_ch6() {
614 let info = parse_beacon_or_probe(&testnet_beacon()).expect("beacon parses");
615 assert_eq!(info.bssid, AP);
616 assert_eq!(info.ssid.as_deref(), Some("testnet"));
617 assert_eq!(info.channel, Some(6));
618 assert_eq!(info.security, Security::Wpa2);
619 }
620
621 /// RSN IE with several AKM suites listed in order.
622 fn rsn_ie_multi(akm_types: &[u8]) -> Vec<u8> {
623 let mut b = vec![
624 0x01, 0x00, // version
625 0x00, 0x0f, 0xac, 0x04, // group cipher CCMP
626 0x01, 0x00, // pairwise count
627 0x00, 0x0f, 0xac, 0x04, // pairwise CCMP
628 ];
629 b.extend_from_slice(&(akm_types.len() as u16).to_le_bytes());
630 for &t in akm_types {
631 b.extend_from_slice(&[0x00, 0x0f, 0xac, t]);
632 }
633 b.extend_from_slice(&[0x00, 0x00]); // rsn capabilities
634 let b = b.split_off(0);
635 ie(IE_RSN, &b)
636 }
637
638 /// Beacon like `testnet_beacon` but with the RSN IE replaced by `rsn`.
639 fn beacon_with_rsn(rsn: Vec<u8>) -> Vec<u8> {
640 let mut v = testnet_beacon();
641 v.splice(v.len() - rsn_ie(2).len().., rsn);
642 v
643 }
644
645 #[test]
646 fn akm_list_parsed() {
647 // WPA2/WPA3 transition: PSK + SAE both advertised.
648 let f = beacon_with_rsn(rsn_ie_multi(&[2, 8]));
649 let info = parse_beacon_or_probe(&f).expect("beacon parses");
650 assert_eq!(info.akms, vec![Akm::Psk, Akm::Sae]);
651 // security label logic untouched: SAE present → Wpa3
652 assert_eq!(info.security, Security::Wpa3);
653
654 // OWE (type 18)
655 let f = beacon_with_rsn(rsn_ie_multi(&[18]));
656 let info = parse_beacon_or_probe(&f).unwrap();
657 assert_eq!(info.akms, vec![Akm::Owe]);
658 // no SAE → Wpa2 label
659 assert_eq!(info.security, Security::Wpa2);
660
661 // unknown suite type → Other, PSK still mapped
662 let f = beacon_with_rsn(rsn_ie_multi(&[2, 99]));
663 let info = parse_beacon_or_probe(&f).unwrap();
664 assert_eq!(info.akms, vec![Akm::Psk, Akm::Other(99)]);
665
666 // plain WPA2-PSK beacon: single PSK entry
667 let info = parse_beacon_or_probe(&testnet_beacon()).unwrap();
668 assert_eq!(info.akms, vec![Akm::Psk]);
669
670 // open network: no security IEs → empty akms
671 let mut f = testnet_beacon();
672 f.truncate(36);
673 f.extend_from_slice(&ie(IE_SSID, b"cafe"));
674 f[34] = 0x01; // clear privacy bit
675 f[35] = 0x04;
676 let info = parse_beacon_or_probe(&f).unwrap();
677 assert_eq!(info.security, Security::Open);
678 assert_eq!(info.akms, Vec::<Akm>::new());
679 }
680
681 #[test]
682 fn wpa1_vendor_ie_yields_psk_akm() {
683 let mut f = testnet_beacon();
684 f.truncate(36);
685 f.extend_from_slice(&ie(IE_SSID, b"legacy"));
686 // WPA_OUI vendor IE: oui+type, then version(2) — content beyond the
687 // OUI is not inspected, so the minimal fixture suffices.
688 f.extend_from_slice(&ie(IE_VENDOR, &[0x00, 0x50, 0xf2, 0x01, 0x01, 0x00]));
689 let info = parse_beacon_or_probe(&f).unwrap();
690 assert_eq!(info.security, Security::Wpa);
691 assert_eq!(info.akms, vec![Akm::Psk]);
692 }
693
694 #[test]
695 fn akms_deduped_across_wpa_and_rsn_ies() {
696 // Mixed WPA/WPA2 AP: RSN IE with PSK plus the WPA vendor IE — the
697 // vendor arm must not surface a duplicate PSK.
698 let mut f = beacon_with_rsn(rsn_ie_multi(&[2]));
699 f.extend_from_slice(&ie(IE_VENDOR, &[0x00, 0x50, 0xf2, 0x01, 0x01, 0x00]));
700 let info = parse_beacon_or_probe(&f).unwrap();
701 assert_eq!(info.akms, vec![Akm::Psk], "no PSK+PSK duplication");
702 }
703
704 #[test]
705 fn seq_number_extracted() {
706 let mut f = testnet_beacon();
707 // seq field at bytes 22-24: seq<<4 | frag
708 f[22] = 0x30; // seq 3, frag 0
709 f[23] = 0x02; // → 0x230 >> 4 = 0x23 = 35
710 assert_eq!(seq_of(&f), Some(0x23));
711 assert_eq!(seq_of(&f[..20]), None);
712 }
713
714 /// Probe builder mirroring the scanner tests' shape.
715 fn probe_with(sta: &MacAddr, ssid: Option<&str>, ies: &[Vec<u8>], seq: u16) -> Vec<u8> {
716 let mut v = Vec::new();
717 v.extend_from_slice(&0x0040u16.to_le_bytes());
718 v.extend_from_slice(&0u16.to_le_bytes());
719 v.extend_from_slice(&MacAddr::BROADCAST.0);
720 v.extend_from_slice(&sta.0);
721 v.extend_from_slice(&MacAddr::BROADCAST.0);
722 v.extend_from_slice(&(seq << 4).to_le_bytes());
723 match ssid {
724 Some(s) => v.extend_from_slice(&ie(IE_SSID, s.as_bytes())),
725 None => v.extend_from_slice(&ie(IE_SSID, b"")),
726 }
727 for b in ies {
728 v.extend_from_slice(b);
729 }
730 v
731 }
732
733 #[test]
734 fn fingerprint_stable_directed_vs_wildcard() {
735 // The same radio alternating directed/wildcard probes must hash
736 // identically; a different IE chain must not.
737 let rates = ie(1, &[0x82, 0x84, 0x8b, 0x96]);
738 let f1 = probe_with(&STA, Some("testnet"), std::slice::from_ref(&rates), 7);
739 let f2 = probe_with(&STA, None, std::slice::from_ref(&rates), 8);
740 let i1 = parse_probe_ident(&f1).expect("parses");
741 let i2 = parse_probe_ident(&f2).expect("parses");
742 assert_eq!(i1.fingerprint, i2.fingerprint);
743 assert_eq!(i1.ssid.as_deref(), Some("testnet"));
744 assert_eq!(i2.ssid, None);
745
746 let other = probe_with(&STA, None, &[ie(1, &[0x82, 0x84])], 9);
747 let i3 = parse_probe_ident(&other).expect("parses");
748 assert_ne!(i1.fingerprint, i3.fingerprint);
749
750 // Off a probe frame entirely → None.
751 assert!(parse_probe_ident(&testnet_beacon()).is_none());
752 }
753
754 #[test]
755 fn wps_uuid_e_parsed_from_probe() {
756 let uuid = [0xabu8; 16];
757 let mut wps_body = vec![0x00, 0x50, 0xf2, 0x04];
758 wps_body.extend_from_slice(&0x1047u16.to_be_bytes());
759 wps_body.extend_from_slice(&16u16.to_be_bytes());
760 wps_body.extend_from_slice(&uuid);
761 let wps = ie(IE_VENDOR, &wps_body);
762 let f = probe_with(&STA, None, &[wps], 7);
763 let ident = parse_probe_ident(&f).expect("parses");
764 assert_eq!(ident.uuid, Some(uuid));
765 // Truncated attribute body → no uuid, no panic.
766 let short = ie(
767 IE_VENDOR,
768 &[0x00, 0x50, 0xf2, 0x04, 0x10, 0x47, 0x00, 0x10, 0xaa, 0xbb],
769 );
770 let f = probe_with(&STA, None, &[short], 7);
771 assert_eq!(parse_probe_ident(&f).unwrap().uuid, None);
772 }
773
774 #[test]
775 fn assoc_ident_parsed() {
776 let f = build_assoc_req(&AP, &STA, b"testap");
777 let ident = parse_assoc_ident(&f).expect("assoc ident parses");
778 assert_eq!(ident.sta, STA);
779 assert_eq!(ident.bssid, AP);
780 assert_eq!(ident.ssid.as_deref(), Some("testap"));
781 assert_eq!(ident.uuid, None);
782 assert!(parse_assoc_ident(&testnet_beacon()).is_none());
783 for cut in 0..f.len() {
784 let _ = parse_assoc_ident(&f[..cut]);
785 }
786 }
787
788 #[test]
789 fn beacon_security_matrix() {
790 // WPA3: same beacon but SAE AKM
791 let mut f = testnet_beacon();
792 let rsn_at = f.len() - rsn_ie(8).len();
793 f.splice(rsn_at.., rsn_ie(8));
794 assert_eq!(parse_beacon_or_probe(&f).unwrap().security, Security::Wpa3);
795
796 // WPA: vendor IE, no RSN
797 let mut hdr_fixed = testnet_beacon();
798 hdr_fixed.truncate(36);
799 hdr_fixed.extend_from_slice(&ie(IE_SSID, b"legacy"));
800 hdr_fixed.extend_from_slice(&ie(IE_VENDOR, &[0x00, 0x50, 0xf2, 0x01, 0x01, 0x00]));
801 assert_eq!(
802 parse_beacon_or_probe(&hdr_fixed).unwrap().security,
803 Security::Wpa
804 );
805
806 // WEP: privacy bit only
807 let mut f = testnet_beacon();
808 f.truncate(36);
809 f.extend_from_slice(&ie(IE_SSID, b"oldnet"));
810 assert_eq!(parse_beacon_or_probe(&f).unwrap().security, Security::Wep);
811
812 // Open: clear privacy bit
813 f[34] = 0x01;
814 f[35] = 0x04;
815 assert_eq!(parse_beacon_or_probe(&f).unwrap().security, Security::Open);
816 }
817
818 #[test]
819 fn hidden_ssid_and_truncated_safe() {
820 let mut f = testnet_beacon();
821 // zero-length SSID IE → None (hidden)
822 let ssid_at = 36;
823 f.drain(ssid_at..ssid_at + 2 + 7);
824 f.splice(ssid_at..ssid_at, vec![IE_SSID, 0]);
825 let info = parse_beacon_or_probe(&f).unwrap();
826 assert_eq!(info.ssid, None);
827 assert_eq!(info.channel, Some(6));
828 // truncation inside an IE: no panic, best-effort parse
829 for cut in 0..f.len() {
830 let _ = parse_beacon_or_probe(&f[..cut]);
831 let _ = parse_probe_req(&f[..cut]);
832 let _ = parse_deauth(&f[..cut]);
833 let _ = data_endpoints(&f[..cut]);
834 let _ = parse_eapol(&f[..cut]);
835 let _ = parse_eapol_key(&f[..cut]);
836 }
837 }
838
839 #[test]
840 fn build_parse_deauth_roundtrip() {
841 let f = build_deauth(&AP, &STA, 7);
842 assert_eq!(f[0], 0xC0);
843 assert_eq!(u16le(&f, 2), Some(314));
844 assert_eq!(parse_deauth(&f), Some((AP, STA)));
845 assert_eq!(u16le(&f, 24), Some(7)); // reason
846 }
847
848 #[test]
849 fn build_auth_and_assoc() {
850 let a = build_auth_open(&AP, &STA, 42);
851 assert_eq!(a[0], 0xB0);
852 assert_eq!(u16le(&a, 2), Some(314));
853 assert_eq!(mac_at(&a, 16), Some(AP)); // addr3 bssid = ap
854 assert_eq!(u16le(&a, 24), Some(0)); // open system
855 assert_eq!(u16le(&a, 26), Some(1)); // transaction 1
856 assert_eq!(u16le(&a, 22), Some(42 << 4)); // seq number encoded
857
858 let r = build_assoc_req(&AP, &STA, b"testnet");
859 assert_eq!(r[0], 0x00);
860 assert_eq!(r[28], IE_SSID);
861 assert_eq!(r[29], 7);
862 assert_eq!(&r[30..], b"testnet");
863 }
864
865 #[test]
866 fn probe_req_parsed() {
867 let mut f = hdr3(0x40, &MacAddr::BROADCAST, &STA, &MacAddr::BROADCAST, 0);
868 f.extend_from_slice(&ie(IE_SSID, b"testnet"));
869 let (sta, ssid) = parse_probe_req(&f).unwrap();
870 assert_eq!(sta, STA);
871 assert_eq!(ssid.as_deref(), Some("testnet"));
872 }
873
874 #[test]
875 fn build_probe_req_roundtrips_wildcard_and_directed() {
876 let wild = build_probe_req(&[], &STA);
877 let (sta, ssid) = parse_probe_req(&wild).unwrap();
878 assert_eq!(sta, STA);
879 assert_eq!(ssid, None, "wildcard SSID (len 0) parses as None");
880 let dir = build_probe_req(b"testnet", &STA);
881 let (sta, ssid) = parse_probe_req(&dir).unwrap();
882 assert_eq!(sta, STA);
883 assert_eq!(ssid.as_deref(), Some("testnet"));
884
885 // broadcast probe: zero-len SSID → None
886 let mut b = hdr3(0x40, &MacAddr::BROADCAST, &STA, &MacAddr::BROADCAST, 0);
887 b.extend_from_slice(&ie(IE_SSID, b""));
888 assert_eq!(parse_probe_req(&b), Some((STA, None)));
889
890 // beacon is not a probe request
891 assert!(parse_probe_req(&testnet_beacon()).is_none());
892 }
893
894 /// Minimal EAPOL-Key frame with the given key_info (BE), filled otherwise.
895 fn eapol_key(key_info: u16) -> Vec<u8> {
896 let mut v = vec![2u8, 3, 0, 95]; // version 2, type KEY, body len
897 v.push(2); // descriptor type: RSN
898 v.extend_from_slice(&key_info.to_be_bytes());
899 v.extend_from_slice(&[0; 16 + 8 - 2 - 2 - 1]); // key_len..replay start pad
900 v.truncate(9);
901 v.extend_from_slice(&1u64.to_be_bytes()); // replay counter
902 v.extend_from_slice(&[0x11; 32]); // nonce
903 v.extend_from_slice(&[0; 16 + 8 + 8]); // iv + rsc + id
904 v.extend_from_slice(&[0x22; 16]); // mic
905 v.extend_from_slice(&[0, 0]); // key_data_len
906 v
907 }
908
909 #[test]
910 fn eapol_key_fields_extracted() {
911 let ki: u16 = 2 | (1 << 7); // version 2 + ack
912 let e = eapol_key(ki);
913 let k = parse_eapol_key(&e).unwrap();
914 assert_eq!(k.key_ver, 2);
915 assert!(k.key_ack);
916 assert!(!k.key_mic);
917 assert_eq!(k.replay_counter, 1);
918 assert_eq!(k.nonce, [0x11; 32]);
919 assert_eq!(k.mic, [0x22; 16]);
920 assert_eq!(k.key_data.len(), 0);
921 assert_eq!(k.raw, &e[..]);
922 }
923
924 #[test]
925 fn four_way_flag_matrix() {
926 const VER2: u16 = 2;
927 const INSTALL: u16 = 1 << 6;
928 const ACK: u16 = 1 << 7;
929 const MIC: u16 = 1 << 8;
930 const SECURE: u16 = 1 << 9;
931
932 let msg = |ki: u16| {
933 let e = eapol_key(ki);
934 let k = parse_eapol_key(&e).unwrap();
935 eapol_4way_msg(&k)
936 };
937 assert_eq!(msg(VER2 | ACK), 1);
938 assert_eq!(msg(VER2 | MIC), 2);
939 assert_eq!(msg(VER2 | ACK | MIC | INSTALL | SECURE), 3);
940 assert_eq!(msg(VER2 | MIC | SECURE), 4);
941 // not a key frame flag combo → 0
942 assert_eq!(msg(VER2), 0);
943 }
944
945 #[test]
946 fn data_frames_and_eapol_detection() {
947 // AP → STA data frame (from_ds) carrying EAPOL
948 let mut f = vec![0x08, 0x02];
949 f.extend_from_slice(&[0; 2]); // duration
950 f.extend_from_slice(&STA.0); // addr1
951 f.extend_from_slice(&AP.0); // addr2
952 f.extend_from_slice(&STA.0); // addr3 (DA)
953 f.extend_from_slice(&[0; 2]); // seq
954 f.extend_from_slice(&SNAP_EAPOL);
955 f.extend_from_slice(&eapol_key(2 | (1 << 7))); // M1
956
957 assert_eq!(data_endpoints(&f), Some((AP, STA)));
958 let (bssid, ap_sender, eap) = parse_eapol(&f).unwrap();
959 assert_eq!(bssid, AP);
960 assert!(ap_sender);
961 assert_eq!(eapol_4way_msg(&parse_eapol_key(eap).unwrap()), 1);
962
963 // QoS data subtype: skip 2 extra header bytes
964 let mut q = f.clone();
965 q[0] = 0x88;
966 q.splice(24..24, [0x00, 0x00]);
967 let (bssid, ap_sender, eap) = parse_eapol(&q).unwrap();
968 assert_eq!((bssid, ap_sender), (AP, true));
969 assert_eq!(eapol_4way_msg(&parse_eapol_key(eap).unwrap()), 1);
970
971 // STA → AP (to_ds): bssid = addr1
972 let mut up = vec![0x08, 0x01];
973 up.extend_from_slice(&[0; 2]);
974 up.extend_from_slice(&AP.0); // addr1 = bssid
975 up.extend_from_slice(&STA.0); // addr2 = sta
976 up.extend_from_slice(&STA.0); // addr3 = DA
977 up.extend_from_slice(&[0; 2]);
978 up.extend_from_slice(&SNAP_EAPOL);
979 up.extend_from_slice(&eapol_key(2 | (1 << 8))); // M2
980 assert_eq!(data_endpoints(&up), Some((AP, STA)));
981 let (bssid, ap_sender, eap) = parse_eapol(&up).unwrap();
982 assert_eq!((bssid, ap_sender), (AP, false));
983 assert_eq!(eapol_4way_msg(&parse_eapol_key(eap).unwrap()), 2);
984
985 // WDS: addr4 present, payload shifted
986 let mut wds = vec![0x08, 0x03];
987 wds.extend_from_slice(&[0; 2]);
988 wds.extend_from_slice(&AP.0); // addr1 RA
989 wds.extend_from_slice(&AP.0); // addr2 TA
990 wds.extend_from_slice(&STA.0); // addr3 DA
991 wds.extend_from_slice(&[0; 2]);
992 wds.extend_from_slice(&STA.0); // addr4 SA
993 wds.extend_from_slice(&SNAP_EAPOL);
994 wds.extend_from_slice(&eapol_key(2 | (1 << 7)));
995 assert_eq!(data_endpoints(&wds), Some((AP, STA)));
996 assert!(parse_eapol(&wds).is_some());
997
998 // management frame → not data
999 assert!(parse_eapol(&testnet_beacon()).is_none());
1000 }
1001}