Skip to main content

zwave_security/
qr.rs

1//! SmartStart and S2 QR codes (the Z-Wave Alliance's Node Provisioning QR
2//! code format): all decimal digits, `90`, a version, a SHA-1 checksum, the
3//! requested keys, the DSK and then TLV blocks.
4
5use crate::dsk::Dsk;
6use crate::{Error, SecurityClass};
7use sha1::{Digest, Sha1};
8
9/// The shortest valid code: lead-in, version, checksum, keys and the DSK.
10pub const MIN_LEN: usize = 52;
11/// Longest code accepted; real labels are far shorter.
12pub const MAX_LEN: usize = 512;
13
14/// What a QR code says about a node.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct QrCode {
17    /// 0 for an S2-only code, 1 for SmartStart.
18    pub version: u8,
19    /// The keys the node asks for, highest first.
20    pub requested_classes: Vec<SecurityClass>,
21    /// The node's DSK.
22    pub dsk: Dsk,
23    /// Generic and specific device class and installer icon, if present.
24    pub product_type: Option<ProductType>,
25    /// Manufacturer, product and application version, if present.
26    pub product_id: Option<ProductId>,
27    /// Supported protocols bit mask (bit 0 Z-Wave, bit 1 Long Range), if present.
28    pub supported_protocols: Option<u16>,
29    /// The longest interval between SmartStart inclusion requests, in seconds, if present.
30    pub max_inclusion_request_interval: Option<u32>,
31}
32
33/// The QR code's Product Type block.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct ProductType {
36    /// Generic device class.
37    pub generic: u8,
38    /// Specific device class.
39    pub specific: u8,
40    /// Installer icon type.
41    pub icon: u16,
42}
43
44/// The QR code's Product Id block.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct ProductId {
47    /// Manufacturer id.
48    pub manufacturer: u16,
49    /// Product type.
50    pub product_type: u16,
51    /// Product id.
52    pub product: u16,
53    /// Application version (major, minor).
54    pub version: (u8, u8),
55}
56
57impl QrCode {
58    /// Whether the code is a SmartStart code (the node joins without a button press).
59    pub fn is_smartstart(&self) -> bool {
60        self.version == 1
61    }
62}
63
64fn num(s: &[u8], at: usize, digits: usize, max: u32) -> Result<u32, Error> {
65    let part = s.get(at..at + digits).ok_or(Error::Invalid("QR code"))?;
66    let mut v: u32 = 0;
67    for &b in part {
68        if !b.is_ascii_digit() {
69            return Err(Error::Invalid("QR code"));
70        }
71        v = v * 10 + u32::from(b - b'0');
72    }
73    if v > max {
74        return Err(Error::Invalid("QR code"));
75    }
76    Ok(v)
77}
78
79/// Parses a QR code string. Whitespace around it is ignored; the checksum
80/// must match.
81pub fn parse(code: &str) -> Result<QrCode, Error> {
82    let s = code.trim().as_bytes();
83    if s.len() < MIN_LEN || s.len() > MAX_LEN || !s.starts_with(b"90") {
84        return Err(Error::Invalid("QR code"));
85    }
86    if !s.iter().all(u8::is_ascii_digit) {
87        return Err(Error::Invalid("QR code"));
88    }
89    let version = num(s, 2, 2, 1)? as u8;
90    let checksum = num(s, 4, 5, 0xffff)? as u16;
91    let digest = Sha1::digest(&s[9..]);
92    if u16::from_be_bytes([digest[0], digest[1]]) != checksum {
93        return Err(Error::Invalid("QR code checksum"));
94    }
95    let keys = num(s, 9, 3, 0xff)? as u8;
96    let mut dsk = [0u8; 16];
97    for i in 0..8 {
98        let v = num(s, 12 + i * 5, 5, 0xffff)? as u16;
99        dsk[i * 2..i * 2 + 2].copy_from_slice(&v.to_be_bytes());
100    }
101    let mut out = QrCode {
102        version,
103        requested_classes: SecurityClass::from_key_bits(keys),
104        dsk: Dsk(dsk),
105        product_type: None,
106        product_id: None,
107        supported_protocols: None,
108        max_inclusion_request_interval: None,
109    };
110    let mut at = MIN_LEN;
111    while at + 4 <= s.len() {
112        let type_critical = num(s, at, 2, 99)? as u8;
113        let len = num(s, at + 2, 2, 99)? as usize;
114        let data = s
115            .get(at + 4..at + 4 + len)
116            .ok_or(Error::Invalid("QR code TLV"))?;
117        at += 4 + len;
118        let critical = type_critical & 1 == 1;
119        match type_critical >> 1 {
120            0x00 if len == 10 => {
121                let classes = num(data, 0, 5, 0xffff)? as u16;
122                out.product_type = Some(ProductType {
123                    generic: (classes >> 8) as u8,
124                    specific: classes as u8,
125                    icon: num(data, 5, 5, 0xffff)? as u16,
126                });
127            }
128            0x01 if len == 20 => {
129                let ver = num(data, 15, 5, 0xffff)? as u16;
130                out.product_id = Some(ProductId {
131                    manufacturer: num(data, 0, 5, 0xffff)? as u16,
132                    product_type: num(data, 5, 5, 0xffff)? as u16,
133                    product: num(data, 10, 5, 0xffff)? as u16,
134                    version: ((ver >> 8) as u8, ver as u8),
135                });
136            }
137            0x02 if len == 2 => {
138                out.max_inclusion_request_interval = Some(128 * num(data, 0, 2, 99)?);
139            }
140            0x04 if matches!(len, 2 | 3 | 5) => {
141                out.supported_protocols = Some(num(data, 0, len, 0xffff)? as u16);
142            }
143            _ if critical => return Err(Error::Invalid("QR code: unknown critical block")),
144            _ => {}
145        }
146    }
147    if at != s.len() {
148        return Err(Error::Invalid("QR code TLV"));
149    }
150    Ok(out)
151}
152
153/// Builds a QR code string (for tests, simulators and label printing).
154pub fn encode(qr: &QrCode) -> String {
155    let mut body = format!("{:03}", SecurityClass::to_key_bits(&qr.requested_classes));
156    for pair in qr.dsk.0.chunks(2) {
157        body += &format!("{:05}", u16::from_be_bytes([pair[0], pair[1]]));
158    }
159    if let Some(pt) = qr.product_type {
160        let classes = (u16::from(pt.generic) << 8) | u16::from(pt.specific);
161        body += &format!("0010{classes:05}{:05}", pt.icon);
162    }
163    if let Some(pi) = qr.product_id {
164        let ver = (u16::from(pi.version.0) << 8) | u16::from(pi.version.1);
165        body += &format!(
166            "0220{:05}{:05}{:05}{ver:05}",
167            pi.manufacturer, pi.product_type, pi.product
168        );
169    }
170    let digest = Sha1::digest(body.as_bytes());
171    format!(
172        "90{:02}{:05}{body}",
173        qr.version,
174        u16::from_be_bytes([digest[0], digest[1]])
175    )
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    #[test]
183    fn roundtrip_and_checksum() {
184        let qr = QrCode {
185            version: 1,
186            requested_classes: vec![
187                SecurityClass::S2Authenticated,
188                SecurityClass::S2Unauthenticated,
189            ],
190            dsk: "51525-35455-41654-24356-13311-14526-06640-31770"
191                .parse()
192                .unwrap(),
193            product_type: Some(ProductType {
194                generic: 0x10,
195                specific: 0x01,
196                icon: 0x0700,
197            }),
198            product_id: Some(ProductId {
199                manufacturer: 0x0000,
200                product_type: 0x0004,
201                product: 0x0003,
202                version: (1, 2),
203            }),
204            supported_protocols: None,
205            max_inclusion_request_interval: None,
206        };
207        let s = encode(&qr);
208        assert!(s.starts_with("9001"));
209        assert_eq!(parse(&s).unwrap(), qr);
210        // One flipped digit breaks the checksum.
211        let mut bad = s.into_bytes();
212        let i = bad.len() - 1;
213        bad[i] = if bad[i] == b'0' { b'1' } else { b'0' };
214        assert!(parse(std::str::from_utf8(&bad).unwrap()).is_err());
215        assert!(parse("90").is_err());
216        assert!(parse(&"9".repeat(60)).is_err());
217    }
218}