Skip to main content

zigbee_host/
install_code.rs

1//! Zigbee 3.0 install codes and the AES-MMO hash that turns one into a link
2//! key (Zigbee specification B.6; Base Device Behavior 10.1).
3
4use aes::cipher::{Array, BlockCipherEncrypt, KeyInit};
5use aes::Aes128;
6use crc::{Crc, CRC_16_IBM_SDLC};
7use zigbee_primitives::Key;
8
9/// CRC-16/X-25, the install code checksum.
10const CRC: Crc<u16> = Crc::<u16>::new(&CRC_16_IBM_SDLC);
11
12/// An install code was not valid.
13#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
14pub enum InstallCodeError {
15    /// Not 6, 8, 12 or 16 bytes plus a 2-byte CRC.
16    #[error("install code of {0} bytes: expected 8, 10, 14 or 18 including the CRC")]
17    Length(usize),
18    /// The CRC did not match.
19    #[error("install code CRC mismatch")]
20    Crc,
21    /// Not hex.
22    #[error("install code is not hex")]
23    Hex,
24}
25
26/// Parse an install code written as hex (spaces and dashes ignored).
27pub fn parse_hex(text: &str) -> Result<Vec<u8>, InstallCodeError> {
28    let digits: String = text
29        .chars()
30        .filter(|c| !c.is_whitespace() && *c != '-' && *c != ':')
31        .collect();
32    if !digits.len().is_multiple_of(2) {
33        return Err(InstallCodeError::Hex);
34    }
35    (0..digits.len())
36        .step_by(2)
37        .map(|i| {
38            digits
39                .get(i..i + 2)
40                .and_then(|pair| u8::from_str_radix(pair, 16).ok())
41                .ok_or(InstallCodeError::Hex)
42        })
43        .collect()
44}
45
46/// Check an install code (with its trailing little-endian CRC) and derive
47/// the link key a device joins with.
48pub fn link_key(code_with_crc: &[u8]) -> Result<Key, InstallCodeError> {
49    if !matches!(code_with_crc.len(), 8 | 10 | 14 | 18) {
50        return Err(InstallCodeError::Length(code_with_crc.len()));
51    }
52    let (code, crc) = code_with_crc.split_at(code_with_crc.len() - 2);
53    let wanted = match crc {
54        [lo, hi] => u16::from_le_bytes([*lo, *hi]),
55        _ => return Err(InstallCodeError::Length(code_with_crc.len())),
56    };
57    if CRC.checksum(code) != wanted {
58        return Err(InstallCodeError::Crc);
59    }
60    Ok(Key(aes_mmo_hash(code_with_crc)))
61}
62
63/// The Matyas-Meyer-Oseas hash with AES-128, padded as the Zigbee
64/// specification (B.6) requires for messages shorter than 2^16 bits.
65pub fn aes_mmo_hash(message: &[u8]) -> [u8; 16] {
66    let bit_len = (message.len() as u64 * 8) as u16;
67    let mut padded = message.to_vec();
68    padded.push(0x80);
69    while padded.len() % 16 != 14 {
70        padded.push(0x00);
71    }
72    padded.extend_from_slice(&bit_len.to_be_bytes());
73
74    let mut hash = [0u8; 16];
75    for chunk in padded.as_chunks::<16>().0 {
76        let cipher = Aes128::new(&Array::from(hash));
77        let block = *chunk;
78        let mut out = Array::from(block);
79        cipher.encrypt_block(&mut out);
80        for (h, (o, m)) in hash.iter_mut().zip(out.iter().zip(block.iter())) {
81            *h = o ^ m;
82        }
83    }
84    hash
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    #[test]
92    fn derives_the_published_test_vector() {
93        // Zigbee Alliance / Silicon Labs AN1089 example.
94        let code = parse_hex("83FED3407A939723A5C639B26916D505C3B5").unwrap();
95        let key = link_key(&code).unwrap();
96        assert_eq!(key.to_hex(), "66b6900981e1ee3ca4206b6b861c02bb");
97    }
98
99    #[test]
100    fn rejects_bad_codes() {
101        let mut code = parse_hex("83FED3407A939723A5C639B26916D505C3B5").unwrap();
102        code[0] ^= 1;
103        assert_eq!(link_key(&code), Err(InstallCodeError::Crc));
104        assert_eq!(link_key(&[1, 2, 3]), Err(InstallCodeError::Length(3)));
105        assert_eq!(parse_hex("zz"), Err(InstallCodeError::Hex));
106    }
107}