Skip to main content

bluetooth_mesh_stack/
bearer.rs

1//! What Mesh puts on the advertising and GATT bearers: beacons (AD type
2//! Mesh Beacon), PB-ADV (AD type PB-ADV: links and provisioning
3//! transactions), and Proxy PDUs on the Mesh Proxy and Provisioning GATT
4//! services.
5
6use crate::crypto::{self, Key};
7
8/// The FCS of 3GPP TS 27.010 (as in RFCOMM): CRC-8 with polynomial
9/// x^8 + x^2 + x + 1, reflected, initial 0xFF, ones' complemented.
10pub fn fcs(data: &[u8]) -> u8 {
11    const CRC: crc::Crc<u8> = crc::Crc::<u8>::new(&crc::CRC_8_ROHC);
12    0xff ^ CRC.checksum(data)
13}
14
15/// A Mesh beacon.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Beacon {
18    /// A device waiting to be provisioned.
19    Unprovisioned {
20        /// Its Device UUID.
21        uuid: [u8; 16],
22        /// OOB information (where its OOB data is).
23        oob_info: u16,
24        /// Hash of its URI, when it advertises one.
25        uri_hash: Option<[u8; 4]>,
26    },
27    /// A network's key refresh and IV index state.
28    SecureNetwork {
29        /// Key refresh (bit 0), IV update (bit 1).
30        flags: u8,
31        /// The network's ID (k3 of its key).
32        network_id: [u8; 8],
33        /// IV index.
34        iv_index: u32,
35        /// Authentication value.
36        auth: [u8; 8],
37    },
38}
39
40impl Beacon {
41    /// Parses a Mesh Beacon AD structure's data.
42    pub fn parse(d: &[u8]) -> Option<Beacon> {
43        match (d.first()?, d.len()) {
44            (0x00, 19) | (0x00, 23) => Some(Beacon::Unprovisioned {
45                uuid: d[1..17].try_into().ok()?,
46                oob_info: u16::from_be_bytes([d[17], d[18]]),
47                uri_hash: (d.len() == 23).then(|| [d[19], d[20], d[21], d[22]]),
48            }),
49            (0x01, 22) => Some(Beacon::SecureNetwork {
50                flags: d[1],
51                network_id: d[2..10].try_into().ok()?,
52                iv_index: u32::from_be_bytes([d[10], d[11], d[12], d[13]]),
53                auth: d[14..22].try_into().ok()?,
54            }),
55            _ => None,
56        }
57    }
58
59    /// A secure network beacon for a network key, authenticated.
60    pub fn secure_network(
61        beacon_key: &Key,
62        network_id: [u8; 8],
63        flags: u8,
64        iv_index: u32,
65    ) -> Vec<u8> {
66        let mut b = vec![0x01, flags];
67        b.extend_from_slice(&network_id);
68        b.extend_from_slice(&iv_index.to_be_bytes());
69        let a = crypto::cmac(beacon_key, &b[1..]);
70        b.extend_from_slice(&a[..8]);
71        b
72    }
73
74    /// Whether a secure network beacon was made with `beacon_key`.
75    pub fn authenticates(&self, beacon_key: &Key) -> bool {
76        match self {
77            Beacon::SecureNetwork {
78                flags,
79                network_id,
80                iv_index,
81                auth,
82            } => {
83                let mut m = vec![*flags];
84                m.extend_from_slice(network_id);
85                m.extend_from_slice(&iv_index.to_be_bytes());
86                crypto::cmac(beacon_key, &m)[..8] == auth[..]
87            }
88            Beacon::Unprovisioned { .. } => false,
89        }
90    }
91}
92
93/// A Generic Provisioning PDU, as carried in PB-ADV.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum Generic {
96    /// The first segment of a provisioning PDU.
97    Start {
98        /// The last segment's index.
99        seg_n: u8,
100        /// The whole PDU's length.
101        total: u16,
102        /// FCS of the whole PDU.
103        fcs: u8,
104        /// The first segment's data.
105        data: Vec<u8>,
106    },
107    /// The transaction was received whole.
108    Ack,
109    /// A later segment.
110    Continuation {
111        /// Its index.
112        index: u8,
113        /// Its data.
114        data: Vec<u8>,
115    },
116    /// Link Open, with the device's UUID.
117    LinkOpen([u8; 16]),
118    /// Link Ack.
119    LinkAck,
120    /// Link Close, with the reason (0 success, 1 timeout, 2 fail).
121    LinkClose(u8),
122}
123
124/// One PB-ADV PDU: link, transaction number and Generic Provisioning PDU.
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct PbAdv {
127    /// Link ID.
128    pub link: u32,
129    /// Transaction number.
130    pub transaction: u8,
131    /// The Generic Provisioning PDU.
132    pub pdu: Generic,
133}
134
135/// Data in a Transaction Start on PB-ADV.
136const START_DATA: usize = 20;
137/// Data in a Transaction Continuation on PB-ADV.
138const CONTINUATION_DATA: usize = 23;
139
140impl PbAdv {
141    /// Parses a PB-ADV AD structure's data.
142    pub fn parse(d: &[u8]) -> Option<PbAdv> {
143        if d.len() < 6 {
144            return None;
145        }
146        let link = u32::from_be_bytes([d[0], d[1], d[2], d[3]]);
147        let transaction = d[4];
148        let g = &d[5..];
149        let pdu = match g[0] & 0b11 {
150            0b00 => {
151                if g.len() < 5 {
152                    return None;
153                }
154                Generic::Start {
155                    seg_n: g[0] >> 2,
156                    total: u16::from_be_bytes([g[1], g[2]]),
157                    fcs: g[3],
158                    data: g[4..].to_vec(),
159                }
160            }
161            0b01 => Generic::Ack,
162            0b10 => Generic::Continuation {
163                index: g[0] >> 2,
164                data: g[1..].to_vec(),
165            },
166            _ => match (g[0] >> 2, g.len()) {
167                (0x00, 17) => Generic::LinkOpen(g[1..17].try_into().ok()?),
168                (0x01, 1) => Generic::LinkAck,
169                (0x02, 2) => Generic::LinkClose(g[1]),
170                _ => return None,
171            },
172        };
173        Some(PbAdv {
174            link,
175            transaction,
176            pdu,
177        })
178    }
179
180    /// The AD structure data.
181    pub fn bytes(&self) -> Vec<u8> {
182        let mut b = self.link.to_be_bytes().to_vec();
183        b.push(self.transaction);
184        match &self.pdu {
185            Generic::Start {
186                seg_n,
187                total,
188                fcs,
189                data,
190            } => {
191                b.push(seg_n << 2);
192                b.extend_from_slice(&total.to_be_bytes());
193                b.push(*fcs);
194                b.extend_from_slice(data);
195            }
196            Generic::Ack => b.push(0x01),
197            Generic::Continuation { index, data } => {
198                b.push((index << 2) | 0b10);
199                b.extend_from_slice(data);
200            }
201            Generic::LinkOpen(uuid) => {
202                b.push(0x03);
203                b.extend_from_slice(uuid);
204            }
205            Generic::LinkAck => b.push((0x01 << 2) | 0b11),
206            Generic::LinkClose(r) => {
207                b.push((0x02 << 2) | 0b11);
208                b.push(*r);
209            }
210        }
211        b
212    }
213
214    /// A provisioning PDU as the segments of one transaction.
215    pub fn transaction(link: u32, transaction: u8, pdu: &[u8]) -> Vec<PbAdv> {
216        let first = &pdu[..pdu.len().min(START_DATA)];
217        let rest = pdu.get(START_DATA..).unwrap_or(&[]);
218        let conts: Vec<&[u8]> = rest.chunks(CONTINUATION_DATA).collect();
219        let mut out = vec![PbAdv {
220            link,
221            transaction,
222            pdu: Generic::Start {
223                seg_n: conts.len() as u8,
224                total: pdu.len() as u16,
225                fcs: fcs(pdu),
226                data: first.to_vec(),
227            },
228        }];
229        out.extend(conts.into_iter().enumerate().map(|(i, c)| PbAdv {
230            link,
231            transaction,
232            pdu: Generic::Continuation {
233                index: (i + 1) as u8,
234                data: c.to_vec(),
235            },
236        }));
237        out
238    }
239}
240
241/// A transaction being received: (number, last segment, total, FCS, segments).
242type Partial = (u8, u8, u16, u8, Vec<Option<Vec<u8>>>);
243
244/// Reassembles one PB-ADV transaction.
245#[derive(Default)]
246pub struct TransactionRx {
247    current: Option<Partial>,
248}
249
250impl TransactionRx {
251    /// Adds a segment; the whole provisioning PDU once complete and its FCS checks.
252    pub fn add(&mut self, p: &PbAdv) -> Option<Vec<u8>> {
253        match &p.pdu {
254            Generic::Start {
255                seg_n,
256                total,
257                fcs: f,
258                data,
259            } => {
260                if *seg_n > 63 {
261                    return None;
262                }
263                let mut parts = vec![None; usize::from(*seg_n) + 1];
264                parts[0] = Some(data.clone());
265                self.current = Some((p.transaction, *seg_n, *total, *f, parts));
266            }
267            Generic::Continuation { index, data } => {
268                let (t, n, ..) = self.current.as_mut()?;
269                if *t != p.transaction || index > n {
270                    return None;
271                }
272                self.current.as_mut()?.4[usize::from(*index)] = Some(data.clone());
273            }
274            _ => return None,
275        }
276        let (_, _, total, f, parts) = self.current.as_ref()?;
277        if !parts.iter().all(Option::is_some) {
278            return None;
279        }
280        let pdu: Vec<u8> = parts.iter().flatten().flatten().copied().collect();
281        let ok = pdu.len() == usize::from(*total) && fcs(&pdu) == *f;
282        self.current = None;
283        ok.then_some(pdu)
284    }
285}
286
287/// Proxy PDU message types.
288pub mod proxy {
289    /// A Network PDU.
290    pub const NETWORK: u8 = 0x00;
291    /// A Mesh Beacon.
292    pub const BEACON: u8 = 0x01;
293    /// Proxy Configuration.
294    pub const CONFIGURATION: u8 = 0x02;
295    /// A Provisioning PDU.
296    pub const PROVISIONING: u8 = 0x03;
297}
298
299/// Splits a message into Proxy PDUs for an ATT MTU (each write carries MTU - 3).
300pub fn proxy_segments(kind: u8, msg: &[u8], mtu: u16) -> Vec<Vec<u8>> {
301    let room = usize::from(mtu.saturating_sub(3)).max(20) - 1;
302    if msg.len() <= room {
303        let mut p = vec![kind & 0x3f];
304        p.extend_from_slice(msg);
305        return vec![p];
306    }
307    let chunks: Vec<&[u8]> = msg.chunks(room).collect();
308    let last = chunks.len() - 1;
309    chunks
310        .into_iter()
311        .enumerate()
312        .map(|(i, c)| {
313            let sar = match i {
314                0 => 0b01,
315                i if i == last => 0b11,
316                _ => 0b10,
317            };
318            let mut p = vec![(sar << 6) | (kind & 0x3f)];
319            p.extend_from_slice(c);
320            p
321        })
322        .collect()
323}
324
325/// Reassembles Proxy PDUs into (type, message).
326#[derive(Default)]
327pub struct ProxyRx {
328    partial: Option<(u8, Vec<u8>)>,
329}
330
331/// The largest proxy message reassembled (a provisioning PDU or network PDU is far smaller).
332const MAX_PROXY: usize = 512;
333
334impl ProxyRx {
335    /// Adds one Proxy PDU; a whole message when complete.
336    pub fn add(&mut self, p: &[u8]) -> Option<(u8, Vec<u8>)> {
337        let (&h, data) = p.split_first()?;
338        let (sar, kind) = (h >> 6, h & 0x3f);
339        match sar {
340            0b00 => {
341                self.partial = None;
342                Some((kind, data.to_vec()))
343            }
344            0b01 => {
345                self.partial = Some((kind, data.to_vec()));
346                None
347            }
348            _ => {
349                let (k, buf) = self.partial.as_mut()?;
350                if *k != kind || buf.len() + data.len() > MAX_PROXY {
351                    self.partial = None;
352                    return None;
353                }
354                buf.extend_from_slice(data);
355                if sar == 0b11 {
356                    self.partial.take()
357                } else {
358                    None
359                }
360            }
361        }
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368
369    #[test]
370    fn fcs_matches_rfcomm() {
371        // RFCOMM SABM on DLCI 0: address 0x03, control 0x3f, length 0x01;
372        // the FCS of a SABM covers all three, and is 0x1c.
373        assert_eq!(fcs(&[0x03, 0x3f, 0x01]), 0x1c);
374    }
375
376    #[test]
377    fn beacons_parse_and_authenticate() {
378        let k = crypto::beacon_key(&[0x11; 16]);
379        let b = Beacon::secure_network(&k, [1, 2, 3, 4, 5, 6, 7, 8], 0x02, 0x12345678);
380        let parsed = Beacon::parse(&b).unwrap();
381        assert!(parsed.authenticates(&k));
382        assert!(!parsed.authenticates(&[0; 16]));
383        let mut u = vec![0x00];
384        u.extend([0xaa; 16]);
385        u.extend([0x40, 0x00]);
386        assert!(matches!(
387            Beacon::parse(&u),
388            Some(Beacon::Unprovisioned {
389                oob_info: 0x4000,
390                uri_hash: None,
391                ..
392            })
393        ));
394        assert!(Beacon::parse(&[0x01, 0]).is_none());
395    }
396
397    #[test]
398    fn pb_adv_transactions_round_trip() {
399        let pdu: Vec<u8> = (0..65u8).collect(); // a Public Key PDU's size
400        let segs = PbAdv::transaction(0xdeadbeef, 0x80, &pdu);
401        assert_eq!(segs.len(), 3); // 20 + 23 + 22 octets
402        let mut rx = TransactionRx::default();
403        let mut whole = None;
404        // Continuations out of order after their start.
405        for s in segs.iter().take(1).chain(segs.iter().skip(1).rev()) {
406            let back = PbAdv::parse(&s.bytes()).unwrap();
407            assert_eq!(&back, s);
408            if let Some(p) = rx.add(&back) {
409                whole = Some(p);
410            }
411        }
412        assert_eq!(whole, Some(pdu.clone()));
413        let mut bad = PbAdv::transaction(1, 0, &pdu);
414        if let Generic::Start { fcs, .. } = &mut bad[0].pdu {
415            *fcs ^= 1;
416        }
417        let mut rx = TransactionRx::default();
418        assert!(
419            bad.iter().filter_map(|s| rx.add(s)).next().is_none(),
420            "a bad FCS is dropped"
421        );
422        for g in [
423            Generic::LinkOpen([7; 16]),
424            Generic::LinkAck,
425            Generic::LinkClose(1),
426            Generic::Ack,
427        ] {
428            let p = PbAdv {
429                link: 9,
430                transaction: 0,
431                pdu: g,
432            };
433            assert_eq!(PbAdv::parse(&p.bytes()), Some(p));
434        }
435    }
436
437    #[test]
438    fn proxy_sar_round_trip() {
439        let msg: Vec<u8> = (0..100u8).collect();
440        let mut rx = ProxyRx::default();
441        let out: Vec<_> = proxy_segments(proxy::PROVISIONING, &msg, 23)
442            .iter()
443            .filter_map(|p| rx.add(p))
444            .collect();
445        assert_eq!(out, vec![(proxy::PROVISIONING, msg)]);
446        assert_eq!(rx.add(&[0x00, 1, 2]), Some((proxy::NETWORK, vec![1, 2])));
447        assert_eq!(
448            rx.add(&[0x80, 1]),
449            None,
450            "a continuation without a start is dropped"
451        );
452    }
453}