Skip to main content

zwave_security/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5pub mod ckdf;
6pub mod crypto;
7pub mod drbg;
8pub mod dsk;
9pub mod kex;
10pub mod provisioning;
11pub mod qr;
12pub mod s0;
13pub mod s2;
14
15use std::fmt;
16
17/// A Z-Wave security class, the unit in which network keys are granted.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
21pub enum SecurityClass {
22    /// Security 0, the legacy scheme.
23    S0Legacy,
24    /// S2 Unauthenticated.
25    S2Unauthenticated,
26    /// S2 Authenticated (needs the DSK PIN).
27    S2Authenticated,
28    /// S2 Access Control (needs the DSK PIN; locks and garage doors).
29    S2AccessControl,
30}
31
32impl SecurityClass {
33    /// Every class, highest first: the order in which a receiver tries keys.
34    pub const HIGHEST_FIRST: [SecurityClass; 4] = [
35        SecurityClass::S2AccessControl,
36        SecurityClass::S2Authenticated,
37        SecurityClass::S2Unauthenticated,
38        SecurityClass::S0Legacy,
39    ];
40
41    /// The bit for this class in the KEX "requested/granted keys" byte.
42    pub const fn key_bit(self) -> u8 {
43        match self {
44            SecurityClass::S2Unauthenticated => 0x01,
45            SecurityClass::S2Authenticated => 0x02,
46            SecurityClass::S2AccessControl => 0x04,
47            SecurityClass::S0Legacy => 0x80,
48        }
49    }
50
51    /// The class for a single KEX key bit.
52    pub const fn from_key_bit(bit: u8) -> Option<SecurityClass> {
53        match bit {
54            0x01 => Some(SecurityClass::S2Unauthenticated),
55            0x02 => Some(SecurityClass::S2Authenticated),
56            0x04 => Some(SecurityClass::S2AccessControl),
57            0x80 => Some(SecurityClass::S0Legacy),
58            _ => None,
59        }
60    }
61
62    /// The classes set in a KEX keys byte, highest first. Unknown bits are ignored.
63    pub fn from_key_bits(bits: u8) -> Vec<SecurityClass> {
64        Self::HIGHEST_FIRST
65            .into_iter()
66            .filter(|c| bits & c.key_bit() != 0)
67            .collect()
68    }
69
70    /// The KEX keys byte for a set of classes.
71    pub fn to_key_bits(classes: &[SecurityClass]) -> u8 {
72        classes.iter().fold(0, |acc, c| acc | c.key_bit())
73    }
74
75    /// Whether granting this class needs the user to confirm the DSK PIN.
76    pub const fn needs_pin(self) -> bool {
77        matches!(
78            self,
79            SecurityClass::S2Authenticated | SecurityClass::S2AccessControl
80        )
81    }
82
83    /// Whether this is one of the S2 classes.
84    pub const fn is_s2(self) -> bool {
85        !matches!(self, SecurityClass::S0Legacy)
86    }
87
88    /// A short stable name (`s2_access_control`, ...).
89    pub const fn name(self) -> &'static str {
90        match self {
91            SecurityClass::S0Legacy => "s0_legacy",
92            SecurityClass::S2Unauthenticated => "s2_unauthenticated",
93            SecurityClass::S2Authenticated => "s2_authenticated",
94            SecurityClass::S2AccessControl => "s2_access_control",
95        }
96    }
97}
98
99impl fmt::Display for SecurityClass {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.write_str(self.name())
102    }
103}
104
105/// A 128-bit network key.
106pub type NetworkKey = [u8; 16];
107
108/// Errors from this crate.
109#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
110pub enum Error {
111    /// The frame is shorter than its format needs or a length field is inconsistent.
112    #[error("malformed frame: {0}")]
113    Malformed(&'static str),
114    /// No shared nonce (SPAN) with the peer: a Nonce Get / Nonce Report exchange is needed first.
115    #[error("no nonce established with the peer")]
116    NoSpan,
117    /// The peer's S0 nonce is missing or expired.
118    #[error("no valid nonce from the peer")]
119    NoNonce,
120    /// Authentication failed with every applicable key and nonce.
121    #[error("decryption failed")]
122    DecryptFailed,
123    /// The frame repeats a sequence number already seen (a retransmission).
124    #[error("duplicate frame")]
125    Duplicate,
126    /// No key is set for the security class this needs.
127    #[error("no key for {0}")]
128    NoKey(SecurityClass),
129    /// A critical extension this implementation does not know.
130    #[error("unsupported critical extension {0:#04x}")]
131    UnsupportedExtension(u8),
132    /// An invalid DSK, PIN or QR code string.
133    #[error("invalid {0}")]
134    Invalid(&'static str),
135    /// The operating system's random number source failed.
136    #[error("random number source failed")]
137    Random,
138}
139
140/// Fills `buf` from the operating system's CSPRNG.
141pub fn random_fill(buf: &mut [u8]) -> Result<(), Error> {
142    getrandom::fill(buf).map_err(|_| Error::Random)
143}
144
145/// Returns `N` random bytes from the operating system's CSPRNG.
146pub fn random_bytes<const N: usize>() -> Result<[u8; N], Error> {
147    let mut b = [0u8; N];
148    random_fill(&mut b)?;
149    Ok(b)
150}