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

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

probe.rs302 lines · 11.3 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 { reservoir: Vec::new(), distinct: HashMap::new(), state: seed, probes: 0, hits: 0 }
57 }
58
59 fn next_u64(&mut self) -> u64 {
60 // splitmix64
61 self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
62 let mut z = self.state;
63 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
64 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
65 z ^ (z >> 31)
66 }
67
68 /// Record that `mac` exists, so its vendor is worth guessing again. Returns whether it was
69 /// accepted.
70 ///
71 /// Locally-administered and multicast OUIs are refused rather than stored: no real access
72 /// point uses one, and keeping it would mean either probing addresses that can never hit
73 /// or quietly rewriting it into some other vendor's range at draw time.
74 pub fn observe(&mut self, mac: u64) -> bool {
75 let oui = (mac >> 24) as u32 & 0xFF_FFFF;
76 if oui & 0x03_0000 != 0 {
77 return false;
78 }
79 *self.distinct.entry(oui).or_insert(0) += 1;
80 if self.reservoir.len() < MAX_RESERVOIR {
81 self.reservoir.push(oui);
82 } else {
83 // Replace a random slot: keeps the reservoir bounded while still tracking the
84 // distribution rather than freezing whatever was seen first.
85 let i = (self.next_u64() as usize) % self.reservoir.len();
86 self.reservoir[i] = oui;
87 }
88 true
89 }
90
91 /// Load OUIs from a supplied list, e.g. the IEEE registry or a local WiFi scan. Returns
92 /// how many were **accepted**, which can be fewer than the lines that parsed.
93 ///
94 /// Accepts anything containing `aa:bb:cc` or `aa-bb-cc` or `AABBCC` prefixes, one per
95 /// line, and ignores the rest of each line — so an IEEE `oui.csv` or the output of a scan
96 /// both work without preprocessing.
97 pub fn load_ouis(&mut self, text: &str) -> usize {
98 let mut added = 0;
99 for line in text.lines() {
100 if let Some(oui) = parse_oui(line) {
101 if self.observe((oui as u64) << 24) {
102 added += 1;
103 }
104 }
105 }
106 added
107 }
108
109 /// Distinct OUIs known.
110 pub fn known_ouis(&self) -> usize {
111 self.distinct.len()
112 }
113
114 /// Hit rate so far, as a fraction of probes.
115 pub fn hit_rate(&self) -> f64 {
116 if self.probes == 0 {
117 0.0
118 } else {
119 self.hits as f64 / self.probes as f64
120 }
121 }
122
123 /// Next candidate BSSID.
124 ///
125 /// Never returns a locally-administered or multicast address: those are randomized or
126 /// virtual, the store builder drops them, and Apple will not know them, so probing one is
127 /// a wasted request. Learned OUIs are already clean (see [`Prober::observe`]); only the
128 /// random exploration path needs masking.
129 pub fn next_candidate(&mut self) -> u64 {
130 self.probes += 1;
131 let explore = (self.next_u64() & 0xFF) < EXPLORE_256;
132 let oui = if self.reservoir.is_empty() || explore {
133 ((self.next_u64() as u32) & 0xFF_FFFF) & !0x03_0000
134 } else {
135 let i = (self.next_u64() as usize) % self.reservoir.len();
136 self.reservoir[i]
137 };
138 let suffix = self.next_u64() & 0xFF_FFFF;
139 ((oui as u64) << 24) | suffix
140 }
141
142 /// Emit `n` candidates.
143 pub fn candidates(&mut self, n: usize) -> Vec<u64> {
144 (0..n).map(|_| self.next_candidate()).collect()
145 }
146}
147
148/// Pull a 24-bit OUI off the front of a line, in any of the usual spellings.
149fn parse_oui(line: &str) -> Option<u32> {
150 let t = line.trim();
151 if t.is_empty() || t.starts_with('#') {
152 return None;
153 }
154 // Take the first token that looks like a MAC or OUI.
155 for tok in t.split(|c: char| c.is_whitespace() || c == ',' || c == ';' || c == '"') {
156 let hex: String = tok.chars().filter(|c| c.is_ascii_hexdigit()).collect();
157 let sep_ok = tok.chars().all(|c| c.is_ascii_hexdigit() || c == ':' || c == '-');
158 if sep_ok && hex.len() >= 6 {
159 if let Ok(v) = u32::from_str_radix(&hex[..6], 16) {
160 return Some(v);
161 }
162 }
163 }
164 None
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170 use crate::keys;
171
172 #[test]
173 fn candidates_are_always_usable_addresses() {
174 let mut p = Prober::new(1);
175 for _ in 0..10_000 {
176 let mac = p.next_candidate();
177 assert!(mac < (1u64 << 48), "escaped 48 bits: {mac:#x}");
178 assert!(
179 !keys::is_randomized_mac(mac),
180 "generated a locally-administered or multicast address: {mac:#012x}"
181 );
182 }
183 assert_eq!(p.probes, 10_000);
184 }
185
186 #[test]
187 fn probing_is_deterministic_for_a_given_seed() {
188 let a: Vec<u64> = Prober::new(42).candidates(100);
189 let b: Vec<u64> = Prober::new(42).candidates(100);
190 assert_eq!(a, b);
191 assert_ne!(a, Prober::new(43).candidates(100));
192 }
193
194 #[test]
195 fn learned_ouis_dominate_the_draw() {
196 let mut p = Prober::new(7);
197 // One vendor, seen many times. b8:fb:b3 is globally administered.
198 for _ in 0..1000 {
199 let _ = p.observe(0xB8_FB_B3_00_00_00);
200 }
201 let hits = (0..2000).filter(|_| (p.next_candidate() >> 24) == 0xB8FBB3).count();
202 // Everything except the exploration fraction should land on the known OUI.
203 assert!(hits > 1700, "only {hits}/2000 probes used the learned OUI");
204 assert!(hits < 2000, "exploration never fired; unseen vendors would be unreachable");
205 }
206
207 #[test]
208 fn frequency_weighting_follows_the_observed_distribution() {
209 let mut p = Prober::new(11);
210 // Both globally administered: 0xAA would have the locally-administered bit set and be
211 // refused, which is the point of the next test.
212 for _ in 0..900 {
213 let _ = p.observe(0xA8_00_00_00_00_00);
214 }
215 for _ in 0..100 {
216 let _ = p.observe(0xCC_00_00_00_00_00);
217 }
218 let mut common = 0;
219 let mut rare = 0;
220 for _ in 0..5000 {
221 match p.next_candidate() >> 24 {
222 0xA80000 => common += 1,
223 0xCC0000 => rare += 1,
224 _ => {}
225 }
226 }
227 assert!(common > rare * 4, "weighting is not tracking frequency: {common} vs {rare}");
228 }
229
230 #[test]
231 fn locally_administered_ouis_are_refused_not_rewritten() {
232 let mut p = Prober::new(13);
233 // 0xAA has the locally-administered bit set; 0x01 is multicast.
234 assert!(!p.observe(0xAA_00_00_00_00_00));
235 assert!(!p.observe(0x01_00_00_00_00_00));
236 assert_eq!(p.known_ouis(), 0, "neither is a real access point vendor");
237
238 // And having refused them, it must not silently probe a neighbouring vendor instead.
239 assert!(p.observe(0xA8_00_00_00_00_00));
240 assert_eq!(p.known_ouis(), 1);
241 for _ in 0..500 {
242 let oui = p.next_candidate() >> 24;
243 assert!(oui == 0xA80000 || p.reservoir.len() == 1, "unexpected OUI {oui:#08x}");
244 }
245 }
246
247 #[test]
248 fn with_nothing_learned_it_still_produces_candidates() {
249 let mut p = Prober::new(3);
250 assert_eq!(p.known_ouis(), 0);
251 let c = p.candidates(50);
252 assert_eq!(c.len(), 50);
253 assert_eq!(c.iter().collect::<std::collections::HashSet<_>>().len(), 50, "all distinct");
254 }
255
256 #[test]
257 fn the_reservoir_stays_bounded() {
258 let mut p = Prober::new(5);
259 for i in 0..(MAX_RESERVOIR as u64 + 5000) {
260 // Keep the multicast/local bits clear so every one is accepted.
261 let _ = p.observe((i << 24) & !0x03_0000_0000_0000);
262 }
263 assert!(p.reservoir.len() <= MAX_RESERVOIR);
264 }
265
266 #[test]
267 fn oui_lists_parse_in_the_shapes_people_have_them() {
268 let mut p = Prober::new(9);
269 let added = p.load_ouis(
270 "# comment\n\
271 b8:fb:b3:86:18:8e\n\
272 A8-BB-CC\n\
273 001122\n\
274 MA-L,102233,Some Vendor Inc,Address\n\
275 11:22:33\n\
276 \n\
277 not a mac at all\n",
278 );
279 // Six lines parse; 11:22:33 is multicast and is refused.
280 assert_eq!(added, 4, "expected four accepted OUIs");
281 assert_eq!(p.known_ouis(), 4);
282 }
283
284 #[test]
285 fn oui_parsing_rejects_noise() {
286 assert_eq!(parse_oui(""), None);
287 assert_eq!(parse_oui("# b8:fb:b3"), None);
288 assert_eq!(parse_oui("hello world"), None);
289 assert_eq!(parse_oui("12345"), None, "too short to be an OUI");
290 assert_eq!(parse_oui("b8:fb:b3"), Some(0xB8FBB3));
291 assert_eq!(parse_oui("B8FBB386188E"), Some(0xB8FBB3));
292 }
293
294 #[test]
295 fn hit_rate_reports_what_actually_landed() {
296 let mut p = Prober::new(2);
297 let _ = p.candidates(200);
298 p.hits = 4;
299 assert!((p.hit_rate() - 0.02).abs() < 1e-9);
300 assert_eq!(Prober::new(2).hit_rate(), 0.0, "no probes means no rate, not a division");
301 }
302}