Skip to main content

zwave_security/
s0.rs

1//! Security 0: nonces and Message Encapsulation.
2//!
3//! S0 frames are AES-128-OFB encrypted and authenticated with an 8-byte
4//! AES-CBC-MAC. Every frame needs a fresh 8-byte nonce from the receiver
5//! (Nonce Get, Nonce Report), so a sender asks first; the IV is the sender's
6//! nonce followed by the receiver's.
7
8use crate::crypto::{aes128_ecb, aes128_ofb, cbc_mac};
9use crate::{random_bytes, Error, NetworkKey};
10use std::collections::HashMap;
11use std::time::{Duration, Instant};
12
13/// The Security (S0) command class id.
14pub const CC_SECURITY: u8 = 0x98;
15
16/// Security 0 command ids.
17pub mod cmd {
18    /// Commands Supported Get.
19    pub const COMMANDS_SUPPORTED_GET: u8 = 0x02;
20    /// Commands Supported Report.
21    pub const COMMANDS_SUPPORTED_REPORT: u8 = 0x03;
22    /// Scheme Get.
23    pub const SCHEME_GET: u8 = 0x04;
24    /// Scheme Report.
25    pub const SCHEME_REPORT: u8 = 0x05;
26    /// Network Key Set.
27    pub const NETWORK_KEY_SET: u8 = 0x06;
28    /// Network Key Verify.
29    pub const NETWORK_KEY_VERIFY: u8 = 0x07;
30    /// Scheme Inherit.
31    pub const SCHEME_INHERIT: u8 = 0x08;
32    /// Nonce Get.
33    pub const NONCE_GET: u8 = 0x40;
34    /// Nonce Report.
35    pub const NONCE_REPORT: u8 = 0x80;
36    /// Message Encapsulation.
37    pub const MESSAGE_ENCAPSULATION: u8 = 0x81;
38    /// Message Encapsulation, asking for a nonce in the same breath.
39    pub const MESSAGE_ENCAPSULATION_NONCE_GET: u8 = 0xc1;
40}
41
42/// How long a nonce we issued stays valid.
43pub const NONCE_LIFETIME: Duration = Duration::from_secs(10);
44/// Most nonces we keep outstanding at once.
45pub const MAX_OWN_NONCES: usize = 64;
46/// The longest S0 payload in one frame; longer commands are split in two.
47pub const MAX_PAYLOAD: usize = 26;
48
49/// The keys derived from one S0 network key.
50#[derive(Clone, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
51struct Keys {
52    auth: [u8; 16],
53    enc: [u8; 16],
54}
55
56impl Keys {
57    fn new(network_key: &NetworkKey) -> Self {
58        Keys {
59            auth: aes128_ecb(network_key, &[0x55; 16]),
60            enc: aes128_ecb(network_key, &[0xaa; 16]),
61        }
62    }
63}
64
65/// The well-known all-zero key S0 uses while handing over the real one.
66pub const TEMP_KEY: NetworkKey = [0; 16];
67
68/// A decapsulated S0 frame.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum S0Payload {
71    /// A complete command (command class id first).
72    Complete(Vec<u8>),
73    /// The first half of a two-frame command; the second follows.
74    FirstHalf,
75}
76
77/// Security 0 state for one node.
78pub struct S0Manager {
79    own_node: u16,
80    keys: Keys,
81    temp: Keys,
82    own_nonces: HashMap<u8, ([u8; 8], u16, Instant)>,
83    peer_nonces: HashMap<u16, ([u8; 8], Instant)>,
84    halves: HashMap<(u16, u8), (Vec<u8>, Instant)>,
85    seq: u8,
86}
87
88impl std::fmt::Debug for S0Manager {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("S0Manager")
91            .field("own_node", &self.own_node)
92            .finish()
93    }
94}
95
96/// One frame of an outgoing encapsulation and whether it asks for the next nonce.
97fn frame_control(sequenced: bool, second: bool, counter: u8) -> u8 {
98    (if sequenced { 0x10 } else { 0 }) | (if second { 0x20 } else { 0 }) | (counter & 0x0f)
99}
100
101impl S0Manager {
102    /// A manager for `own_node` with the network key.
103    pub fn new(own_node: u16, network_key: &NetworkKey) -> Self {
104        S0Manager {
105            own_node,
106            keys: Keys::new(network_key),
107            temp: Keys::new(&TEMP_KEY),
108            own_nonces: HashMap::new(),
109            peer_nonces: HashMap::new(),
110            halves: HashMap::new(),
111            seq: 0,
112        }
113    }
114
115    /// Changes the own node id (after being included).
116    pub fn set_own_node(&mut self, own_node: u16) {
117        self.own_node = own_node;
118    }
119
120    /// Replaces the network key (a node receiving Network Key Set).
121    pub fn set_network_key(&mut self, key: &NetworkKey) {
122        self.keys = Keys::new(key);
123    }
124
125    fn expire(&mut self, now: Instant) {
126        self.own_nonces
127            .retain(|_, (_, _, t)| now.duration_since(*t) < NONCE_LIFETIME);
128        self.peer_nonces
129            .retain(|_, (_, t)| now.duration_since(*t) < NONCE_LIFETIME);
130        self.halves
131            .retain(|_, (_, t)| now.duration_since(*t) < NONCE_LIFETIME);
132    }
133
134    /// A Nonce Get command.
135    pub fn nonce_get() -> Vec<u8> {
136        vec![CC_SECURITY, cmd::NONCE_GET]
137    }
138
139    /// Issues a nonce for `peer` and returns the Nonce Report carrying it.
140    pub fn nonce_report(&mut self, peer: u16) -> Result<Vec<u8>, Error> {
141        let now = Instant::now();
142        self.expire(now);
143        if self.own_nonces.len() >= MAX_OWN_NONCES {
144            // Drop the oldest; a flood of Nonce Gets must not grow memory.
145            if let Some(oldest) = self
146                .own_nonces
147                .iter()
148                .min_by_key(|(_, (_, _, t))| *t)
149                .map(|(k, _)| *k)
150            {
151                self.own_nonces.remove(&oldest);
152            }
153        }
154        let nonce = loop {
155            let n = random_bytes::<8>()?;
156            // The first byte is the nonce id and must be unique among live nonces.
157            if !self.own_nonces.contains_key(&n[0]) {
158                break n;
159            }
160        };
161        self.own_nonces.insert(nonce[0], (nonce, peer, now));
162        let mut v = vec![CC_SECURITY, cmd::NONCE_REPORT];
163        v.extend_from_slice(&nonce);
164        Ok(v)
165    }
166
167    /// Stores the nonce from a peer's Nonce Report (`frame` starts at `0x98 0x80`).
168    pub fn handle_nonce_report(&mut self, peer: u16, frame: &[u8]) -> Result<(), Error> {
169        if frame.len() != 10 || frame[0] != CC_SECURITY || frame[1] != cmd::NONCE_REPORT {
170            return Err(Error::Malformed("not an S0 nonce report"));
171        }
172        let n: [u8; 8] = frame[2..10].try_into().expect("8 bytes");
173        self.peer_nonces.insert(peer, (n, Instant::now()));
174        Ok(())
175    }
176
177    /// Whether we hold a live nonce from `peer`.
178    pub fn has_peer_nonce(&self, peer: u16) -> bool {
179        self.peer_nonces
180            .get(&peer)
181            .is_some_and(|(_, t)| t.elapsed() < NONCE_LIFETIME)
182    }
183
184    /// Encapsulates `command` for `peer` with its stored nonce (consumed).
185    ///
186    /// A command longer than [`MAX_PAYLOAD`] needs two frames; this returns
187    /// the first and the caller sends it, fetches a new nonce and calls
188    /// again with the rest via [`encapsulate_part`](Self::encapsulate_part).
189    pub fn encapsulate(
190        &mut self,
191        peer: u16,
192        command: &[u8],
193        temp_key: bool,
194    ) -> Result<Vec<u8>, Error> {
195        if command.len() > MAX_PAYLOAD {
196            return Err(Error::Malformed("S0 command too long for one frame"));
197        }
198        self.encapsulate_part(
199            peer,
200            command,
201            frame_control(false, false, 0),
202            temp_key,
203            false,
204        )
205    }
206
207    /// Splits a long command into the two halves S0 sends in sequence.
208    pub fn split(&mut self, command: &[u8]) -> Option<[(Vec<u8>, u8); 2]> {
209        if command.len() <= MAX_PAYLOAD || command.len() > 2 * MAX_PAYLOAD {
210            return None;
211        }
212        self.seq = (self.seq + 1) & 0x0f;
213        let (a, b) = command.split_at(MAX_PAYLOAD);
214        Some([
215            (a.to_vec(), frame_control(true, false, self.seq)),
216            (b.to_vec(), frame_control(true, true, self.seq)),
217        ])
218    }
219
220    /// Encapsulates one part with an explicit frame control byte. `nonce_get`
221    /// asks the receiver for its next nonce in the same frame.
222    pub fn encapsulate_part(
223        &mut self,
224        peer: u16,
225        part: &[u8],
226        control: u8,
227        temp_key: bool,
228        nonce_get: bool,
229    ) -> Result<Vec<u8>, Error> {
230        let now = Instant::now();
231        self.expire(now);
232        let (receiver_nonce, _) = self.peer_nonces.remove(&peer).ok_or(Error::NoNonce)?;
233        let sender_nonce = random_bytes::<8>()?;
234        let keys = if temp_key { &self.temp } else { &self.keys };
235        let mut iv = [0u8; 16];
236        iv[..8].copy_from_slice(&sender_nonce);
237        iv[8..].copy_from_slice(&receiver_nonce);
238        let mut plain = Vec::with_capacity(part.len() + 1);
239        plain.push(control);
240        plain.extend_from_slice(part);
241        let ct = aes128_ofb(&keys.enc, &iv, &plain);
242        let command = if nonce_get {
243            cmd::MESSAGE_ENCAPSULATION_NONCE_GET
244        } else {
245            cmd::MESSAGE_ENCAPSULATION
246        };
247        let mac = Self::mac(&keys.auth, &iv, command, self.own_node, peer, &ct);
248        let mut out = Vec::with_capacity(2 + 8 + ct.len() + 9);
249        out.extend_from_slice(&[CC_SECURITY, command]);
250        out.extend_from_slice(&sender_nonce);
251        out.extend_from_slice(&ct);
252        out.push(receiver_nonce[0]);
253        out.extend_from_slice(&mac);
254        Ok(out)
255    }
256
257    fn mac(
258        auth: &[u8; 16],
259        iv: &[u8; 16],
260        command: u8,
261        sender: u16,
262        receiver: u16,
263        ct: &[u8],
264    ) -> [u8; 8] {
265        let mut data = Vec::with_capacity(20 + ct.len());
266        data.extend_from_slice(iv);
267        data.extend_from_slice(&[command, sender as u8, receiver as u8, ct.len() as u8]);
268        data.extend_from_slice(ct);
269        let full = cbc_mac(auth, &data);
270        full[..8].try_into().expect("8 bytes")
271    }
272
273    /// Decapsulates a frame from `peer` (`frame` starts at `0x98 0x81` or `0x98 0xC1`).
274    ///
275    /// The nonce it names must be one we issued to `peer` and still live; it
276    /// is consumed either way.
277    pub fn decapsulate(
278        &mut self,
279        peer: u16,
280        frame: &[u8],
281        temp_key: bool,
282    ) -> Result<S0Payload, Error> {
283        if frame.len() < 2 + 8 + 1 + 1 + 8
284            || frame[0] != CC_SECURITY
285            || !matches!(
286                frame[1],
287                cmd::MESSAGE_ENCAPSULATION | cmd::MESSAGE_ENCAPSULATION_NONCE_GET
288            )
289        {
290            return Err(Error::Malformed("not an S0 encapsulation"));
291        }
292        let now = Instant::now();
293        self.expire(now);
294        let sender_nonce = &frame[2..10];
295        let ct = &frame[10..frame.len() - 9];
296        let nonce_id = frame[frame.len() - 9];
297        let mac = &frame[frame.len() - 8..];
298        let (receiver_nonce, issued_to, _) =
299            self.own_nonces.remove(&nonce_id).ok_or(Error::NoNonce)?;
300        if issued_to != peer {
301            return Err(Error::NoNonce);
302        }
303        let keys = if temp_key { &self.temp } else { &self.keys };
304        let mut iv = [0u8; 16];
305        iv[..8].copy_from_slice(sender_nonce);
306        iv[8..].copy_from_slice(&receiver_nonce);
307        let want = Self::mac(&keys.auth, &iv, frame[1], peer, self.own_node, ct);
308        if want.as_slice() != mac {
309            return Err(Error::DecryptFailed);
310        }
311        let plain = aes128_ofb(&keys.enc, &iv, ct);
312        let control = plain[0];
313        let body = plain[1..].to_vec();
314        let sequenced = control & 0x10 != 0;
315        let second = control & 0x20 != 0;
316        let counter = control & 0x0f;
317        if !sequenced {
318            return Ok(S0Payload::Complete(body));
319        }
320        if !second {
321            self.halves.insert((peer, counter), (body, now));
322            return Ok(S0Payload::FirstHalf);
323        }
324        let (mut first, _) = self
325            .halves
326            .remove(&(peer, counter))
327            .ok_or(Error::Malformed("S0 second half without first"))?;
328        first.extend_from_slice(&body);
329        Ok(S0Payload::Complete(first))
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    #[test]
338    fn roundtrip() {
339        let key = [7u8; 16];
340        let mut c = S0Manager::new(1, &key);
341        let mut n = S0Manager::new(9, &key);
342        assert_eq!(c.encapsulate(9, &[0x25, 0x02], false), Err(Error::NoNonce));
343        let report = n.nonce_report(1).unwrap();
344        c.handle_nonce_report(9, &report).unwrap();
345        let f = c.encapsulate(9, &[0x25, 0x01, 0xff], false).unwrap();
346        assert_eq!(
347            n.decapsulate(1, &f, false).unwrap(),
348            S0Payload::Complete(vec![0x25, 0x01, 0xff])
349        );
350        // The nonce was single-use.
351        assert_eq!(n.decapsulate(1, &f, false), Err(Error::NoNonce));
352    }
353
354    #[test]
355    fn mac_and_key_are_checked() {
356        let mut c = S0Manager::new(1, &[7; 16]);
357        let mut n = S0Manager::new(9, &[8; 16]);
358        let r = n.nonce_report(1).unwrap();
359        c.handle_nonce_report(9, &r).unwrap();
360        let f = c.encapsulate(9, &[0x25, 0x02], false).unwrap();
361        assert_eq!(n.decapsulate(1, &f, false), Err(Error::DecryptFailed));
362        // Temporary key during key handover.
363        let r = n.nonce_report(1).unwrap();
364        c.handle_nonce_report(9, &r).unwrap();
365        let mut set = vec![CC_SECURITY, cmd::NETWORK_KEY_SET];
366        set.extend_from_slice(&[7; 16]);
367        let f = c.encapsulate(9, &set, true).unwrap();
368        assert_eq!(
369            n.decapsulate(1, &f, true).unwrap(),
370            S0Payload::Complete(set)
371        );
372    }
373
374    #[test]
375    fn nonce_from_another_peer_is_refused() {
376        let key = [7u8; 16];
377        let mut c = S0Manager::new(1, &key);
378        let mut n = S0Manager::new(9, &key);
379        let r = n.nonce_report(2).unwrap();
380        c.handle_nonce_report(9, &r).unwrap();
381        let f = c.encapsulate(9, &[0x20, 0x02], false).unwrap();
382        assert_eq!(n.decapsulate(1, &f, false), Err(Error::NoNonce));
383    }
384
385    #[test]
386    fn two_part_commands() {
387        let key = [7u8; 16];
388        let mut c = S0Manager::new(1, &key);
389        let mut n = S0Manager::new(9, &key);
390        let long: Vec<u8> = (0..40).collect();
391        let parts = c.split(&long).unwrap();
392        for (i, (part, control)) in parts.iter().enumerate() {
393            let r = n.nonce_report(1).unwrap();
394            c.handle_nonce_report(9, &r).unwrap();
395            let f = c
396                .encapsulate_part(9, part, *control, false, i == 0)
397                .unwrap();
398            let out = n.decapsulate(1, &f, false).unwrap();
399            if i == 0 {
400                assert_eq!(out, S0Payload::FirstHalf);
401            } else {
402                assert_eq!(out, S0Payload::Complete(long.clone()));
403            }
404        }
405    }
406
407    #[test]
408    fn nonce_table_is_bounded() {
409        let mut n = S0Manager::new(9, &[0; 16]);
410        for _ in 0..500 {
411            n.nonce_report(1).unwrap();
412        }
413        assert!(n.own_nonces.len() <= MAX_OWN_NONCES);
414    }
415}