matter_kit/crypto/mod.rs
1//! The cryptosuite (Core ch. 3), and where a node's private keys live.
2//!
3//! Matter has exactly one cryptosuite. The specification is explicit: "There is no
4//! cryptosuite negotiation in this protocol: one version of the Message Format has one
5//! cryptosuite as defined in this chapter." SHA-256, HMAC-SHA256, HKDF, PBKDF2,
6//! AES-128-CCM with a 16-octet tag, AES-128-CTR, NIST P-256, SPAKE2+. Nothing here is a
7//! choice a node makes.
8//!
9//! # Why these are functions and not a trait
10//!
11//! The obvious shape is `Platform::Crypto`, an associated type threaded through every
12//! generic in the stack. It is the wrong shape, and this crate's own design notes had it
13//! wrong before the code existed.
14//!
15//! What varies is not the *algorithms* — the specification fixes those — but the
16//! *implementation*: software here, an AES peripheral there, a vendor library somewhere
17//! else. That is a property of the **build**, not of the node, and a build-time choice is
18//! what a Cargo feature is for. Making it a type parameter would put `C: Crypto` in the
19//! signature of everything from the session table to the interaction model, to express a
20//! choice nobody makes twice in one binary.
21//!
22//! So: the cryptosuite is [`mod@crate::crypto`], selected by feature. What *does* vary per
23//! node is **where the private keys live**, and that is [`KeyStore`] — a trait, because a
24//! node with a secure element and a node without one are genuinely different nodes.
25//!
26//! # Keys that stop existing
27//!
28//! [`SymmetricKey`] and [`Secret`] zeroise themselves when dropped, and compare in
29//! constant time. A `[u8; 16]` does neither: it leaves copies in freed memory and its
30//! `==` returns early on the first differing byte, which over enough tries tells an
31//! attacker the key one byte at a time.
32
33use core::fmt;
34
35use subtle::ConstantTimeEq;
36use zeroize::{Zeroize, ZeroizeOnDrop};
37
38use crate::error::{Error, ErrorCode, Result};
39
40#[cfg(feature = "rustcrypto")]
41mod rustcrypto;
42
43#[cfg(feature = "rustcrypto")]
44pub use rustcrypto::*;
45
46#[cfg(feature = "rustcrypto")]
47mod spake2p;
48
49#[cfg(feature = "rustcrypto")]
50pub use spake2p::{
51 Confirmation, SharedSecret, Spake2pProver, Spake2pVerifier, Spake2pVerifierData, context,
52};
53
54/// The `Info` string of the Privacy Key derivation (Core §4.9.1).
55pub const PRIVACY_KEY_INFO: &[u8] = b"PrivacyKey";
56
57// --- Constants, exactly as Core ch. 3 names them --------------------------------------
58
59/// `CRYPTO_HASH_LEN_BYTES` — SHA-256 produces 32 octets (§3.3).
60pub const HASH_LEN_BYTES: usize = 32;
61
62/// `CRYPTO_GROUP_SIZE_BYTES` — the P-256 scalar size (§3.5.1).
63pub const GROUP_SIZE_BYTES: usize = 32;
64
65/// `CRYPTO_PUBLIC_KEY_SIZE_BYTES` — `(2 * 32) + 1`, an uncompressed SEC 1 point (§3.5.1).
66pub const PUBLIC_KEY_SIZE_BYTES: usize = (2 * GROUP_SIZE_BYTES) + 1;
67
68/// `CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES` — AES-128 (§3.6).
69pub const SYMMETRIC_KEY_LENGTH_BYTES: usize = 16;
70
71/// `CRYPTO_AEAD_MIC_LENGTH_BYTES` — a full-length CCM tag (§3.6).
72pub const AEAD_MIC_LENGTH_BYTES: usize = 16;
73
74/// `CRYPTO_AEAD_NONCE_LENGTH_BYTES` (§3.6).
75pub const AEAD_NONCE_LENGTH_BYTES: usize = 13;
76
77/// `CRYPTO_PRIVACY_NONCE_LENGTH_BYTES` (§3.7).
78pub const PRIVACY_NONCE_LENGTH_BYTES: usize = 13;
79
80/// The signature size: `r` and `s`, each a group element (§3.5.3).
81pub const SIGNATURE_LEN_BYTES: usize = 2 * GROUP_SIZE_BYTES;
82
83/// `CRYPTO_W_SIZE_BYTES` — the PBKDF2 output half-width for SPAKE2+ (§3.10).
84pub const W_SIZE_BYTES: usize = GROUP_SIZE_BYTES + 8;
85
86/// `CRYPTO_PBKDF_ITERATIONS_MIN` (§3.9).
87pub const PBKDF_ITERATIONS_MIN: u32 = 1_000;
88
89/// `CRYPTO_PBKDF_ITERATIONS_MAX` (§3.9).
90pub const PBKDF_ITERATIONS_MAX: u32 = 100_000;
91
92/// The shortest PBKDF2 salt the specification allows (§3.9).
93pub const PBKDF_SALT_MIN_BYTES: usize = 16;
94
95/// The longest PBKDF2 salt the specification allows (§3.9).
96pub const PBKDF_SALT_MAX_BYTES: usize = 32;
97
98// --- Key material ---------------------------------------------------------------------
99
100/// A 128-bit symmetric key.
101///
102/// Zeroised on drop, and compared in constant time. There is no `Debug` that prints it and
103/// no `Deref` to the bytes: getting at the material is [`SymmetricKey::as_bytes`], which is
104/// easy to grep for in a review.
105#[derive(Clone, Zeroize, ZeroizeOnDrop)]
106pub struct SymmetricKey([u8; SYMMETRIC_KEY_LENGTH_BYTES]);
107
108impl SymmetricKey {
109 /// Wraps raw key material.
110 #[must_use]
111 pub const fn new(bytes: [u8; SYMMETRIC_KEY_LENGTH_BYTES]) -> Self {
112 Self(bytes)
113 }
114
115 /// Takes the first [`SYMMETRIC_KEY_LENGTH_BYTES`] of `bytes`.
116 pub fn from_slice(bytes: &[u8]) -> Result<Self> {
117 let Some(head) = bytes.get(..SYMMETRIC_KEY_LENGTH_BYTES) else {
118 return Err(Error::new(ErrorCode::InvalidArgument));
119 };
120 let mut out = [0u8; SYMMETRIC_KEY_LENGTH_BYTES];
121 out.copy_from_slice(head);
122 Ok(Self(out))
123 }
124
125 /// The raw material.
126 #[must_use]
127 pub const fn as_bytes(&self) -> &[u8; SYMMETRIC_KEY_LENGTH_BYTES] {
128 &self.0
129 }
130}
131
132impl fmt::Debug for SymmetricKey {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 // A key that prints itself is a key in a log file.
135 f.write_str("SymmetricKey(<redacted>)")
136 }
137}
138
139impl PartialEq for SymmetricKey {
140 fn eq(&self, other: &Self) -> bool {
141 self.0.ct_eq(&other.0).into()
142 }
143}
144
145impl Eq for SymmetricKey {}
146
147/// A secret of arbitrary length that zeroises on drop — a shared secret, a transcript
148/// hash, an intermediate KDF output.
149#[derive(Clone, Zeroize, ZeroizeOnDrop)]
150pub struct Secret<const N: usize>([u8; N]);
151
152impl<const N: usize> Secret<N> {
153 /// Wraps raw material.
154 #[must_use]
155 pub const fn new(bytes: [u8; N]) -> Self {
156 Self(bytes)
157 }
158
159 /// An all-zero secret, to be filled in.
160 #[must_use]
161 pub const fn zeroed() -> Self {
162 Self([0u8; N])
163 }
164
165 /// The raw material.
166 #[must_use]
167 pub const fn as_bytes(&self) -> &[u8; N] {
168 &self.0
169 }
170
171 /// The raw material, mutably — for a primitive that writes into it.
172 pub const fn as_mut(&mut self) -> &mut [u8; N] {
173 &mut self.0
174 }
175}
176
177impl<const N: usize> fmt::Debug for Secret<N> {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 f.write_str("Secret(<redacted>)")
180 }
181}
182
183impl<const N: usize> PartialEq for Secret<N> {
184 fn eq(&self, other: &Self) -> bool {
185 self.0.ct_eq(&other.0).into()
186 }
187}
188
189impl<const N: usize> Eq for Secret<N> {}
190
191/// A P-256 public key, as an uncompressed SEC 1 point (§3.5.1).
192#[derive(Clone, Copy, PartialEq, Eq)]
193pub struct PublicKey([u8; PUBLIC_KEY_SIZE_BYTES]);
194
195impl PublicKey {
196 /// Wraps an uncompressed point. The bytes are *not* checked to be on the curve here;
197 /// the primitive that uses them does that, and says so when they are not.
198 #[must_use]
199 pub const fn from_bytes(bytes: [u8; PUBLIC_KEY_SIZE_BYTES]) -> Self {
200 Self(bytes)
201 }
202
203 /// Reads an uncompressed point from a slice.
204 pub fn from_slice(bytes: &[u8]) -> Result<Self> {
205 let Ok(arr) = <[u8; PUBLIC_KEY_SIZE_BYTES]>::try_from(bytes) else {
206 return Err(Error::new(ErrorCode::InvalidArgument));
207 };
208 Ok(Self(arr))
209 }
210
211 /// The uncompressed SEC 1 encoding.
212 #[must_use]
213 pub const fn as_bytes(&self) -> &[u8; PUBLIC_KEY_SIZE_BYTES] {
214 &self.0
215 }
216}
217
218impl fmt::Debug for PublicKey {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 // Public keys are public; printing the first few octets is enough to tell two
221 // apart in a log without filling it.
222 let head = self.0.get(..4).unwrap_or(&[]);
223 write!(f, "PublicKey({head:02x?}…)")
224 }
225}
226
227/// An ECDSA signature: `r || s`, each a group element (§3.5.3).
228#[derive(Clone, Copy, PartialEq, Eq)]
229pub struct Signature([u8; SIGNATURE_LEN_BYTES]);
230
231impl Signature {
232 /// Wraps `r || s`.
233 #[must_use]
234 pub const fn from_bytes(bytes: [u8; SIGNATURE_LEN_BYTES]) -> Self {
235 Self(bytes)
236 }
237
238 /// Reads `r || s` from a slice.
239 pub fn from_slice(bytes: &[u8]) -> Result<Self> {
240 let Ok(arr) = <[u8; SIGNATURE_LEN_BYTES]>::try_from(bytes) else {
241 return Err(Error::new(ErrorCode::InvalidArgument));
242 };
243 Ok(Self(arr))
244 }
245
246 /// The `r || s` encoding.
247 #[must_use]
248 pub const fn as_bytes(&self) -> &[u8; SIGNATURE_LEN_BYTES] {
249 &self.0
250 }
251}
252
253impl fmt::Debug for Signature {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.write_str("Signature(..)")
256 }
257}
258
259// --- Where private keys live ------------------------------------------------------------
260
261/// A handle to a private key that this crate never sees the bytes of.
262///
263/// Opaque and `Copy`: an index, a slot number, whatever the store uses. The point is that
264/// nothing above [`KeyStore`] can do anything with it except pass it back.
265#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
266pub struct KeyHandle(pub u32);
267
268/// What a private key is for, so a store can apply different policy to each.
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
270#[non_exhaustive]
271pub enum KeyPurpose {
272 /// The Device Attestation Certificate's key. Written at manufacture, never replaced,
273 /// and the one most worth putting in hardware: it is what proves the device is genuine.
274 DeviceAttestation,
275 /// A Node Operational Certificate's key, one per fabric. Created during commissioning,
276 /// destroyed when the fabric is removed.
277 Operational,
278 /// An ephemeral key for one session establishment, discarded when it completes.
279 Ephemeral,
280}
281
282/// Custody of private keys.
283///
284/// Every operation that needs a private key goes through here, and none of them returns
285/// one. A node whose keys are in an ATECC608, an nRF KMU, an ESP32 HMAC peripheral or a
286/// TPM implements this over that; a node without one gets
287/// [`SoftKeyStore`], which keeps them in zeroising memory.
288///
289/// This is a trait — unlike the cryptosuite — because *where the keys live* really does
290/// differ between two nodes running the same binary.
291pub trait KeyStore {
292 /// Generates a key pair from 32 octets of randomness, returning its handle and
293 /// public key.
294 ///
295 /// The randomness is a parameter rather than something this crate fetches, for the
296 /// same reason every other source of entropy is: it comes from the one
297 /// [`Rng`](crate::platform::Rng) the integrator installed, so a platform with a
298 /// hardware generator uses it everywhere and a test can be deterministic.
299 ///
300 /// Returns [`ErrorCode::InvalidArgument`] if the value is not a valid private key —
301 /// zero, or at or above the group order. A caller should draw again.
302 fn generate(
303 &mut self,
304 purpose: KeyPurpose,
305 random: &[u8; GROUP_SIZE_BYTES],
306 ) -> Result<(KeyHandle, PublicKey)>;
307
308 /// Imports an existing private key. A store backed by hardware may refuse.
309 fn import(&mut self, purpose: KeyPurpose, secret: &[u8; GROUP_SIZE_BYTES])
310 -> Result<KeyHandle>;
311
312 /// The public key for a handle.
313 fn public_key(&self, handle: KeyHandle) -> Result<PublicKey>;
314
315 /// Signs `message` — ECDSA over SHA-256 (§3.5.3.1).
316 fn sign(&self, handle: KeyHandle, message: &[u8]) -> Result<Signature>;
317
318 /// Computes the ECDH shared secret with `peer` (§3.5.4).
319 ///
320 /// "The output of ECDH() SHALL be the serialization of the x-coordinate of the
321 /// resultant point."
322 fn ecdh(&self, handle: KeyHandle, peer: &PublicKey) -> Result<Secret<GROUP_SIZE_BYTES>>;
323
324 /// Destroys a key. Removing a fabric destroys its operational key, and that has to
325 /// actually happen rather than merely be forgotten about.
326 fn remove(&mut self, handle: KeyHandle) -> Result<()>;
327}
328
329/// Verifies an ECDSA signature (§3.5.3.2).
330///
331/// Free rather than a [`KeyStore`] method: verification needs only a public key, so there
332/// is nothing for a key store to have custody of.
333pub fn verify(public: &PublicKey, message: &[u8], signature: &Signature) -> Result<bool> {
334 #[cfg(feature = "rustcrypto")]
335 {
336 rustcrypto::verify_impl(public, message, signature)
337 }
338 #[cfg(not(feature = "rustcrypto"))]
339 {
340 let _ = (public, message, signature);
341 Err(Error::new(ErrorCode::Platform))
342 }
343}
344
345/// Constant-time equality for anything secret.
346///
347/// A `==` on two byte slices returns as soon as it finds a difference, so how long it took
348/// says how many leading octets matched. Over enough attempts that recovers a MIC or a
349/// confirmation value one octet at a time.
350#[must_use]
351pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
352 if a.len() != b.len() {
353 // The lengths are public — they are on the wire in the clear — so branching on
354 // them leaks nothing.
355 return false;
356 }
357 a.ct_eq(b).into()
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 #[test]
365 fn constants_match_chapter_3() {
366 assert_eq!(HASH_LEN_BYTES, 32);
367 assert_eq!(GROUP_SIZE_BYTES, 32);
368 assert_eq!(PUBLIC_KEY_SIZE_BYTES, 65);
369 assert_eq!(SYMMETRIC_KEY_LENGTH_BYTES, 16);
370 assert_eq!(AEAD_MIC_LENGTH_BYTES, 16);
371 assert_eq!(AEAD_NONCE_LENGTH_BYTES, 13);
372 assert_eq!(W_SIZE_BYTES, 40, "CRYPTO_GROUP_SIZE_BYTES + 8");
373 }
374
375 #[cfg(feature = "std")]
376 #[test]
377 fn a_key_does_not_print_itself() {
378 // A key that prints itself is a key in a log file. Needs `std` only because
379 // formatting to a `String` does.
380 let k = SymmetricKey::new([0xAB; 16]);
381 let shown = std::format!("{k:?}");
382 assert!(shown.contains("redacted"), "{shown}");
383 assert!(!shown.contains("ab"), "{shown}");
384 }
385
386 #[test]
387 fn keys_compare_by_value() {
388 assert_eq!(SymmetricKey::new([1; 16]), SymmetricKey::new([1; 16]));
389 assert_ne!(SymmetricKey::new([1; 16]), SymmetricKey::new([2; 16]));
390 }
391
392 #[test]
393 fn ct_eq_agrees_with_eq() {
394 assert!(ct_eq(b"abc", b"abc"));
395 assert!(!ct_eq(b"abc", b"abd"));
396 assert!(!ct_eq(b"abc", b"ab"), "different lengths are not equal");
397 assert!(ct_eq(b"", b""));
398 }
399
400 #[test]
401 fn a_symmetric_key_from_a_short_slice_is_refused() {
402 assert!(SymmetricKey::from_slice(&[0u8; 15]).is_err());
403 assert!(SymmetricKey::from_slice(&[0u8; 16]).is_ok());
404 // A longer slice takes the first 16, which is what a KDF output is.
405 assert!(SymmetricKey::from_slice(&[0u8; 32]).is_ok());
406 }
407}