Skip to main content

bluetooth_mesh_stack/
network.rs

1//! The network layer (Mesh Protocol 3.4): Network PDUs encrypted and
2//! obfuscated with a network key's material, decoded by trying the keys
3//! whose NID matches, and a bounded message cache so a relayed copy is
4//! handled once.
5
6use std::collections::{HashSet, VecDeque};
7
8use crate::crypto::{self, Key, NetworkMaterial};
9
10/// A network key and what is derived from it.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct NetworkKey {
13    /// The global key index.
14    pub index: u16,
15    /// The key.
16    pub key: Key,
17    /// NID, encryption key and privacy key (k2, master credentials).
18    pub material: NetworkMaterial,
19    /// The Network ID (k3).
20    pub network_id: [u8; 8],
21    /// The beacon key, for secure network beacons.
22    pub beacon_key: Key,
23    /// The identity key, for node identity advertising.
24    pub identity_key: Key,
25}
26
27impl NetworkKey {
28    /// Derives everything from the key.
29    pub fn new(index: u16, key: Key) -> Self {
30        NetworkKey {
31            index,
32            key,
33            material: crypto::k2(&key, &[0]),
34            network_id: crypto::k3(&key),
35            beacon_key: crypto::beacon_key(&key),
36            identity_key: crypto::identity_key(&key),
37        }
38    }
39}
40
41/// A Network PDU, decrypted.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct NetworkPdu {
44    /// Control message (true) or access message.
45    pub ctl: bool,
46    /// Time to live.
47    pub ttl: u8,
48    /// Sequence number (24 bits).
49    pub seq: u32,
50    /// Source address (a unicast address).
51    pub src: u16,
52    /// Destination address.
53    pub dst: u16,
54    /// The lower transport PDU.
55    pub transport: Vec<u8>,
56}
57
58/// The most a Network PDU carries on the advertising bearer.
59pub const MAX_PDU: usize = 29;
60
61/// Which nonce a Network PDU is encrypted with.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63enum Nonce {
64    /// Every PDU on the mesh.
65    Network,
66    /// Proxy Configuration messages, between a proxy client and server only.
67    Proxy,
68}
69
70fn nonce(kind: Nonce, pdu: &NetworkPdu, iv_index: u32) -> [u8; 13] {
71    let mut n = [0u8; 13];
72    match kind {
73        Nonce::Network => n[1] = (u8::from(pdu.ctl) << 7) | (pdu.ttl & 0x7f),
74        Nonce::Proxy => n[0] = 0x03,
75    }
76    n[2..5].copy_from_slice(&pdu.seq.to_be_bytes()[1..]);
77    n[5..7].copy_from_slice(&pdu.src.to_be_bytes());
78    n[9..13].copy_from_slice(&iv_index.to_be_bytes());
79    n
80}
81
82fn pecb(privacy_key: &Key, iv_index: u32, privacy_random: &[u8]) -> [u8; 16] {
83    let mut p = [0u8; 16];
84    p[5..9].copy_from_slice(&iv_index.to_be_bytes());
85    p[9..16].copy_from_slice(&privacy_random[..7]);
86    crypto::e(privacy_key, &p)
87}
88
89/// Errors building a PDU.
90#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
91pub enum Error {
92    /// The transport PDU does not fit.
93    #[error("the transport PDU is {0} octets, more than a Network PDU carries")]
94    TooLong(usize),
95    /// A field is out of range.
96    #[error("{0}")]
97    Invalid(&'static str),
98}
99
100/// Encrypts and obfuscates a Network PDU.
101pub fn encode(net: &NetworkKey, iv_index: u32, pdu: &NetworkPdu) -> Result<Vec<u8>, Error> {
102    encode_with(Nonce::Network, net, iv_index, pdu)
103}
104
105/// Encrypts and obfuscates a Proxy Configuration message (with the proxy
106/// nonce; `pdu` is a control message, TTL 0, to the unassigned address).
107pub fn encode_proxy(net: &NetworkKey, iv_index: u32, pdu: &NetworkPdu) -> Result<Vec<u8>, Error> {
108    encode_with(Nonce::Proxy, net, iv_index, pdu)
109}
110
111fn encode_with(
112    kind: Nonce,
113    net: &NetworkKey,
114    iv_index: u32,
115    pdu: &NetworkPdu,
116) -> Result<Vec<u8>, Error> {
117    let mic = if pdu.ctl { 8 } else { 4 };
118    if 9 + pdu.transport.len() + mic > MAX_PDU {
119        return Err(Error::TooLong(pdu.transport.len()));
120    }
121    if pdu.seq > 0x00ff_ffff || pdu.ttl > 127 || pdu.src == 0 || pdu.src & 0x8000 != 0 {
122        return Err(Error::Invalid("seq, ttl or source address out of range"));
123    }
124    let mut plain = pdu.dst.to_be_bytes().to_vec();
125    plain.extend_from_slice(&pdu.transport);
126    let enc = crypto::ccm_encrypt(
127        &net.material.encryption_key,
128        &nonce(kind, pdu, iv_index),
129        &[],
130        &plain,
131        mic,
132    );
133    let p = pecb(&net.material.privacy_key, iv_index, &enc);
134    let mut header = [0u8; 6];
135    header[0] = (u8::from(pdu.ctl) << 7) | (pdu.ttl & 0x7f);
136    header[1..4].copy_from_slice(&pdu.seq.to_be_bytes()[1..]);
137    header[4..6].copy_from_slice(&pdu.src.to_be_bytes());
138    let mut out = Vec::with_capacity(7 + enc.len());
139    out.push((((iv_index & 1) as u8) << 7) | net.material.nid);
140    out.extend(header.iter().zip(p.iter()).map(|(a, b)| a ^ b));
141    out.extend_from_slice(&enc);
142    Ok(out)
143}
144
145/// Decodes a Network PDU with whichever key opens it. `iv_index` is the
146/// current one; a PDU whose IVI bit differs is tried with the one before
147/// (during an IV update). Returns the key's position, the IV index used and
148/// the PDU.
149pub fn decode(keys: &[NetworkKey], iv_index: u32, data: &[u8]) -> Option<(usize, u32, NetworkPdu)> {
150    decode_with(Nonce::Network, keys, iv_index, data)
151}
152
153/// Decodes a Proxy Configuration message, as [`decode`] does a Network PDU.
154pub fn decode_proxy(
155    keys: &[NetworkKey],
156    iv_index: u32,
157    data: &[u8],
158) -> Option<(usize, u32, NetworkPdu)> {
159    decode_with(Nonce::Proxy, keys, iv_index, data)
160}
161
162fn decode_with(
163    kind: Nonce,
164    keys: &[NetworkKey],
165    iv_index: u32,
166    data: &[u8],
167) -> Option<(usize, u32, NetworkPdu)> {
168    if data.len() < 14 || data.len() > MAX_PDU {
169        return None;
170    }
171    let ivi = data[0] >> 7;
172    let nid = data[0] & 0x7f;
173    let iv = if (iv_index & 1) as u8 == ivi {
174        iv_index
175    } else {
176        iv_index.checked_sub(1)?
177    };
178    for (i, net) in keys
179        .iter()
180        .enumerate()
181        .filter(|(_, k)| k.material.nid == nid)
182    {
183        let p = pecb(&net.material.privacy_key, iv, &data[7..]);
184        let mut h = [0u8; 6];
185        for (j, b) in h.iter_mut().enumerate() {
186            *b = data[1 + j] ^ p[j];
187        }
188        let ctl = h[0] & 0x80 != 0;
189        let mic = if ctl { 8 } else { 4 };
190        if data.len() < 7 + 2 + mic + 1 {
191            continue;
192        }
193        let pdu = NetworkPdu {
194            ctl,
195            ttl: h[0] & 0x7f,
196            seq: u32::from_be_bytes([0, h[1], h[2], h[3]]),
197            src: u16::from_be_bytes([h[4], h[5]]),
198            dst: 0,
199            transport: Vec::new(),
200        };
201        if let Some(plain) = crypto::ccm_decrypt(
202            &net.material.encryption_key,
203            &nonce(kind, &pdu, iv),
204            &[],
205            &data[7..],
206            mic,
207        ) {
208            if plain.len() < 2 {
209                continue;
210            }
211            return Some((
212                i,
213                iv,
214                NetworkPdu {
215                    dst: u16::from_be_bytes([plain[0], plain[1]]),
216                    transport: plain[2..].to_vec(),
217                    ..pdu
218                },
219            ));
220        }
221    }
222    None
223}
224
225/// Recently seen Network PDUs (by source and sequence), bounded.
226pub struct Cache {
227    seen: HashSet<(u16, u32)>,
228    order: VecDeque<(u16, u32)>,
229    limit: usize,
230}
231
232impl Cache {
233    /// A cache of `limit` entries.
234    pub fn new(limit: usize) -> Self {
235        Cache {
236            seen: HashSet::new(),
237            order: VecDeque::new(),
238            limit: limit.max(1),
239        }
240    }
241
242    /// Whether this PDU is new; remembers it.
243    pub fn insert(&mut self, src: u16, seq: u32) -> bool {
244        if !self.seen.insert((src, seq)) {
245            return false;
246        }
247        self.order.push_back((src, seq));
248        if self.order.len() > self.limit {
249            if let Some(old) = self.order.pop_front() {
250                self.seen.remove(&old);
251            }
252        }
253        true
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    fn h(s: &str) -> Vec<u8> {
262        hex::decode(s.replace(' ', "")).unwrap()
263    }
264
265    #[test]
266    fn proxy_nonce_is_its_own() {
267        let net = NetworkKey::new(0, h("7dd7364cd842ad18c17c2b820c84c3d6").try_into().unwrap());
268        let pdu = NetworkPdu {
269            ctl: true,
270            ttl: 0,
271            seq: 1,
272            src: 0x0001,
273            dst: 0x0000,
274            transport: vec![0x00, 0x01],
275        };
276        assert_eq!(
277            nonce(Nonce::Proxy, &pdu, 0x1234_5678).to_vec(),
278            h("03 00 000001 0001 0000 12345678")
279        );
280        let wire = encode_proxy(&net, 0x1234_5678, &pdu).unwrap();
281        let keys = [net];
282        let (_, _, back) = decode_proxy(&keys, 0x1234_5678, &wire).unwrap();
283        assert_eq!(back, pdu);
284        assert!(
285            decode(&keys, 0x1234_5678, &wire).is_none(),
286            "not a mesh PDU"
287        );
288        let mesh = encode(&keys[0], 0x1234_5678, &pdu).unwrap();
289        assert!(
290            decode_proxy(&keys, 0x1234_5678, &mesh).is_none(),
291            "not a proxy PDU"
292        );
293    }
294
295    /// Mesh Protocol, 8.3.1 (Message #1: a control message, relayed by no one).
296    #[test]
297    fn message_1_sample() {
298        let net = NetworkKey::new(0, h("7dd7364cd842ad18c17c2b820c84c3d6").try_into().unwrap());
299        assert_eq!(net.material.nid, 0x68);
300        assert_eq!(
301            net.material.encryption_key.to_vec(),
302            h("0953fa93e7caac9638f58820220a398e")
303        );
304        assert_eq!(
305            net.material.privacy_key.to_vec(),
306            h("8b84eedec100067d670971dd2aa700cf")
307        );
308        let pdu = NetworkPdu {
309            ctl: true,
310            ttl: 0,
311            seq: 1,
312            src: 0x1201,
313            dst: 0xfffd,
314            transport: h("034b50057e400000010000"),
315        };
316        let wire = encode(&net, 0x1234_5678, &pdu).unwrap();
317        assert_eq!(
318            hex::encode(&wire),
319            "68eca487516765b5e5bfdacbaf6cb7fb6bff871f035444ce83a670df"
320        );
321        let (i, iv, back) = decode(std::slice::from_ref(&net), 0x1234_5678, &wire).unwrap();
322        assert_eq!((i, iv), (0, 0x1234_5678));
323        assert_eq!(back, pdu);
324    }
325
326    #[test]
327    fn access_round_trip_iv_update_and_tamper() {
328        let net = NetworkKey::new(1, [9; 16]);
329        let pdu = NetworkPdu {
330            ctl: false,
331            ttl: 5,
332            seq: 0x00ab_cdef,
333            src: 0x0042,
334            dst: 0xc000,
335            transport: vec![0x66; 16],
336        };
337        let wire = encode(&net, 7, &pdu).unwrap();
338        assert_eq!(wire.len(), 29);
339        // The receiver moved on to IV index 8: IVI 1 still opens with 7.
340        let (_, iv, back) = decode(std::slice::from_ref(&net), 8, &wire).unwrap();
341        assert_eq!((iv, back), (7, pdu.clone()));
342        let mut bad = wire.clone();
343        bad[20] ^= 1;
344        assert!(decode(std::slice::from_ref(&net), 7, &bad).is_none());
345        assert!(decode(std::slice::from_ref(&net), 7, &wire[..10]).is_none());
346        assert!(encode(
347            &net,
348            7,
349            &NetworkPdu {
350                transport: vec![0; 17],
351                ..pdu
352            }
353        )
354        .is_err());
355    }
356
357    #[test]
358    fn cache_is_bounded() {
359        let mut c = Cache::new(2);
360        assert!(c.insert(1, 1));
361        assert!(!c.insert(1, 1));
362        assert!(c.insert(1, 2));
363        assert!(c.insert(1, 3));
364        assert!(c.insert(1, 1), "the oldest was forgotten");
365    }
366}