Skip to main content

webbluetooth_core/
blocklist.rs

1//! The GATT blocklist.
2//!
3//! Some attributes are too dangerous to expose to code that reached the device
4//! through a permission prompt rather than a deliberate install: the HID
5//! service would make a keylogger, an unsigned firmware-update service would
6//! let a page brick or backdoor the device, and the serial number is a
7//! tracking identifier. The Web Bluetooth Community Group maintains the
8//! authoritative list; this crate vendors it and refuses the same attributes.
9//!
10//! The vendored copy is a **snapshot**. Re-run `scripts/update.sh blocklist` to
11//! refresh it — the list grows as new device classes turn out to be
12//! exploitable, and a stale copy silently under-blocks.
13//!
14//! Source: <https://github.com/WebBluetoothCG/registries>
15
16use crate::filter::DataPrefix;
17use crate::uuid::BluetoothUuid;
18use std::collections::HashMap;
19use std::sync::OnceLock;
20
21/// What a blocklist entry forbids.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Blocked {
24    /// Not reachable at all — discovery must not return it.
25    All,
26    /// Readable, but never writable.
27    Writes,
28    /// Writable, but never readable.
29    Reads,
30}
31
32/// The vendored registry file, parsed on first use.
33const SOURCE: &str = include_str!("../spec/gatt-blocklist.txt");
34
35fn table() -> &'static HashMap<BluetoothUuid, Blocked> {
36    static TABLE: OnceLock<HashMap<BluetoothUuid, Blocked>> = OnceLock::new();
37    TABLE.get_or_init(|| parse(SOURCE))
38}
39
40/// Parse the registry's format: one UUID per line, optionally followed by
41/// `exclude-reads` or `exclude-writes`; `#` starts a comment.
42fn parse(source: &str) -> HashMap<BluetoothUuid, Blocked> {
43    let mut out = HashMap::new();
44    for line in source.lines() {
45        let line = line.split('#').next().unwrap_or("").trim();
46        if line.is_empty() {
47            continue;
48        }
49        let mut parts = line.split_whitespace();
50        let Some(uuid) = parts.next() else { continue };
51        let Ok(uuid) = BluetoothUuid::parse(uuid) else {
52            continue;
53        };
54        let blocked = match parts.next() {
55            Some("exclude-writes") => Blocked::Writes,
56            Some("exclude-reads") => Blocked::Reads,
57            _ => Blocked::All,
58        };
59        out.insert(uuid, blocked);
60    }
61    out
62}
63
64/// How `uuid` is restricted, if at all.
65pub fn lookup(uuid: &BluetoothUuid) -> Option<Blocked> {
66    table().get(uuid).copied()
67}
68
69/// Whether `uuid` may not be reached at all.
70pub fn is_blocked(uuid: &BluetoothUuid) -> bool {
71    matches!(lookup(uuid), Some(Blocked::All))
72}
73
74/// Whether reading `uuid` is forbidden.
75pub fn reads_blocked(uuid: &BluetoothUuid) -> bool {
76    matches!(lookup(uuid), Some(Blocked::All) | Some(Blocked::Reads))
77}
78
79/// Whether writing `uuid` is forbidden.
80pub fn writes_blocked(uuid: &BluetoothUuid) -> bool {
81    matches!(lookup(uuid), Some(Blocked::All) | Some(Blocked::Writes))
82}
83
84// ── The manufacturer data blocklist ─────────────────────────────────────────
85//
86// The second registry, and the one easiest to overlook: the GATT blocklist
87// guards attributes you connect to, this one guards what a device shouts into
88// the air. Today it holds a single entry — Apple's iBeacon — because an
89// iBeacon's proximity UUID is a location fix, and reading one off a passing
90// phone would locate its owner without connecting to anything.
91//
92// The registry's format is documented in the registries repository:
93//
94//     manufacturer <company> advdata-<data>/<mask>
95//
96// The specification also prints a parsing algorithm for this file, and its
97// regular expression does not match the file: the expression wants the prefix
98// to start with hex digits, but every entry writes it with a literal
99// `advdata-` tag, which is what the registry documents and what the spec's own
100// `parse an advertising data filter` expects already stripped. Followed
101// literally the list parses as an error — and an error blocks *everything*, so
102// no manufacturer data would reach any caller and every `manufacturerData`
103// filter would throw. That is plainly not the intent, so this parser strips
104// the tag and applies the spec's prefix/mask rule to the rest. See
105// spec/README.md. The failure direction is kept: an entry we cannot parse
106// blocks rather than opens.
107const MANUFACTURER_SOURCE: &str = include_str!("../spec/manufacturer-data-blocklist.txt");
108
109/// Company identifier to the advertising-data prefixes forbidden for it.
110///
111/// `None` in place of the map means the file did not parse. The specification
112/// is explicit that an unreadable list blocks everything rather than nothing,
113/// so the distinction is preserved rather than collapsed into an empty map.
114type ManufacturerTable = Option<HashMap<u16, Vec<DataPrefix>>>;
115
116fn manufacturer_table() -> &'static ManufacturerTable {
117    static TABLE: OnceLock<ManufacturerTable> = OnceLock::new();
118    TABLE.get_or_init(|| parse_manufacturer(MANUFACTURER_SOURCE))
119}
120
121fn parse_manufacturer(source: &str) -> ManufacturerTable {
122    fn hex(text: &str) -> Option<Vec<u8>> {
123        if text.is_empty() || !text.len().is_multiple_of(2) {
124            return None;
125        }
126        (0..text.len())
127            .step_by(2)
128            .map(|i| u8::from_str_radix(&text[i..i + 2], 16).ok())
129            .collect()
130    }
131
132    let mut out: HashMap<u16, Vec<DataPrefix>> = HashMap::new();
133    for line in source.lines() {
134        let line = line.split('#').next().unwrap_or("").trim();
135        if line.is_empty() {
136            continue;
137        }
138        let mut parts = line.split_whitespace();
139        if parts.next() != Some("manufacturer") {
140            return None;
141        }
142        // At most four hexadecimal digits, per the registry.
143        let company = parts
144            .next()
145            .filter(|c| c.len() <= 4)
146            .and_then(|c| u16::from_str_radix(c, 16).ok())?;
147        let (data, mask) = parts.next()?.strip_prefix("advdata-")?.split_once('/')?;
148        let (data, mask) = (hex(data)?, hex(mask)?);
149        let prefix = DataPrefix::with_mask(data, mask).ok()?;
150        out.entry(company).or_default().push(prefix);
151    }
152    Some(out)
153}
154
155/// Whether `data` advertised under `company` must be withheld from callers.
156///
157/// This is the specification's *blocklisted manufacturer data*.
158pub fn manufacturer_data_blocked(company: u16, data: &[u8]) -> bool {
159    let Some(table) = manufacturer_table() else {
160        return true; // An unreadable list blocks everything.
161    };
162    table
163        .get(&company)
164        .is_some_and(|prefixes| prefixes.iter().any(|p| p.matches(data)))
165}
166
167/// Whether a caller may filter on `company` with `prefix`.
168///
169/// This is the specification's *blocklisted manufacturer data filter*, and it
170/// is deliberately not the same test as the one above. A filter is refused
171/// only when it is a *strict subset* of a blocked prefix — when everything it
172/// could ever match is already blocked. A broader filter is allowed through,
173/// because the data it returns gets stripped anyway; refusing it would only
174/// tell the caller what the blocklist contains.
175pub fn manufacturer_filter_blocked(company: u16, prefix: &DataPrefix) -> bool {
176    let Some(table) = manufacturer_table() else {
177        return true;
178    };
179    table
180        .get(&company)
181        .is_some_and(|blocked| blocked.iter().any(|b| prefix.strict_subset_of(b)))
182}
183
184/// Every entry in the vendored snapshot.
185pub fn entries() -> impl Iterator<Item = (&'static BluetoothUuid, Blocked)> {
186    table().iter().map(|(u, b)| (u, *b))
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use crate::uuid::{characteristics, descriptors, services};
193
194    const APPLE: u16 = 0x004C;
195
196    /// The vendored entry: Apple company data whose first byte is `0x02`,
197    /// which is what an iBeacon frame starts with.
198    #[test]
199    fn ibeacon_data_is_blocked_because_it_is_a_location_fix() {
200        assert!(
201            manufacturer_data_blocked(APPLE, &[0x02, 0x15, 0xAB, 0xCD]),
202            "an iBeacon frame must not reach a caller"
203        );
204        assert!(
205            !manufacturer_data_blocked(APPLE, &[0x09, 0x06, 0x03]),
206            "Apple's other advertisements are not blocked wholesale"
207        );
208        assert!(
209            !manufacturer_data_blocked(0x00E0, &[0x02, 0x15]),
210            "another company's 0x02 frame is not an iBeacon"
211        );
212    }
213
214    /// Short data cannot match a longer prefix, and must not panic trying.
215    #[test]
216    fn data_shorter_than_the_prefix_is_not_blocked() {
217        assert!(!manufacturer_data_blocked(APPLE, &[]));
218    }
219
220    /// A filter is refused only when everything it could match is already
221    /// blocked; a broader one is allowed, and simply comes back stripped.
222    #[test]
223    fn only_filters_wholly_inside_the_blocklist_are_refused() {
224        let ibeacon = DataPrefix::new(vec![0x02]);
225        assert!(manufacturer_filter_blocked(APPLE, &ibeacon));
226
227        let narrower = DataPrefix::new(vec![0x02, 0x15]);
228        assert!(
229            manufacturer_filter_blocked(APPLE, &narrower),
230            "narrowing a blocked filter must not get around it"
231        );
232
233        let other = DataPrefix::new(vec![0x09]);
234        assert!(
235            !manufacturer_filter_blocked(APPLE, &other),
236            "a filter for something else is fine"
237        );
238
239        // Masked so loosely that it also matches non-iBeacon frames. It is not
240        // a subset of the blocked prefix, so it is allowed — the data still
241        // comes back stripped of anything that is one.
242        let loose = DataPrefix::with_mask(vec![0x02], vec![0x01]).unwrap();
243        assert!(!manufacturer_filter_blocked(APPLE, &loose));
244    }
245
246    /// An unparseable list must block everything rather than nothing. This is
247    /// the direction that matters: the failure mode of a privacy control is
248    /// silently permitting what it was installed to forbid.
249    #[test]
250    fn an_unreadable_list_blocks_everything() {
251        for bad in [
252            "manufacturer",                              // truncated
253            "manufacturer 4c",                           // no data prefix
254            "manufacturer 4c 02/ff",                     // missing the advdata- tag
255            "manufacturer 4c advdata-02",                // no mask
256            "manufacturer 4c advdata-2/ff",              // odd digit count
257            "manufacturer 4c advdata-02/fg",             // not hex
258            "manufacturer 12345 advdata-02/ff",          // company too wide
259            "uuid 00001812-0000-1000-8000-00805f9b34fb", // wrong file entirely
260        ] {
261            assert!(
262                parse_manufacturer(bad).is_none(),
263                "{bad:?} should have failed to parse"
264            );
265        }
266    }
267
268    #[test]
269    fn the_vendored_list_parses_and_is_not_empty() {
270        // Guards against a fetch that installed an error page, which would
271        // parse as an error and — because that fails closed — block every
272        // company's data on every platform.
273        let table = manufacturer_table()
274            .as_ref()
275            .expect("the vendored manufacturer blocklist must parse");
276        assert!(!table.is_empty());
277    }
278
279    /// Mismatched prefix and mask lengths are a parse failure, not a panic.
280    #[test]
281    fn prefix_and_mask_must_agree_in_length() {
282        assert!(parse_manufacturer("manufacturer 4c advdata-0215/ff").is_none());
283    }
284
285    #[test]
286    fn hid_service_is_fully_blocked() {
287        // Direct access to a keyboard would make any caller a keylogger.
288        let hid = services::HUMAN_INTERFACE_DEVICE;
289        assert!(is_blocked(&hid));
290        assert!(reads_blocked(&hid) && writes_blocked(&hid));
291    }
292
293    #[test]
294    fn firmware_update_services_are_blocked() {
295        for uuid in [
296            "00001530-1212-efde-1523-785feabcd123", // Nordic legacy DFU
297            "f000ffc0-0451-4000-b000-000000000000", // TI over-the-air download
298        ] {
299            assert!(
300                is_blocked(&BluetoothUuid::parse(uuid).unwrap()),
301                "{uuid} not blocked"
302            );
303        }
304    }
305
306    #[test]
307    fn serial_number_is_blocked_because_it_identifies_the_user() {
308        let sn = characteristics::SERIAL_NUMBER_STRING;
309        assert!(is_blocked(&sn));
310    }
311
312    #[test]
313    fn cccd_is_write_blocked_not_read_blocked() {
314        // Writing the Client Characteristic Configuration descriptor by hand
315        // would bypass `start_notifications`, so it is writes-only-blocked.
316        let cccd = descriptors::CLIENT_CHARACTERISTIC_CONFIGURATION;
317        assert_eq!(lookup(&cccd), Some(Blocked::Writes));
318        assert!(writes_blocked(&cccd));
319        assert!(!reads_blocked(&cccd));
320        assert!(!is_blocked(&cccd));
321    }
322
323    #[test]
324    fn ordinary_services_are_not_blocked() {
325        for u in [
326            services::BATTERY_SERVICE,
327            services::HEART_RATE,
328            services::DEVICE_INFORMATION,
329        ] {
330            assert!(lookup(&u).is_none());
331        }
332    }
333
334    #[test]
335    fn snapshot_parsed_completely() {
336        // Every non-comment line in the vendored file became an entry; a silent
337        // parse failure would under-block.
338        let expected = SOURCE
339            .lines()
340            .filter(|l| {
341                let l = l.split('#').next().unwrap_or("").trim();
342                !l.is_empty()
343            })
344            .count();
345        assert_eq!(
346            table().len(),
347            expected,
348            "some blocklist lines failed to parse"
349        );
350        assert!(
351            expected >= 12,
352            "vendored blocklist looks truncated: {expected} entries"
353        );
354    }
355}