Skip to main content

matter_controller/
network.rs

1//! Operational network credentials for devices being commissioned.
2//!
3//! A Thread network is given to a device as its active operational dataset:
4//! MeshCoP TLVs (one byte of type, one byte of length, the value), as a
5//! border router hands them out. The controller sends the dataset as it is;
6//! it only reads the extended PAN id, which names the network in
7//! `ConnectNetwork` and is the one part of the dataset safe to log.
8
9use crate::Error;
10
11/// The largest dataset Matter's `AddOrUpdateThreadNetwork` takes.
12pub const MAX_DATASET_LEN: usize = 254;
13
14const TLV_EXTENDED_PAN_ID: u8 = 2;
15const TLV_NETWORK_KEY: u8 = 5;
16
17/// Walk the dataset's TLVs, checking each fits, and return the value of the
18/// first with type `wanted`.
19fn find(dataset: &[u8], wanted: u8) -> Result<Option<&[u8]>, Error> {
20    let invalid = |why: &str| Error::Invalid(format!("Thread dataset: {why}"));
21    if dataset.is_empty() || dataset.len() > MAX_DATASET_LEN {
22        return Err(invalid("must be 1 to 254 bytes"));
23    }
24    let mut found = None;
25    let mut rest = dataset;
26    while let [ty, len, tail @ ..] = rest {
27        let len = usize::from(*len);
28        let Some((value, next)) = tail.split_at_checked(len) else {
29            return Err(invalid("a TLV runs past the end"));
30        };
31        if *ty == wanted && found.is_none() {
32            found = Some(value);
33        }
34        rest = next;
35    }
36    if !rest.is_empty() {
37        return Err(invalid("trailing byte"));
38    }
39    Ok(found)
40}
41
42/// The extended PAN id of a Thread active operational dataset, after
43/// checking the dataset is well-formed and carries a network key.
44pub fn thread_extended_pan_id(dataset: &[u8]) -> Result<[u8; 8], Error> {
45    if find(dataset, TLV_NETWORK_KEY)?.is_none_or(|k| k.len() != 16) {
46        return Err(Error::Invalid(
47            "Thread dataset: no 16-byte network key".into(),
48        ));
49    }
50    find(dataset, TLV_EXTENDED_PAN_ID)?
51        .and_then(|v| <[u8; 8]>::try_from(v).ok())
52        .ok_or_else(|| Error::Invalid("Thread dataset: no 8-byte extended PAN id".into()))
53}
54
55/// Parse a dataset given as hex (whitespace ignored), as `ot-ctl dataset
56/// active -x` and a border router's REST API give it.
57pub fn parse_thread_dataset_hex(text: &str) -> Result<Vec<u8>, Error> {
58    let compact: String = text.chars().filter(|c| !c.is_whitespace()).collect();
59    let dataset =
60        hex::decode(&compact).map_err(|_| Error::Invalid("Thread dataset: not hex".into()))?;
61    thread_extended_pan_id(&dataset)?;
62    Ok(dataset)
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    /// An OpenThread active dataset (the documentation's example network).
70    const DATASET: &str = "0e080000000000010000000300001435060004001fffe00208dead00beef00cafe0708fddead00beef000005101234567890abcdef1234567890abcdef030a4f70656e546872656164010212340410a6cb6ea0e9e9bc4d1a7dfe9a6b4fd0190c0402a0f7f8";
71
72    #[test]
73    fn reads_the_extended_pan_id() {
74        let dataset = parse_thread_dataset_hex(DATASET).unwrap();
75        assert_eq!(
76            thread_extended_pan_id(&dataset).unwrap(),
77            [0xde, 0xad, 0x00, 0xbe, 0xef, 0x00, 0xca, 0xfe]
78        );
79    }
80
81    #[test]
82    fn refuses_malformed_datasets() {
83        let good = hex::decode(DATASET).unwrap();
84        assert!(thread_extended_pan_id(&good[..good.len() - 1]).is_err());
85        assert!(thread_extended_pan_id(&[]).is_err());
86        assert!(thread_extended_pan_id(&[2, 8, 1, 2, 3]).is_err());
87        assert!(
88            thread_extended_pan_id(&[2, 8, 0, 0, 0, 0, 0, 0, 0, 0]).is_err(),
89            "no key"
90        );
91        assert!(thread_extended_pan_id(&vec![0u8; 300]).is_err());
92        assert!(parse_thread_dataset_hex("zz").is_err());
93    }
94
95    #[test]
96    fn debug_never_shows_secrets() {
97        let networks = crate::Networks {
98            thread_dataset: Some(hex::decode(DATASET).unwrap()),
99            wifi: Some(crate::WiFi {
100                ssid: b"home".to_vec(),
101                credentials: b"secret".to_vec(),
102            }),
103        };
104        let shown = format!("{networks:?}");
105        assert!(
106            shown.contains("dead00beef00cafe") && shown.contains("home"),
107            "{shown}"
108        );
109        assert!(
110            !shown.contains("secret") && !shown.contains("1234567890abcdef"),
111            "{shown}"
112        );
113    }
114}