Skip to main content

zwave_security/
kex.rs

1//! S2 key exchange (KEX) constants and the Curve25519 key pair.
2//!
3//! The exchange itself is a conversation between the controller and the
4//! joining node and lives in the host stack; this module holds the pieces
5//! both sides compute identically.
6
7use crate::ckdf::{temp_keys, temp_prk, DerivedKeys};
8use crate::Error;
9use x25519_dalek::{PublicKey, StaticSecret};
10
11/// KEX scheme 1, the bit in the "supported schemes" byte.
12pub const KEX_SCHEME_1: u8 = 0x02;
13/// The Curve25519 ECDH profile, the bit in the "supported profiles" byte.
14pub const ECDH_CURVE25519: u8 = 0x01;
15
16/// Why a key exchange was aborted (the KEX Fail command's payload).
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18#[repr(u8)]
19pub enum KexFail {
20    /// No supported key is requested or granted.
21    Key = 0x01,
22    /// No supported KEX scheme.
23    Scheme = 0x02,
24    /// No supported ECDH curve.
25    Curves = 0x03,
26    /// A frame could not be decrypted with the temporary key.
27    Decrypt = 0x05,
28    /// The user or the controller cancelled.
29    Cancel = 0x06,
30    /// The echoed KEX Set/Report did not match.
31    Auth = 0x07,
32    /// A key was requested that was not granted.
33    KeyGet = 0x08,
34    /// The Network Key Verify did not decrypt.
35    KeyVerify = 0x09,
36    /// The Network Key Report was not valid.
37    KeyReport = 0x0a,
38}
39
40impl KexFail {
41    /// The fail type for a wire value.
42    pub fn from_u8(v: u8) -> Option<Self> {
43        Some(match v {
44            0x01 => KexFail::Key,
45            0x02 => KexFail::Scheme,
46            0x03 => KexFail::Curves,
47            0x05 => KexFail::Decrypt,
48            0x06 => KexFail::Cancel,
49            0x07 => KexFail::Auth,
50            0x08 => KexFail::KeyGet,
51            0x09 => KexFail::KeyVerify,
52            0x0a => KexFail::KeyReport,
53            _ => return None,
54        })
55    }
56}
57
58/// A Curve25519 key pair: the controller's long-term pair, or a node's.
59#[derive(Clone)]
60pub struct KeyPair {
61    secret: StaticSecret,
62    public: [u8; 32],
63}
64
65impl std::fmt::Debug for KeyPair {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        write!(f, "KeyPair {{ public: {:02x?} }}", &self.public[..4])
68    }
69}
70
71impl KeyPair {
72    /// A fresh key pair from the operating system's CSPRNG.
73    pub fn generate() -> Result<Self, Error> {
74        Ok(Self::from_private(crate::random_bytes::<32>()?))
75    }
76
77    /// The key pair for a stored private key (clamped as X25519 does).
78    pub fn from_private(private: [u8; 32]) -> Self {
79        let secret = StaticSecret::from(private);
80        let public = PublicKey::from(&secret).to_bytes();
81        KeyPair { secret, public }
82    }
83
84    /// The private key, for storage.
85    pub fn private_bytes(&self) -> [u8; 32] {
86        self.secret.to_bytes()
87    }
88
89    /// The public key.
90    pub fn public(&self) -> &[u8; 32] {
91        &self.public
92    }
93
94    /// The ECDH shared secret with a peer's public key. Refuses low-order
95    /// points, whose all-zero secret anyone could predict.
96    pub fn shared_secret(&self, peer_public: &[u8; 32]) -> Result<[u8; 32], Error> {
97        let shared = self.secret.diffie_hellman(&PublicKey::from(*peer_public));
98        if !shared.was_contributory() {
99            return Err(Error::Invalid("public key"));
100        }
101        Ok(shared.to_bytes())
102    }
103}
104
105/// The temporary keys both ends derive once public keys are exchanged.
106///
107/// `controller_public` is the including node's key, `node_public` the
108/// joining node's (with its DSK PIN bytes restored).
109pub fn bootstrap_keys(
110    shared_secret: &[u8; 32],
111    controller_public: &[u8; 32],
112    node_public: &[u8; 32],
113) -> DerivedKeys {
114    temp_keys(&temp_prk(shared_secret, controller_public, node_public))
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    // RFC 7748 section 6.1.
122    #[test]
123    fn x25519_rfc7748() {
124        let h = |s: &str| -> [u8; 32] { hex::decode(s).unwrap().try_into().unwrap() };
125        let alice = KeyPair::from_private(h(
126            "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
127        ));
128        let bob = KeyPair::from_private(h(
129            "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb",
130        ));
131        assert_eq!(
132            alice.public(),
133            &h("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a")
134        );
135        assert_eq!(
136            bob.public(),
137            &h("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f")
138        );
139        let k = h("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742");
140        assert_eq!(alice.shared_secret(bob.public()).unwrap(), k);
141        assert_eq!(bob.shared_secret(alice.public()).unwrap(), k);
142    }
143
144    #[test]
145    fn low_order_point_refused() {
146        let a = KeyPair::generate().unwrap();
147        assert!(a.shared_secret(&[0u8; 32]).is_err());
148    }
149
150    #[test]
151    fn both_ends_derive_the_same_temp_keys() {
152        let ctrl = KeyPair::generate().unwrap();
153        let node = KeyPair::generate().unwrap();
154        let a = bootstrap_keys(
155            &ctrl.shared_secret(node.public()).unwrap(),
156            ctrl.public(),
157            node.public(),
158        );
159        let b = bootstrap_keys(
160            &node.shared_secret(ctrl.public()).unwrap(),
161            ctrl.public(),
162            node.public(),
163        );
164        assert_eq!(a, b);
165    }
166}