Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / networklocation / wps_harvest / src / probe.rs

probe.rs308 lines · 11.4 KiBRaw
1//! Random BSSID probing, for when the frontier has nothing in it.
2//!
3//! The crawl normally expands because every answer contains neighbours. That only works once
4//! it knows a single real BSSID, and there is no open bulk dump to get one from — beaconDB's
5//! dumps are announced but unpublished, and Mozilla Location Services was never able to
6//! release its WiFi data at all. So the cold start is: guess addresses until one hits.
7//!
8//! ## Why guessing works at all
9//!
10//! A MAC is 48 bits, which sounds hopeless, but the top 24 are an IEEE-assigned OUI and only
11//! about 37 000 of the 16.7 million possible OUIs are assigned to anyone. Drawing from
12//! *assigned* OUI space is therefore some 450x better than drawing uniformly:
13//!
14//! | Drawing from | Candidate space | Rough hit rate |
15//! | --- | --- | --- |
16//! | Full 48-bit | 2.8e14 | ~1 in 140 000 |
17//! | Assigned OUIs | ~6.2e11 | ~1 in 300 |
18//! | OUIs already seen in responses | far smaller, and weighted by real deployment | better still |
19//!
20//! (Taking Apple's database to hold on the order of a billion access points.)
21//!
22//! So this learns. Every BSSID that comes back in any response contributes its OUI to a
23//! reservoir, and probes are drawn from that reservoir with repeats — which weights them by
24//! how common each vendor actually is in the wild, for free. A small fraction of probes go to
25//! a uniformly random OUI instead, so the crawl can still discover vendors it has never seen.
26//!
27//! One real BSSID from anywhere — a local WiFi scan will do — skips the cold start entirely
28//! and is worth far more than any amount of guessing.
29
30use std::collections::HashMap;
31
32/// Reservoir cap. Enough to represent the vendor distribution, bounded so a long crawl cannot
33/// grow it without limit.
34const MAX_RESERVOIR: usize = 1 << 20;
35
36/// Fraction of probes (in 1/256ths) drawn from a uniformly random OUI rather than a learned
37/// one, so an unseen vendor can still be discovered.
38const EXPLORE_256: u64 = 13; // ~5%
39
40/// Generates candidate BSSIDs, learning which OUIs are worth guessing.
41pub struct Prober {
42 /// Observed OUIs, with repeats, so a uniform draw is frequency-weighted.
43 reservoir: Vec<u32>,
44 /// Distinct OUIs seen, for reporting.
45 distinct: HashMap<u32, u32>,
46 state: u64,
47 /// Candidates emitted.
48 pub probes: u64,
49 /// Candidates that came back with a location.
50 pub hits: u64,
51}
52
53impl Prober {
54 /// Seed the RNG deterministically, so a run can be reproduced.
55 pub fn new(seed: u64) -> Prober {
56 Prober {
57 reservoir: Vec::new(),
58 distinct: HashMap::new(),
59 state: seed,
60 probes: 0,
61 hits: 0,
62 }
63 }
64
65 fn next_u64(&mut self) -> u64 {
66 // splitmix64
67 self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
68 let mut z = self.state;
69 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
70 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
71 z ^ (z >> 31)
72 }
73
74 /// Record that `mac` exists, so its vendor is worth guessing again. Returns whether it was
75 /// accepted.
76 ///
77 /// Locally-administered and multicast OUIs are refused rather than stored: no real access
78 /// point uses one, and keeping it would mean either probing addresses that can never hit
79 /// or quietly rewriting it into some other vendor's range at draw time.
80 pub fn observe(&mut self, mac: u64) -> bool {
81 let oui = (mac >> 24) as u32 & 0xFF_FFFF;
82 if oui & 0x03_0000 != 0 {
83 return false;
84 }
85 *self.distinct.entry(oui).or_insert(0) += 1;
86 if self.reservoir.len() < MAX_RESERVOIR {
87 self.reservoir.push(oui);
88 } else {
89 // Replace a random slot: keeps the reservoir bounded while still tracking the
90 // distribution rather than freezing whatever was seen first.
91 let i = (self.next_u64() as usize) % self.reservoir.len();
92 self.reservoir[i] = oui;
93 }
94 true
95 }
96
97 /// Load OUIs from a supplied list, e.g. the IEEE registry or a local WiFi scan. Returns
98 /// how many were **accepted**, which can be fewer than the lines that parsed.
99 ///
100 /// Accepts anything containing `aa:bb:cc` or `aa-bb-cc` or `AABBCC` prefixes, one per
101 /// line, and ignores the rest of each line — so an IEEE `oui.csv` or the output of a scan
102 /// both work without preprocessing.
103 pub fn load_ouis(&mut self, text: &str) -> usize {
104 let mut added = 0;
105 for line in text.lines() {
106 if let Some(oui) = parse_oui(line) {
107 if self.observe((oui as u64) << 24) {
108 added += 1;
109 }
110 }
111 }
112 added
113 }
114
115 /// Distinct OUIs known.
116 pub fn known_ouis(&self) -> usize {
117 self.distinct.len()
118 }
119
120 /// Hit rate so far, as a fraction of probes.
121 pub fn hit_rate(&self) -> f64 {
122 if self.probes == 0 {
123 0.0
124 } else {
125 self.hits as f64 / self.probes as f64
126 }
127 }
128
129 /// Next candidate BSSID.
130 ///
131 /// Never returns a locally-administered or multicast address: those are randomized or
132 /// virtual, the store builder drops them, and Apple will not know them, so probing one is
133 /// a wasted request. Learned OUIs are already clean (see [`Prober::observe`]); only the
134 /// random exploration path needs masking.
135 pub fn next_candidate(&mut self) -> u64 {
136 self.probes += 1;
137 let explore = (self.next_u64() & 0xFF) < EXPLORE_256;
138 let oui = if self.reservoir.is_empty() || explore {
139 ((self.next_u64() as u32) & 0xFF_FFFF) & !0x03_0000
140 } else {
141 let i = (self.next_u64() as usize) % self.reservoir.len();
142 self.reservoir[i]
143 };
144 let suffix = self.next_u64() & 0xFF_FFFF;
145 ((oui as u64) << 24) | suffix
146 }
147
148 /// Emit `n` candidates.
149 pub fn candidates(&mut self, n: usize) -> Vec<u64> {
150 (0..n).map(|_| self.next_candidate()).collect()
151 }
152}
153
154/// Pull a 24-bit OUI off the front of a line, in any of the usual spellings.
155fn parse_oui(line: &str) -> Option<u32> {
156 let t = line.trim();
157 if t.is_empty() || t.starts_with('#') {
158 return None;
159 }
160 // Take the first token that looks like a MAC or OUI.
161 for tok in t.split(|c: char| c.is_whitespace() || c == ',' || c == ';' || c == '"') {
162 let hex: String = tok.chars().filter(|c| c.is_ascii_hexdigit()).collect();
163 let sep_ok = tok.chars().all(|c| c.is_ascii_hexdigit() || c == ':' || c == '-');
164 if sep_ok && hex.len() >= 6 {
165 if let Ok(v) = u32::from_str_radix(&hex[..6], 16) {
166 return Some(v);
167 }
168 }
169 }
170 None
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176 use crate::keys;
177
178 #[test]
179 fn candidates_are_always_usable_addresses() {
180 let mut p = Prober::new(1);
181 for _ in 0..10_000 {
182 let mac = p.next_candidate();
183 assert!(mac < (1u64 << 48), "escaped 48 bits: {mac:#x}");
184 assert!(
185 !keys::is_randomized_mac(mac),
186 "generated a locally-administered or multicast address: {mac:#012x}"
187 );
188 }
189 assert_eq!(p.probes, 10_000);
190 }
191
192 #[test]
193 fn probing_is_deterministic_for_a_given_seed() {
194 let a: Vec<u64> = Prober::new(42).candidates(100);
195 let b: Vec<u64> = Prober::new(42).candidates(100);
196 assert_eq!(a, b);
197 assert_ne!(a, Prober::new(43).candidates(100));
198 }
199
200 #[test]
201 fn learned_ouis_dominate_the_draw() {
202 let mut p = Prober::new(7);
203 // One vendor, seen many times. b8:fb:b3 is globally administered.
204 for _ in 0..1000 {
205 let _ = p.observe(0xB8_FB_B3_00_00_00);
206 }
207 let hits = (0..2000).filter(|_| (p.next_candidate() >> 24) == 0xB8FBB3).count();
208 // Everything except the exploration fraction should land on the known OUI.
209 assert!(hits > 1700, "only {hits}/2000 probes used the learned OUI");
210 assert!(hits < 2000, "exploration never fired; unseen vendors would be unreachable");
211 }
212
213 #[test]
214 fn frequency_weighting_follows_the_observed_distribution() {
215 let mut p = Prober::new(11);
216 // Both globally administered: 0xAA would have the locally-administered bit set and be
217 // refused, which is the point of the next test.
218 for _ in 0..900 {
219 let _ = p.observe(0xA8_00_00_00_00_00);
220 }
221 for _ in 0..100 {
222 let _ = p.observe(0xCC_00_00_00_00_00);
223 }
224 let mut common = 0;
225 let mut rare = 0;
226 for _ in 0..5000 {
227 match p.next_candidate() >> 24 {
228 0xA80000 => common += 1,
229 0xCC0000 => rare += 1,
230 _ => {}
231 }
232 }
233 assert!(common > rare * 4, "weighting is not tracking frequency: {common} vs {rare}");
234 }
235
236 #[test]
237 fn locally_administered_ouis_are_refused_not_rewritten() {
238 let mut p = Prober::new(13);
239 // 0xAA has the locally-administered bit set; 0x01 is multicast.
240 assert!(!p.observe(0xAA_00_00_00_00_00));
241 assert!(!p.observe(0x01_00_00_00_00_00));
242 assert_eq!(p.known_ouis(), 0, "neither is a real access point vendor");
243
244 // And having refused them, it must not silently probe a neighbouring vendor instead.
245 assert!(p.observe(0xA8_00_00_00_00_00));
246 assert_eq!(p.known_ouis(), 1);
247 for _ in 0..500 {
248 let oui = p.next_candidate() >> 24;
249 assert!(oui == 0xA80000 || p.reservoir.len() == 1, "unexpected OUI {oui:#08x}");
250 }
251 }
252
253 #[test]
254 fn with_nothing_learned_it_still_produces_candidates() {
255 let mut p = Prober::new(3);
256 assert_eq!(p.known_ouis(), 0);
257 let c = p.candidates(50);
258 assert_eq!(c.len(), 50);
259 assert_eq!(c.iter().collect::<std::collections::HashSet<_>>().len(), 50, "all distinct");
260 }
261
262 #[test]
263 fn the_reservoir_stays_bounded() {
264 let mut p = Prober::new(5);
265 for i in 0..(MAX_RESERVOIR as u64 + 5000) {
266 // Keep the multicast/local bits clear so every one is accepted.
267 let _ = p.observe((i << 24) & !0x03_0000_0000_0000);
268 }
269 assert!(p.reservoir.len() <= MAX_RESERVOIR);
270 }
271
272 #[test]
273 fn oui_lists_parse_in_the_shapes_people_have_them() {
274 let mut p = Prober::new(9);
275 let added = p.load_ouis(
276 "# comment\n\
277 b8:fb:b3:86:18:8e\n\
278 A8-BB-CC\n\
279 001122\n\
280 MA-L,102233,Some Vendor Inc,Address\n\
281 11:22:33\n\
282 \n\
283 not a mac at all\n",
284 );
285 // Six lines parse; 11:22:33 is multicast and is refused.
286 assert_eq!(added, 4, "expected four accepted OUIs");
287 assert_eq!(p.known_ouis(), 4);
288 }
289
290 #[test]
291 fn oui_parsing_rejects_noise() {
292 assert_eq!(parse_oui(""), None);
293 assert_eq!(parse_oui("# b8:fb:b3"), None);
294 assert_eq!(parse_oui("hello world"), None);
295 assert_eq!(parse_oui("12345"), None, "too short to be an OUI");
296 assert_eq!(parse_oui("b8:fb:b3"), Some(0xB8FBB3));
297 assert_eq!(parse_oui("B8FBB386188E"), Some(0xB8FBB3));
298 }
299
300 #[test]
301 fn hit_rate_reports_what_actually_landed() {
302 let mut p = Prober::new(2);
303 let _ = p.candidates(200);
304 p.hits = 4;
305 assert!((p.hit_rate() - 0.02).abs() < 1e-9);
306 assert_eq!(Prober::new(2).hit_rate(), 0.0, "no probes means no rate, not a division");
307 }
308}