Skip to main content

matter_kit/sc/
case.rs

1//! CASE — Certificate Authenticated Session Establishment (Core §4.14.2).
2//!
3//! PASE turns a printed passcode into one session, once, during commissioning. CASE turns
4//! operational certificates into every session after that, and is the protocol a Matter
5//! node spends its life speaking.
6//!
7//! # The shape of it
8//!
9//! CASE "mirrors the \[SIGMA\] protocol and uses the Identity Protection Key (IPK) to provide
10//! better identity protection". Three messages, two round trips:
11//!
12//! ```text
13//! initiator                                                    responder
14//!   Sigma1  ──── random, session id, destinationId, ephemeral ──▶
15//!          ◀──── random, session id, ephemeral, encrypted2 ──── Sigma2
16//!   Sigma3  ──── encrypted3 ─────────────────────────────────▶
17//!          ◀──── StatusReport(SESSION_ESTABLISHMENT_SUCCESS) ──
18//! ```
19//!
20//! Each peer proves it holds its NOC's private key by *signing the two ephemeral public
21//! keys together with its own certificate chain*. Signing the ephemerals is what binds the
22//! identity to this particular exchange; signing them in that order — own key first — is
23//! what stops a signature from Sigma2 being replayed as a Sigma3.
24//!
25//! The certificates themselves travel encrypted, under a key derived from the ECDH secret
26//! and the IPK. That is the identity protection: an observer who does not hold the fabric's
27//! IPK learns neither peer's identity, and cannot even tell which fabric they are on —
28//! which is also what [`destination_identifier`](crate::fabric::destination_identifier) is
29//! for.
30//!
31//! # Three keys, all from one secret
32//!
33//! `SharedSecret` is the ECDH of the two ephemerals. Everything else is an HKDF of it, and
34//! what distinguishes the derivations is the *salt*, which always contains the running
35//! transcript hash:
36//!
37//! | Key | Salt | Encrypts |
38//! |---|---|---|
39//! | S2K | `IPK ‖ responderRandom ‖ responderEphPubKey ‖ Hash(Msg1)` | Sigma2's `encrypted2` |
40//! | S3K | `IPK ‖ Hash(Msg1 ‖ Msg2)` | Sigma3's `encrypted3` |
41//! | session keys | `IPK ‖ Hash(Msg1 ‖ Msg2 ‖ Msg3)` | everything afterwards |
42//!
43//! Binding each key to the hash of everything said so far is what makes the exchange
44//! tamper-evident: change any byte of any earlier message and the next key is different, so
45//! the next decryption fails. There is no separate transcript MAC because the key *is* the
46//! MAC.
47//!
48//! # Resumption
49//!
50//! A peer that remembers a previous session's `SharedSecret` can skip both signatures —
51//! "dramatically reducing the computation required as well as reducing the number of
52//! messages exchanged", which on a battery-powered device is the difference between a
53//! session that costs milliseconds and one that costs hundreds. Resumption is
54//! [`ResumptionState`] plus the `Sigma2_Resume` path.
55//!
56//! # What this module is not
57//!
58//! It does not own the network, a clock or a key: a [`CaseInitiator`] and a
59//! [`CaseResponder`] consume and produce message bytes, and take randomness and signatures
60//! as parameters. `tests/case_over_sim.rs` drives a full exchange between two of them over
61//! the simulated network.
62
63use crate::cert::{CERT_TLV_MAX, MatterCertificate, VerifiedIdentity, verify_chain};
64use crate::crypto::{
65    AEAD_MIC_LENGTH_BYTES, AEAD_NONCE_LENGTH_BYTES, GROUP_SIZE_BYTES, HASH_LEN_BYTES, Hasher,
66    KeyHandle, KeyPurpose, KeyStore, PUBLIC_KEY_SIZE_BYTES, PublicKey, SIGNATURE_LEN_BYTES, Secret,
67    Signature, SymmetricKey, aead_decrypt_in_place, aead_encrypt_in_place, ct_eq, kdf_key, verify,
68};
69use crate::error::{Error, ErrorCode, Result, bail};
70use crate::fabric::{Fabric, INITIATOR_RANDOM_LEN};
71use crate::msg::SessionId;
72use crate::sc::status::{SecureChannelCode, StatusReport};
73use crate::sc::{Fields, SessionParams};
74use crate::tlv::{Tag, TlvWriter, set_once};
75
76/// The Secure Channel opcodes CASE uses (§4.11, Table 18).
77pub mod opcode {
78    /// `CASE Sigma1` — "The first message of the CASE protocol."
79    pub const SIGMA1: u8 = 0x30;
80    /// `CASE Sigma2`.
81    pub const SIGMA2: u8 = 0x31;
82    /// `CASE Sigma3`.
83    pub const SIGMA3: u8 = 0x32;
84    /// `CASE Sigma2_Resume` — "The second resumption message of the CASE protocol."
85    pub const SIGMA2_RESUME: u8 = 0x33;
86    /// `StatusReport`, which carries `SigmaFinished`.
87    pub const STATUS_REPORT: u8 = 0x40;
88}
89
90/// The length of `initiatorRandom` and `responderRandom` (§4.14.2.3).
91pub const RANDOM_LEN: usize = INITIATOR_RANDOM_LEN;
92
93/// The length of a resumption ID — `Crypto_DRBG(len = 16 * 8)`.
94pub const RESUMPTION_ID_LEN: usize = 16;
95
96// --- The `Info` strings of §4.14.2.6, spelled out as the specification spells them --------
97
98/// `S2K_Info` — "Sigma2".
99pub const S2K_INFO: &[u8] = b"Sigma2";
100/// `S3K_Info` — "Sigma3".
101pub const S3K_INFO: &[u8] = b"Sigma3";
102/// `S1RK_Info` — "Sigma1_Resume".
103pub const S1RK_INFO: &[u8] = b"Sigma1_Resume";
104/// `S2RK_Info` — "Sigma2_Resume".
105pub const S2RK_INFO: &[u8] = b"Sigma2_Resume";
106/// `SEKeys_Info` — "SessionKeys", shared with PASE (§4.14.1.2).
107pub const SESSION_KEYS_INFO: &[u8] = crate::session::SESSION_KEYS_INFO;
108/// `RSEKeys_Info` — "SessionResumptionKeys".
109pub const RESUMPTION_SESSION_KEYS_INFO: &[u8] = b"SessionResumptionKeys";
110
111// --- The AEAD nonces of §4.14.2, which are constants rather than counters ------------------
112
113/// `TBEData2_Nonce` — "NCASE_Sigma2N".
114pub const SIGMA2_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_Sigma2N";
115/// `TBEData3_Nonce` — "NCASE_Sigma3N".
116pub const SIGMA3_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_Sigma3N";
117/// `Resume1MIC_Nonce` — "NCASE_SigmaS1".
118pub const RESUME1_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_SigmaS1";
119/// `Resume2MIC_Nonce` — "NCASE_SigmaS2".
120pub const RESUME2_NONCE: [u8; AEAD_NONCE_LENGTH_BYTES] = *b"NCASE_SigmaS2";
121
122/// TLV overhead for an octet string whose length needs two octets — a control octet, a context
123/// tag, and the length. A certificate at §6.1.3's 400-octet cap is exactly such a string, and
124/// the difference between this and the three-octet short form is what a slack-based estimate
125/// gets wrong.
126const LONG_STRING_HEADER: usize = 4;
127/// The same for a string short enough to carry a one-octet length: a signature, a resumption
128/// id, a public key.
129const SHORT_STRING_HEADER: usize = 3;
130/// A structure costs its opening control octet and its end-of-container octet.
131const STRUCTURE_OVERHEAD: usize = 2;
132
133/// The largest `sigma-2-tbedata` **before** encryption: two certificates at §6.1.3's cap, the
134/// signature over the corresponding `tbsdata`, and the resumption id.
135///
136/// Written out term by term rather than as a sum plus slack, because the slack was wrong: the
137/// previous estimate for `encrypted3` was five octets short of what two maximum-size
138/// certificates actually need, which is a `BufferTooSmall` in the middle of a handshake and
139/// only against a peer whose CA issues large certificates.
140const MAX_TBEDATA2: usize = STRUCTURE_OVERHEAD
141    + (2 * (LONG_STRING_HEADER + CERT_TLV_MAX))
142    + (SHORT_STRING_HEADER + SIGNATURE_LEN_BYTES)
143    + (SHORT_STRING_HEADER + RESUMPTION_ID_LEN);
144
145/// The largest `sigma-3-tbedata`: the same without the resumption id.
146const MAX_TBEDATA3: usize = STRUCTURE_OVERHEAD
147    + (2 * (LONG_STRING_HEADER + CERT_TLV_MAX))
148    + (SHORT_STRING_HEADER + SIGNATURE_LEN_BYTES);
149
150/// The largest `encrypted2` this crate will build or accept — the plaintext plus the AEAD tag.
151///
152/// A responder that cannot fit this cannot complete CASE with a peer that uses an intermediate
153/// CA and a CA that issues certificates at the size the specification permits.
154pub const MAX_ENCRYPTED2: usize = MAX_TBEDATA2 + AEAD_MIC_LENGTH_BYTES;
155
156/// The largest `encrypted3`.
157pub const MAX_ENCRYPTED3: usize = MAX_TBEDATA3 + AEAD_MIC_LENGTH_BYTES;
158
159/// The largest `sigma-2-tbsdata` or `sigma-3-tbsdata` this crate signs or verifies: two
160/// certificates and the two ephemeral public keys.
161pub const MAX_TBSDATA: usize = STRUCTURE_OVERHEAD
162    + (2 * (LONG_STRING_HEADER + CERT_TLV_MAX))
163    + (2 * (SHORT_STRING_HEADER + PUBLIC_KEY_SIZE_BYTES));
164
165/// The largest `sigma-1-struct`: two randoms' worth of octet strings, a public key, a
166/// resumption id and MIC, the session parameters, and a TLV header for each.
167pub const MAX_SIGMA1: usize = RANDOM_LEN
168    + HASH_LEN_BYTES
169    + PUBLIC_KEY_SIZE_BYTES
170    + RESUMPTION_ID_LEN
171    + AEAD_MIC_LENGTH_BYTES
172    + 64;
173
174/// The largest `sigma-2-struct` this crate will build or accept.
175///
176/// It exists for the same reason [`MAX_SIGMA1`] does: a caller has to allocate the buffer the
177/// message is encoded into, and a caller that guesses guesses low. The guess only fails
178/// against a peer whose certificates are near §6.1.3's cap — so it survives every test written
179/// against this crate's own certificates and fails at a certification event.
180pub const MAX_SIGMA2: usize = STRUCTURE_OVERHEAD
181    + (SHORT_STRING_HEADER + RANDOM_LEN)
182    + 4
183    + (SHORT_STRING_HEADER + PUBLIC_KEY_SIZE_BYTES)
184    + (LONG_STRING_HEADER + MAX_ENCRYPTED2)
185    + MAX_SESSION_PARAMS;
186
187/// The largest `sigma-3-struct`: one field, and everything is inside it.
188pub const MAX_SIGMA3: usize = STRUCTURE_OVERHEAD + LONG_STRING_HEADER + MAX_ENCRYPTED3;
189
190/// The largest `session-parameter-struct` (§4.13.1): nine unsigned fields, each at most a
191/// control octet, a tag and four octets of value.
192pub const MAX_SESSION_PARAMS: usize = STRUCTURE_OVERHEAD + (9 * 6);
193
194/// The bounds above, checked against the encoding rules at compile time.
195///
196/// They are `const` assertions rather than tests for the reason [`crate::Config`]'s minima
197/// are: a buffer bound that is wrong is not a failing test, it is a node that cannot complete
198/// a handshake with a conforming peer, and the cheapest place to say so is the build.
199///
200/// Each is the sum of what the field actually costs, recomputed here from the octet counts
201/// rather than from the constants, so that a constant edited without its derivation fails. The
202/// numbers they guard were both wrong before anyone looked: `MAX_ENCRYPTED3` was five octets
203/// short of two certificates at §6.1.3's cap, and `MAX_SIGMA2` did not exist, so `examples/light`
204/// used a round 1024 against a real Sigma2 of 1081.
205const _: () = {
206    // `sigma-2-tbedata` = { NOC, ICAC, signature, resumptionID }, sealed.
207    assert!(
208        MAX_ENCRYPTED2
209            >= 2 + 2 * (4 + CERT_TLV_MAX)
210                + (3 + SIGNATURE_LEN_BYTES)
211                + (3 + RESUMPTION_ID_LEN)
212                + AEAD_MIC_LENGTH_BYTES
213    );
214    // `sigma-3-tbedata` = the same without the resumption id.
215    assert!(
216        MAX_ENCRYPTED3
217            >= 2 + 2 * (4 + CERT_TLV_MAX) + (3 + SIGNATURE_LEN_BYTES) + AEAD_MIC_LENGTH_BYTES
218    );
219    // `sigma-2-tbsdata` = { NOC, ICAC, both ephemeral public keys }, signed.
220    assert!(MAX_TBSDATA >= 2 + 2 * (4 + CERT_TLV_MAX) + 2 * (3 + PUBLIC_KEY_SIZE_BYTES));
221    // Nine unsigned fields, the widest 32 bits (§4.13.1).
222    assert!(MAX_SESSION_PARAMS >= 2 + 9 * (1 + 1 + 4));
223    // The whole `sigma-2-struct`, which is what a caller allocates for.
224    assert!(
225        MAX_SIGMA2
226            >= 2 + (3 + RANDOM_LEN)
227                + 4
228                + (3 + PUBLIC_KEY_SIZE_BYTES)
229                + (4 + MAX_ENCRYPTED2)
230                + MAX_SESSION_PARAMS
231    );
232    assert!(MAX_SIGMA3 >= 2 + 4 + MAX_ENCRYPTED3);
233    // CASE runs over MRP before there is any session to negotiate a larger transport on, so
234    // every one of these has to fit Core §4.4.4's 1280-octet datagram with its headers.
235    assert!(MAX_SIGMA2 + 64 <= crate::config::MAX_UDP_MESSAGE);
236};
237
238fn parse_error() -> Error {
239    Error::new(ErrorCode::TlvWrongType)
240}
241
242/// Encrypts `len` octets in place and appends the MIC, returning ciphertext ‖ MIC.
243///
244/// Every CASE AEAD uses an empty AAD — "TBEData2_A[] = {}" and its siblings — because
245/// everything that could usefully be bound in is already in the key's salt. The nonce is a
246/// constant rather than a counter, which is safe only because each key is used exactly
247/// once, for exactly one message.
248fn seal<'b>(
249    key: &SymmetricKey,
250    nonce: &[u8; AEAD_NONCE_LENGTH_BYTES],
251    buf: &'b mut [u8],
252    len: usize,
253) -> Result<&'b [u8]> {
254    let end = len
255        .checked_add(AEAD_MIC_LENGTH_BYTES)
256        .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
257    if buf.len() < end {
258        bail!(BufferTooSmall)
259    }
260    let (plaintext, rest) = buf.split_at_mut(len);
261    let mut mic = [0u8; AEAD_MIC_LENGTH_BYTES];
262    aead_encrypt_in_place(key, nonce, &[], plaintext, &mut mic)?;
263    rest.get_mut(..AEAD_MIC_LENGTH_BYTES)
264        .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?
265        .copy_from_slice(&mic);
266    buf.get(..end)
267        .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))
268}
269
270/// Copies `sealed` into `buf`, verifies its MIC and decrypts in place, returning the
271/// plaintext length.
272///
273/// The ciphertext is copied rather than decrypted where it lies because it arrived inside
274/// the received message, which the caller still needs intact for the transcript hash.
275fn open(
276    key: &SymmetricKey,
277    nonce: &[u8; AEAD_NONCE_LENGTH_BYTES],
278    buf: &mut [u8],
279    sealed: &[u8],
280) -> Result<usize> {
281    let len = sealed
282        .len()
283        .checked_sub(AEAD_MIC_LENGTH_BYTES)
284        .ok_or_else(|| Error::new(ErrorCode::IntegrityCheckFailed))?;
285    let (body, mic) = sealed.split_at(len);
286    let mic = <[u8; AEAD_MIC_LENGTH_BYTES]>::try_from(mic)
287        .map_err(|_| Error::new(ErrorCode::IntegrityCheckFailed))?;
288    let slot = buf
289        .get_mut(..len)
290        .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
291    slot.copy_from_slice(body);
292    aead_decrypt_in_place(key, nonce, &[], slot, &mic)?;
293    Ok(len)
294}
295
296// --- Sigma1 --------------------------------------------------------------------------------
297
298/// `sigma-1-struct` (§4.14.2.3).
299#[derive(Debug, Clone, PartialEq, Eq)]
300pub struct Sigma1<'a> {
301    /// `initiatorRandom [1]`.
302    pub initiator_random: [u8; RANDOM_LEN],
303    /// `initiatorSessionId [2]` — the id *the initiator* will listen on.
304    pub initiator_session_id: SessionId,
305    /// `destinationId [3]` — which fabric and node this is for, without naming either.
306    pub destination_id: [u8; HASH_LEN_BYTES],
307    /// `initiatorEphPubKey [4]`.
308    pub initiator_eph_pub_key: PublicKey,
309    /// `initiatorSessionParams [5]`.
310    pub session_params: Option<SessionParams>,
311    /// `resumptionID [6]` — present only when resuming.
312    pub resumption_id: Option<[u8; RESUMPTION_ID_LEN]>,
313    /// `initiatorResumeMIC [7]` — present only when resuming.
314    pub initiator_resume_mic: Option<[u8; AEAD_MIC_LENGTH_BYTES]>,
315    /// A borrow of the encoded message, because every later key is salted with its hash and
316    /// re-encoding it is not guaranteed to reproduce the peer's bytes.
317    encoded: &'a [u8],
318}
319
320impl<'a> Sigma1<'a> {
321    /// The bytes this message was decoded from — the `Msg1` of every transcript hash.
322    #[must_use]
323    pub const fn encoded(&self) -> &'a [u8] {
324        self.encoded
325    }
326
327    /// Whether the message asks for resumption: "The nomenclature Sigma1 with Resumption …
328    /// implies a Sigma1 message with **both** the optional resumptionID and
329    /// initiatorResumeMIC fields populated."
330    #[must_use]
331    pub const fn is_resumption(&self) -> bool {
332        self.resumption_id.is_some() && self.initiator_resume_mic.is_some()
333    }
334
335    /// Encodes a Sigma1.
336    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
337        let mut w = TlvWriter::new(buf);
338        w.start_structure(Tag::Anonymous)?;
339        w.octets(Tag::Context(1), &self.initiator_random)?;
340        w.unsigned(Tag::Context(2), u64::from(self.initiator_session_id.0))?;
341        w.octets(Tag::Context(3), &self.destination_id)?;
342        w.octets(Tag::Context(4), self.initiator_eph_pub_key.as_bytes())?;
343        if let Some(params) = self.session_params {
344            params.encode(&mut w, Tag::Context(5))?;
345        }
346        if let Some(id) = self.resumption_id.as_ref() {
347            w.octets(Tag::Context(6), id)?;
348        }
349        if let Some(mic) = self.initiator_resume_mic.as_ref() {
350            w.octets(Tag::Context(7), mic)?;
351        }
352        w.end_container()?;
353        w.finish()
354    }
355
356    /// Decodes a Sigma1, keeping a borrow of `buf` for the transcript.
357    pub fn decode(buf: &'a [u8]) -> Result<Self> {
358        let mut fields = Fields::new(buf)?;
359        let mut initiator_random = None;
360        let mut initiator_session_id = None;
361        let mut destination_id = None;
362        let mut initiator_eph_pub_key = None;
363        let mut session_params = None;
364        let mut resumption_id = None;
365        let mut initiator_resume_mic = None;
366
367        while let Some((tag, element)) = fields.next()? {
368            match tag {
369                1 => set_once(
370                    &mut initiator_random,
371                    fixed::<RANDOM_LEN>(element.octets()?)?,
372                )?,
373                2 => {
374                    let id =
375                        SessionId(u16::try_from(element.unsigned()?).map_err(|_| parse_error())?);
376                    set_once(&mut initiator_session_id, id)?;
377                }
378                3 => set_once(
379                    &mut destination_id,
380                    fixed::<HASH_LEN_BYTES>(element.octets()?)?,
381                )?,
382                4 => set_once(
383                    &mut initiator_eph_pub_key,
384                    PublicKey::from_slice(element.octets()?)?,
385                )?,
386                5 => set_once(&mut session_params, SessionParams::decode(&mut fields)?)?,
387                6 => set_once(
388                    &mut resumption_id,
389                    fixed::<RESUMPTION_ID_LEN>(element.octets()?)?,
390                )?,
391                7 => {
392                    let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(element.octets()?)?;
393                    set_once(&mut initiator_resume_mic, mic)?;
394                }
395                // "Any context-specific tags not listed in the above TLV schemas SHALL be
396                // reserved for future use, and SHALL be silently ignored if seen by a
397                // responder which cannot understand them."
398                _ => fields.skip(&element)?,
399            }
400        }
401
402        Ok(Self {
403            initiator_random: initiator_random.ok_or_else(parse_error)?,
404            initiator_session_id: initiator_session_id.ok_or_else(parse_error)?,
405            destination_id: destination_id.ok_or_else(parse_error)?,
406            initiator_eph_pub_key: initiator_eph_pub_key.ok_or_else(parse_error)?,
407            session_params,
408            resumption_id,
409            initiator_resume_mic,
410            encoded: buf,
411        })
412    }
413}
414
415// --- Sigma2 --------------------------------------------------------------------------------
416
417/// `sigma-2-struct` (§4.14.2.3).
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct Sigma2<'a> {
420    /// `responderRandom [1]`.
421    pub responder_random: [u8; RANDOM_LEN],
422    /// `responderSessionId [2]`.
423    pub responder_session_id: SessionId,
424    /// `responderEphPubKey [3]`.
425    pub responder_eph_pub_key: PublicKey,
426    /// `encrypted2 [4]` — `sigma-2-tbedata` under S2K.
427    pub encrypted2: &'a [u8],
428    /// `responderSessionParams [5]`.
429    pub session_params: Option<SessionParams>,
430    encoded: &'a [u8],
431}
432
433impl<'a> Sigma2<'a> {
434    /// The bytes this message was decoded from — the `Msg2` of every transcript hash.
435    #[must_use]
436    pub const fn encoded(&self) -> &'a [u8] {
437        self.encoded
438    }
439
440    /// Encodes a Sigma2.
441    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
442        let mut w = TlvWriter::new(buf);
443        w.start_structure(Tag::Anonymous)?;
444        w.octets(Tag::Context(1), &self.responder_random)?;
445        w.unsigned(Tag::Context(2), u64::from(self.responder_session_id.0))?;
446        w.octets(Tag::Context(3), self.responder_eph_pub_key.as_bytes())?;
447        w.octets(Tag::Context(4), self.encrypted2)?;
448        if let Some(params) = self.session_params {
449            params.encode(&mut w, Tag::Context(5))?;
450        }
451        w.end_container()?;
452        w.finish()
453    }
454
455    /// Decodes a Sigma2.
456    pub fn decode(buf: &'a [u8]) -> Result<Self> {
457        let mut fields = Fields::new(buf)?;
458        let mut responder_random = None;
459        let mut responder_session_id = None;
460        let mut responder_eph_pub_key = None;
461        let mut encrypted2 = None;
462        let mut session_params = None;
463
464        while let Some((tag, element)) = fields.next()? {
465            match tag {
466                1 => set_once(
467                    &mut responder_random,
468                    fixed::<RANDOM_LEN>(element.octets()?)?,
469                )?,
470                2 => {
471                    let id =
472                        SessionId(u16::try_from(element.unsigned()?).map_err(|_| parse_error())?);
473                    set_once(&mut responder_session_id, id)?;
474                }
475                3 => set_once(
476                    &mut responder_eph_pub_key,
477                    PublicKey::from_slice(element.octets()?)?,
478                )?,
479                4 => set_once(&mut encrypted2, element.octets()?)?,
480                5 => set_once(&mut session_params, SessionParams::decode(&mut fields)?)?,
481                _ => fields.skip(&element)?,
482            }
483        }
484
485        Ok(Self {
486            responder_random: responder_random.ok_or_else(parse_error)?,
487            responder_session_id: responder_session_id.ok_or_else(parse_error)?,
488            responder_eph_pub_key: responder_eph_pub_key.ok_or_else(parse_error)?,
489            encrypted2: encrypted2.ok_or_else(parse_error)?,
490            session_params,
491            encoded: buf,
492        })
493    }
494}
495
496// --- Sigma3 --------------------------------------------------------------------------------
497
498/// `sigma-3-struct` — one field, because everything else is inside it (§4.14.2.3).
499#[derive(Debug, Clone, PartialEq, Eq)]
500pub struct Sigma3<'a> {
501    /// `encrypted3 [1]` — `sigma-3-tbedata` under S3K.
502    pub encrypted3: &'a [u8],
503    encoded: &'a [u8],
504}
505
506impl<'a> Sigma3<'a> {
507    /// The bytes this message was decoded from — the `Msg3` of the session-key transcript.
508    #[must_use]
509    pub const fn encoded(&self) -> &'a [u8] {
510        self.encoded
511    }
512
513    /// Encodes a Sigma3.
514    pub fn encode<'b>(encrypted3: &[u8], buf: &'b mut [u8]) -> Result<&'b [u8]> {
515        let mut w = TlvWriter::new(buf);
516        w.start_structure(Tag::Anonymous)?;
517        w.octets(Tag::Context(1), encrypted3)?;
518        w.end_container()?;
519        w.finish()
520    }
521
522    /// Decodes a Sigma3.
523    pub fn decode(buf: &'a [u8]) -> Result<Self> {
524        let mut fields = Fields::new(buf)?;
525        let mut encrypted3 = None;
526        while let Some((tag, element)) = fields.next()? {
527            match tag {
528                1 => set_once(&mut encrypted3, element.octets()?)?,
529                _ => fields.skip(&element)?,
530            }
531        }
532        Ok(Self {
533            encrypted3: encrypted3.ok_or_else(parse_error)?,
534            encoded: buf,
535        })
536    }
537}
538
539/// `sigma-2-resume-struct` (§4.14.2.3).
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub struct Sigma2Resume {
542    /// `resumptionID [1]` — the id of the *new* session, not the one being resumed.
543    pub resumption_id: [u8; RESUMPTION_ID_LEN],
544    /// `sigma2ResumeMIC [2]`.
545    pub sigma2_resume_mic: [u8; AEAD_MIC_LENGTH_BYTES],
546    /// `responderSessionID [3]`.
547    pub responder_session_id: SessionId,
548    /// `responderSessionParams [4]`.
549    pub session_params: Option<SessionParams>,
550}
551
552impl Sigma2Resume {
553    /// Encodes a `Sigma2_Resume`.
554    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
555        let mut w = TlvWriter::new(buf);
556        w.start_structure(Tag::Anonymous)?;
557        w.octets(Tag::Context(1), &self.resumption_id)?;
558        w.octets(Tag::Context(2), &self.sigma2_resume_mic)?;
559        w.unsigned(Tag::Context(3), u64::from(self.responder_session_id.0))?;
560        if let Some(params) = self.session_params {
561            params.encode(&mut w, Tag::Context(4))?;
562        }
563        w.end_container()?;
564        w.finish()
565    }
566
567    /// Decodes a `Sigma2_Resume`.
568    pub fn decode(buf: &[u8]) -> Result<Self> {
569        let mut fields = Fields::new(buf)?;
570        let mut resumption_id = None;
571        let mut sigma2_resume_mic = None;
572        let mut responder_session_id = None;
573        let mut session_params = None;
574        while let Some((tag, element)) = fields.next()? {
575            match tag {
576                1 => set_once(
577                    &mut resumption_id,
578                    fixed::<RESUMPTION_ID_LEN>(element.octets()?)?,
579                )?,
580                2 => {
581                    let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(element.octets()?)?;
582                    set_once(&mut sigma2_resume_mic, mic)?;
583                }
584                3 => {
585                    let id =
586                        SessionId(u16::try_from(element.unsigned()?).map_err(|_| parse_error())?);
587                    set_once(&mut responder_session_id, id)?;
588                }
589                4 => set_once(&mut session_params, SessionParams::decode(&mut fields)?)?,
590                _ => fields.skip(&element)?,
591            }
592        }
593        Ok(Self {
594            resumption_id: resumption_id.ok_or_else(parse_error)?,
595            sigma2_resume_mic: sigma2_resume_mic.ok_or_else(parse_error)?,
596            responder_session_id: responder_session_id.ok_or_else(parse_error)?,
597            session_params,
598        })
599    }
600}
601
602/// The `StatusReport` a peer sends when CASE fails (§4.14.2.3, Appendix D).
603///
604/// The specification names two, and they answer different questions:
605///
606/// * [`SecureChannelCode::NoSharedTrustRoots`] — "If there is no candidateDestinationId
607///   matching the incoming destinationId, the responder SHALL send a status report" with
608///   this code. It means *we are not on a fabric together*, and it is the only honest answer
609///   a responder can give without revealing which fabrics it is on.
610/// * [`SecureChannelCode::InvalidParameter`] — every other rejection: a decryption that
611///   failed, a chain that did not verify, a signature that did not match, an identity that
612///   was not the one addressed. Deliberately undiscriminating: telling a peer *which* check
613///   it failed tells an attacker how far it got.
614///
615/// Every fallible entry point here returns a [`Result`], and a caller that wants to answer
616/// rather than simply drop the exchange encodes one of these. Which one to send is the
617/// caller's, because only the caller knows whether its fabric lookup came up empty.
618///
619/// ```
620/// use matter_kit::sc::{SecureChannelCode, case};
621///
622/// let mut out = [0u8; 32];
623/// let n = case::failure_report(SecureChannelCode::NoSharedTrustRoots, &mut out)?;
624/// // Eight octets: GeneralCode(2) + ProtocolId(4) + ProtocolCode(2).
625/// assert_eq!(n, 8);
626/// # Ok::<(), matter_kit::Error>(())
627/// ```
628pub fn failure_report(code: SecureChannelCode, out: &mut [u8]) -> Result<usize> {
629    StatusReport::secure_channel(code).encode(out)
630}
631
632fn fixed<const N: usize>(bytes: &[u8]) -> Result<[u8; N]> {
633    <[u8; N]>::try_from(bytes).map_err(|_| parse_error())
634}
635
636// --- The key schedule (§4.14.2.6) ------------------------------------------------------------
637
638/// The running transcript hash, which every CASE key is salted with.
639///
640/// "TranscriptHash = Crypto_Hash(message = Msg1)", then `Msg1 ‖ Msg2`, then
641/// `Msg1 ‖ Msg2 ‖ Msg3` — the same hash extended, not three separate ones. Keeping it
642/// incremental means a node never has to hold all three messages at once, which matters:
643/// with two certificate chains in flight they come to over a kilobyte.
644#[derive(Debug, Clone)]
645pub struct Transcript(Hasher);
646
647impl Default for Transcript {
648    fn default() -> Self {
649        Self::new()
650    }
651}
652
653impl Transcript {
654    /// An empty transcript.
655    #[must_use]
656    pub fn new() -> Self {
657        Self(Hasher::new())
658    }
659
660    /// Appends a message's encoded bytes — exactly the bytes that went on the wire.
661    pub fn update(&mut self, message: &[u8]) {
662        self.0.update(message);
663    }
664
665    /// The hash of everything appended so far, without consuming the transcript.
666    #[must_use]
667    pub fn hash(&self) -> [u8; HASH_LEN_BYTES] {
668        self.0.clone().finish()
669    }
670}
671
672/// The salt of an S2K derivation: `IPK ‖ responderRandom ‖ responderEphPubKey ‖ TranscriptHash`.
673const S2K_SALT_LEN: usize =
674    crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES + RANDOM_LEN + PUBLIC_KEY_SIZE_BYTES + HASH_LEN_BYTES;
675
676/// Derives S2K (§4.14.2.6.2).
677pub fn sigma2_key(
678    shared_secret: &Secret<GROUP_SIZE_BYTES>,
679    ipk: &SymmetricKey,
680    responder_random: &[u8; RANDOM_LEN],
681    responder_eph_pub_key: &PublicKey,
682    transcript_hash: &[u8; HASH_LEN_BYTES],
683) -> Result<SymmetricKey> {
684    let mut salt = [0u8; S2K_SALT_LEN];
685    let mut at = 0usize;
686    at = put(&mut salt, at, ipk.as_bytes())?;
687    at = put(&mut salt, at, responder_random)?;
688    at = put(&mut salt, at, responder_eph_pub_key.as_bytes())?;
689    at = put(&mut salt, at, transcript_hash)?;
690    let salt = salt.get(..at).ok_or_else(parse_error)?;
691    kdf_key(shared_secret.as_bytes(), salt, S2K_INFO)
692}
693
694/// The salt of an S3K or session-key derivation: `IPK ‖ TranscriptHash`.
695const IPK_TRANSCRIPT_SALT_LEN: usize = crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES + HASH_LEN_BYTES;
696
697fn ipk_transcript_salt(
698    ipk: &SymmetricKey,
699    transcript_hash: &[u8; HASH_LEN_BYTES],
700) -> [u8; IPK_TRANSCRIPT_SALT_LEN] {
701    let mut salt = [0u8; IPK_TRANSCRIPT_SALT_LEN];
702    let (head, tail) = salt.split_at_mut(crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES);
703    head.copy_from_slice(ipk.as_bytes());
704    tail.copy_from_slice(transcript_hash);
705    salt
706}
707
708/// Derives S3K (§4.14.2.6.3).
709pub fn sigma3_key(
710    shared_secret: &Secret<GROUP_SIZE_BYTES>,
711    ipk: &SymmetricKey,
712    transcript_hash: &[u8; HASH_LEN_BYTES],
713) -> Result<SymmetricKey> {
714    kdf_key(
715        shared_secret.as_bytes(),
716        &ipk_transcript_salt(ipk, transcript_hash),
717        S3K_INFO,
718    )
719}
720
721/// The salt of a resumption derivation: `Sigma1.initiatorRandom ‖ ResumptionID`.
722const RESUME_SALT_LEN: usize = RANDOM_LEN + RESUMPTION_ID_LEN;
723
724fn resume_salt(
725    initiator_random: &[u8; RANDOM_LEN],
726    resumption_id: &[u8; RESUMPTION_ID_LEN],
727) -> [u8; RESUME_SALT_LEN] {
728    let mut salt = [0u8; RESUME_SALT_LEN];
729    let (head, tail) = salt.split_at_mut(RANDOM_LEN);
730    head.copy_from_slice(initiator_random);
731    tail.copy_from_slice(resumption_id);
732    salt
733}
734
735/// Derives S1RK (§4.14.2.6.4), where `resumption_id` is the **previous** session's.
736pub fn sigma1_resume_key(
737    shared_secret: &Secret<GROUP_SIZE_BYTES>,
738    initiator_random: &[u8; RANDOM_LEN],
739    resumption_id: &[u8; RESUMPTION_ID_LEN],
740) -> Result<SymmetricKey> {
741    kdf_key(
742        shared_secret.as_bytes(),
743        &resume_salt(initiator_random, resumption_id),
744        S1RK_INFO,
745    )
746}
747
748/// Derives S2RK (§4.14.2.6.5), where `resumption_id` is the **new** session's.
749///
750/// The two resumption keys differ only in their `Info` string and in which resumption ID
751/// salts them — which is the whole reason the specification spells both out rather than
752/// reusing one: the same secret, the same random, and two different keys.
753pub fn sigma2_resume_key(
754    shared_secret: &Secret<GROUP_SIZE_BYTES>,
755    initiator_random: &[u8; RANDOM_LEN],
756    resumption_id: &[u8; RESUMPTION_ID_LEN],
757) -> Result<SymmetricKey> {
758    kdf_key(
759        shared_secret.as_bytes(),
760        &resume_salt(initiator_random, resumption_id),
761        S2RK_INFO,
762    )
763}
764
765/// The three session keys a completed CASE produces (§4.14.2.6.6).
766pub fn session_keys(
767    shared_secret: &Secret<GROUP_SIZE_BYTES>,
768    ipk: &SymmetricKey,
769    transcript_hash: &[u8; HASH_LEN_BYTES],
770) -> Result<crate::session::EstablishedKeys> {
771    crate::session::EstablishedKeys::derive(
772        shared_secret.as_bytes(),
773        &ipk_transcript_salt(ipk, transcript_hash),
774    )
775}
776
777/// The three session keys a completed *resumption* produces (§4.14.2.6.7).
778///
779/// A different `Info` and a salt with no transcript in it, because a resumption has no
780/// transcript worth binding: its security comes from the shared secret of the session it
781/// resumes.
782pub fn resumption_session_keys(
783    shared_secret: &Secret<GROUP_SIZE_BYTES>,
784    initiator_random: &[u8; RANDOM_LEN],
785    resumption_id: &[u8; RESUMPTION_ID_LEN],
786) -> Result<crate::session::EstablishedKeys> {
787    crate::session::EstablishedKeys::derive_with_info(
788        shared_secret.as_bytes(),
789        &resume_salt(initiator_random, resumption_id),
790        RESUMPTION_SESSION_KEYS_INFO,
791    )
792}
793
794fn put(buf: &mut [u8], at: usize, src: &[u8]) -> Result<usize> {
795    let end = at
796        .checked_add(src.len())
797        .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
798    let Some(slot) = buf.get_mut(at..end) else {
799        bail!(BufferTooSmall)
800    };
801    slot.copy_from_slice(src);
802    Ok(end)
803}
804
805// --- The signed and encrypted payloads ---------------------------------------------------
806
807/// Encodes a `sigma-2-tbsdata` or `sigma-3-tbsdata` — the structure that is signed but never
808/// transmitted (§4.14.2.3).
809///
810/// Both have the same shape: the signer's certificate chain, then its own ephemeral public
811/// key, then the peer's. The order of the two ephemerals is what distinguishes a Sigma2
812/// signature from a Sigma3 one, and is therefore what stops one being replayed as the
813/// other.
814pub fn encode_tbsdata<'b>(
815    noc: &[u8],
816    icac: Option<&[u8]>,
817    own_eph_pub_key: &PublicKey,
818    peer_eph_pub_key: &PublicKey,
819    buf: &'b mut [u8],
820) -> Result<&'b [u8]> {
821    let mut w = TlvWriter::new(buf);
822    w.start_structure(Tag::Anonymous)?;
823    w.octets(Tag::Context(1), noc)?;
824    if let Some(icac) = icac {
825        w.octets(Tag::Context(2), icac)?;
826    }
827    w.octets(Tag::Context(3), own_eph_pub_key.as_bytes())?;
828    w.octets(Tag::Context(4), peer_eph_pub_key.as_bytes())?;
829    w.end_container()?;
830    w.finish()
831}
832
833/// A decoded `sigma-2-tbedata` or `sigma-3-tbedata`.
834#[derive(Debug, Clone, PartialEq, Eq)]
835pub struct TbeData<'a> {
836    /// `[1]` — the peer's NOC, in Matter TLV.
837    pub noc: &'a [u8],
838    /// `[2]` — the peer's ICAC, if its chain has one.
839    pub icac: Option<&'a [u8]>,
840    /// `[3]` — the signature over the corresponding `tbsdata`.
841    pub signature: Signature,
842    /// `[4]` — the resumption ID, present in a `sigma-2-tbedata` and absent from a
843    /// `sigma-3-tbedata`.
844    pub resumption_id: Option<[u8; RESUMPTION_ID_LEN]>,
845}
846
847impl<'a> TbeData<'a> {
848    /// Encodes a `tbedata`.
849    ///
850    /// The certificate octets must be "byte-for-byte identical to the encoding in
851    /// sigma-2-tbsdata" (§4.14.2.3), which is why this takes the same slices rather than a
852    /// decoded certificate it might re-encode differently.
853    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
854        let mut w = TlvWriter::new(buf);
855        w.start_structure(Tag::Anonymous)?;
856        w.octets(Tag::Context(1), self.noc)?;
857        if let Some(icac) = self.icac {
858            w.octets(Tag::Context(2), icac)?;
859        }
860        w.octets(Tag::Context(3), self.signature.as_bytes())?;
861        if let Some(id) = self.resumption_id.as_ref() {
862            w.octets(Tag::Context(4), id)?;
863        }
864        w.end_container()?;
865        w.finish()
866    }
867
868    /// Decodes a `tbedata` from decrypted plaintext.
869    pub fn decode(buf: &'a [u8]) -> Result<Self> {
870        let mut fields = Fields::new(buf)?;
871        let mut noc = None;
872        let mut icac = None;
873        let mut signature = None;
874        let mut resumption_id = None;
875        while let Some((tag, element)) = fields.next()? {
876            match tag {
877                1 => set_once(&mut noc, element.octets()?)?,
878                2 => set_once(&mut icac, element.octets()?)?,
879                3 => set_once(&mut signature, Signature::from_slice(element.octets()?)?)?,
880                4 => set_once(
881                    &mut resumption_id,
882                    fixed::<RESUMPTION_ID_LEN>(element.octets()?)?,
883                )?,
884                _ => fields.skip(&element)?,
885            }
886        }
887        Ok(Self {
888            noc: noc.ok_or_else(parse_error)?,
889            icac,
890            signature: signature.ok_or_else(parse_error)?,
891            resumption_id,
892        })
893    }
894}
895
896// --- Resumption state (§4.14.2.2.1) ---------------------------------------------------------
897
898/// What both peers must remember to resume a session later.
899///
900/// §4.14.2.2.1 lists exactly this: "SharedSecret, Local Fabric Index, Peer Node ID, Peer
901/// CASE Authenticated Tags, ResumptionID". The CATs are part of the peer's identity, so
902/// resuming without them would silently widen what the peer is allowed to do — they are
903/// held in [`ResumptionState::identity`] rather than re-derived.
904#[derive(Debug, Clone)]
905pub struct ResumptionState {
906    /// The ECDH secret of the session being resumed. "It SHALL be that SharedSecret that is
907    /// used to compute the resumption ID."
908    pub shared_secret: Secret<GROUP_SIZE_BYTES>,
909    /// The identifier of that session.
910    pub resumption_id: [u8; RESUMPTION_ID_LEN],
911    /// This node's index for the fabric it was on.
912    pub fabric_index: crate::msg::FabricIndex,
913    /// Who the peer was, as the previous exchange established it.
914    pub identity: VerifiedIdentity,
915}
916
917/// Everything a completed CASE hands back.
918#[derive(Debug)]
919pub struct CaseOutcome {
920    /// The three session keys.
921    pub keys: crate::session::EstablishedKeys,
922    /// The peer's authenticated operational identity.
923    pub peer: VerifiedIdentity,
924    /// The session id the peer will listen on — what this node puts in outgoing messages.
925    pub peer_session_id: SessionId,
926    /// The MRP parameters the peer announced, if it announced any.
927    pub peer_session_params: Option<SessionParams>,
928    /// State for a later resumption, which the caller may keep or drop.
929    pub resumption: ResumptionState,
930}
931
932impl CaseOutcome {
933    /// Builds the operational session this handshake produced.
934    ///
935    /// Every identity a CASE session needs comes from exactly two places — this outcome and
936    /// the fabric the handshake ran on — so taking both is the only way to be sure none is
937    /// left at its default. Assembling a [`SecureSession`](crate::session::SecureSession)
938    /// field by field is still possible and is still wrong more often than it is right.
939    ///
940    /// The field that makes this more than convenience is `local_node_id`. §4.9.2 builds the
941    /// AEAD nonce from "the Security Flags, the Message Counter, and the Source Node ID of
942    /// that message", and for a CASE session the source node id is the sender's operational
943    /// node id — which never appears in the header, because both ends are supposed to know
944    /// it from the session. A session left at
945    /// [`NodeId::UNSPECIFIED`](crate::msg::NodeId::UNSPECIFIED) therefore encrypts every
946    /// message with a nonce the peer will not reconstruct, and the peer discards them
947    /// as unauthenticated. Nothing fails locally: this node sends, MRP retransmits into
948    /// silence, and the exchange is abandoned with no error at either end that names the
949    /// cause.
950    ///
951    /// `randomness` seeds the outgoing message counter (§4.6.2, which randomises it "on session
952    /// establishment") and `now` timestamps the
953    /// session, exactly as [`SecureSession::new`](crate::session::SecureSession::new) takes them.
954    pub fn into_session(
955        &self,
956        local_session_id: SessionId,
957        fabric: &Fabric,
958        randomness: u32,
959        now: crate::platform::Instant,
960    ) -> crate::session::SecureSession {
961        let mut session = crate::session::SecureSession::new(
962            local_session_id,
963            self.peer_session_id,
964            crate::session::SessionKind::Case,
965            crate::session::Role::Responder,
966            self.keys.clone(),
967            randomness,
968            now,
969        );
970        session.role = crate::session::Role::Responder;
971        session.local_node_id = fabric.node_id;
972        session.peer_node_id = self.peer.node_id;
973        session.fabric_index = fabric.index;
974        // §6.5.6 allows a NOC at most three, and `peer_cats` is sized for exactly that, so
975        // the push cannot overflow — but it is not worth a panic to say so.
976        for cat in &self.peer.cats {
977            let _ = session.peer_cats.push(*cat);
978        }
979        // "A Node SHALL use the provided default value for each parameter unless the message
980        // recipient Node advertises an alternate value" (§4.13.1): what the peer announced in
981        // Sigma1 governs how long this node waits before retransmitting to it.
982        if let Some(params) = self.peer_session_params {
983            session.mrp = params.to_mrp();
984        }
985        session
986    }
987
988    /// The same, for the node that *initiated* the handshake.
989    ///
990    /// The only difference is the role, and the role decides which of the two directional
991    /// keys this node encrypts with (§4.14.1) — so getting it wrong is the same silent
992    /// failure as getting `local_node_id` wrong.
993    pub fn into_initiator_session(
994        &self,
995        local_session_id: SessionId,
996        fabric: &Fabric,
997        randomness: u32,
998        now: crate::platform::Instant,
999    ) -> crate::session::SecureSession {
1000        let mut session = self.into_session(local_session_id, fabric, randomness, now);
1001        session.role = crate::session::Role::Initiator;
1002        session
1003    }
1004}
1005
1006// --- Responder --------------------------------------------------------------------------
1007
1008/// The device side of CASE: receives Sigma1, answers Sigma2, accepts Sigma3 (§4.14.2.3).
1009#[derive(Debug)]
1010pub struct CaseResponder {
1011    session_id: SessionId,
1012    session_params: Option<SessionParams>,
1013    state: ResponderState,
1014}
1015
1016/// The whole enum is as large as `AwaitingSigma3`, which is inherent: a responder mid-CASE
1017/// is holding a shared secret, an IPK, a hash state and two public keys, and there is
1018/// nowhere smaller to put them on a node with no allocator. It exists only between Sigma1
1019/// and Sigma3, so the cost is transient.
1020#[expect(
1021    clippy::large_enum_variant,
1022    reason = "no allocator, and the state is transient"
1023)]
1024#[derive(Debug)]
1025enum ResponderState {
1026    AwaitingSigma1,
1027    AwaitingSigma3(Box2),
1028    Done,
1029    Failed,
1030}
1031
1032/// The responder's state between Sigma2 and Sigma3.
1033#[derive(Debug)]
1034struct Box2 {
1035    shared_secret: Secret<GROUP_SIZE_BYTES>,
1036    ipk: SymmetricKey,
1037    transcript: Transcript,
1038    fabric_index: crate::msg::FabricIndex,
1039    /// The fabric the destination identifier selected; §4.14.2.3's *Validate Sigma3* step 4a
1040    /// holds the initiator's NOC to it.
1041    fabric_id: crate::msg::FabricId,
1042    initiator_session_id: SessionId,
1043    initiator_session_params: Option<SessionParams>,
1044    initiator_eph_pub_key: PublicKey,
1045    responder_eph_pub_key: PublicKey,
1046    resumption_id: [u8; RESUMPTION_ID_LEN],
1047}
1048
1049impl CaseResponder {
1050    /// A responder that will listen on `session_id` and announce `session_params`.
1051    #[must_use]
1052    pub fn new(session_id: SessionId, session_params: Option<SessionParams>) -> Self {
1053        Self {
1054            session_id,
1055            session_params,
1056            state: ResponderState::AwaitingSigma1,
1057        }
1058    }
1059
1060    /// Handles a Sigma1 and writes the reply into `out`.
1061    ///
1062    /// `fabric` is the one whose `destinationId` matched — found with
1063    /// [`FabricTable::find_by_destination_identifier`](crate::fabric::FabricTable::find_by_destination_identifier),
1064    /// which is a search this function deliberately does not do: it needs the fabric table,
1065    /// and threading the whole table through here would make the protocol depend on how a
1066    /// node stores its fabrics.
1067    ///
1068    /// `ephemeral_random` is 32 octets of entropy for the ephemeral key pair,
1069    /// `resumption_random` 16 for the new resumption ID.
1070    #[expect(
1071        clippy::too_many_arguments,
1072        reason = "Sigma2 genuinely needs all of this, and bundling it into a struct would \
1073                  only move the list somewhere the reader has to go and look for it."
1074    )]
1075    pub fn handle_sigma1<K: KeyStore>(
1076        &mut self,
1077        sigma1: &Sigma1<'_>,
1078        fabric: &Fabric,
1079        noc: &[u8],
1080        icac: Option<&[u8]>,
1081        keys: &mut K,
1082        ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1083        responder_random: &[u8; RANDOM_LEN],
1084        resumption_random: &[u8; RESUMPTION_ID_LEN],
1085        out: &mut [u8],
1086    ) -> Result<usize> {
1087        if !matches!(self.state, ResponderState::AwaitingSigma1) {
1088            self.state = ResponderState::Failed;
1089            bail!(InvalidState)
1090        }
1091        let result = self.build_sigma2(
1092            sigma1,
1093            fabric,
1094            noc,
1095            icac,
1096            keys,
1097            ephemeral_random,
1098            responder_random,
1099            resumption_random,
1100            out,
1101        );
1102        if result.is_err() {
1103            self.state = ResponderState::Failed;
1104        }
1105        result
1106    }
1107
1108    #[expect(clippy::too_many_arguments, reason = "see handle_sigma1")]
1109    fn build_sigma2<K: KeyStore>(
1110        &mut self,
1111        sigma1: &Sigma1<'_>,
1112        fabric: &Fabric,
1113        noc: &[u8],
1114        icac: Option<&[u8]>,
1115        keys: &mut K,
1116        ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1117        responder_random: &[u8; RANDOM_LEN],
1118        resumption_random: &[u8; RESUMPTION_ID_LEN],
1119        out: &mut [u8],
1120    ) -> Result<usize> {
1121        // The destination identifier must be for this fabric and this node. The caller
1122        // found the fabric by matching it, but re-checking here means a caller that
1123        // searched wrongly cannot establish a session on the wrong fabric.
1124        let expected = fabric.destination_identifier(&sigma1.initiator_random)?;
1125        if !ct_eq(&expected, &sigma1.destination_id) {
1126            bail!(CertPathInvalid)
1127        }
1128
1129        // §4.14.2.3: an ephemeral key pair per exchange, never reused.
1130        let (eph_handle, responder_eph_pub_key) =
1131            keys.generate(KeyPurpose::Ephemeral, ephemeral_random)?;
1132        // An ECDH against a peer's public key can fail — the point may not be on the curve —
1133        // and a key store has a fixed number of slots, so a stranger who sends a stream of
1134        // bad Sigma1s must not be able to fill it. The ephemeral is destroyed either way.
1135        let shared_secret = keys.ecdh(eph_handle, &sigma1.initiator_eph_pub_key);
1136        keys.remove(eph_handle)?;
1137        let shared_secret = shared_secret?;
1138
1139        let mut transcript = Transcript::new();
1140        transcript.update(sigma1.encoded());
1141        let s2k = sigma2_key(
1142            &shared_secret,
1143            &fabric.ipk,
1144            responder_random,
1145            &responder_eph_pub_key,
1146            &transcript.hash(),
1147        )?;
1148
1149        // sigma-2-tbsdata: own chain, own ephemeral, then the peer's.
1150        let mut tbs = [0u8; MAX_TBSDATA];
1151        let tbsdata = encode_tbsdata(
1152            noc,
1153            icac,
1154            &responder_eph_pub_key,
1155            &sigma1.initiator_eph_pub_key,
1156            &mut tbs,
1157        )?;
1158        let signature = keys.sign(fabric.operational_key, tbsdata)?;
1159
1160        let tbe = TbeData {
1161            noc,
1162            icac,
1163            signature,
1164            resumption_id: Some(*resumption_random),
1165        };
1166        let mut encrypted = [0u8; MAX_ENCRYPTED2];
1167        let plaintext_len = tbe.encode(&mut encrypted)?.len();
1168        // "TBEData2_A[] = {}" — no additional data, because everything that could be bound
1169        // in is already in S2K's salt.
1170        let encrypted2 = seal(&s2k, &SIGMA2_NONCE, &mut encrypted, plaintext_len)?;
1171
1172        let sigma2 = Sigma2 {
1173            responder_random: *responder_random,
1174            responder_session_id: self.session_id,
1175            responder_eph_pub_key,
1176            encrypted2,
1177            session_params: self.session_params,
1178            encoded: &[],
1179        };
1180        let len = sigma2.encode(out)?.len();
1181        let encoded = out.get(..len).ok_or_else(parse_error)?;
1182        transcript.update(encoded);
1183
1184        self.state = ResponderState::AwaitingSigma3(Box2 {
1185            shared_secret,
1186            ipk: fabric.ipk.clone(),
1187            transcript,
1188            fabric_index: fabric.index,
1189            fabric_id: fabric.fabric_id,
1190            initiator_session_id: sigma1.initiator_session_id,
1191            initiator_session_params: sigma1.session_params,
1192            initiator_eph_pub_key: sigma1.initiator_eph_pub_key,
1193            responder_eph_pub_key,
1194            resumption_id: *resumption_random,
1195        });
1196        Ok(len)
1197    }
1198
1199    /// Validates a `Sigma3` against the root of the fabric `Sigma1` resolved, and writes the
1200    /// `SigmaFinished` status report (§4.14.2.3).
1201    ///
1202    /// `fabric` is the index [`accept_sigma1`] returned, and using any other is the mistake this
1203    /// exists to prevent: §4.14.2.3's Validate Sigma3 checks the initiator's certificate chain
1204    /// against *this fabric's* trusted root, and a chain that verifies against another root is a
1205    /// chain from another administrator. Taking whichever root the table lists first works
1206    /// perfectly on a node with one fabric and refuses every peer on the second — as
1207    /// `chain does not validate`, which reads like a bad certificate and is not one.
1208    ///
1209    /// `at` is the current Matter `epoch-s`, or `None` on a node without a clock (§6.4.5.1).
1210    #[cfg(feature = "rustcrypto")]
1211    pub fn accept_sigma3<C: crate::config::Config, const N: usize>(
1212        &mut self,
1213        sigma3: &Sigma3<'_>,
1214        fabrics: &crate::fabric::FabricTable<C, N>,
1215        fabric: crate::msg::FabricIndex,
1216        at: Option<u32>,
1217        out: &mut [u8],
1218    ) -> Result<(CaseOutcome, usize)> {
1219        let rcac = fabrics
1220            .find(fabric)
1221            .map(|f| f.credentials.rcac.clone())
1222            .ok_or(Error::new(ErrorCode::NoSession))?;
1223        let root = MatterCertificate::decode(&rcac)?;
1224        let outcome = self.handle_sigma3(sigma3, &root, at)?;
1225        let n = self.finished(out)?;
1226        Ok((outcome, n))
1227    }
1228
1229    /// Handles a Sigma3, verifying the initiator's chain and establishing the session.
1230    ///
1231    /// `root` is the fabric's trusted root certificate; `at` the current Matter `epoch-s`,
1232    /// or `None` on a node without a clock (§6.4.5.1). Prefer
1233    /// [`accept_sigma3`](CaseResponder::accept_sigma3), which takes the root from the fabric the
1234    /// handshake is on rather than from the caller's memory.
1235    pub fn handle_sigma3(
1236        &mut self,
1237        sigma3: &Sigma3<'_>,
1238        root: &MatterCertificate<'_>,
1239        at: Option<u32>,
1240    ) -> Result<CaseOutcome> {
1241        let ResponderState::AwaitingSigma3(state) = &self.state else {
1242            self.state = ResponderState::Failed;
1243            bail!(InvalidState)
1244        };
1245
1246        let mut plaintext = [0u8; MAX_ENCRYPTED3];
1247        let s3k = sigma3_key(&state.shared_secret, &state.ipk, &state.transcript.hash())?;
1248        let decrypted_len = match open(&s3k, &SIGMA3_NONCE, &mut plaintext, sigma3.encrypted3) {
1249            Ok(len) => len,
1250            Err(e) => {
1251                self.state = ResponderState::Failed;
1252                return Err(e);
1253            }
1254        };
1255
1256        let outcome = (|| {
1257            let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
1258            let peer = verify_peer(
1259                &tbe,
1260                root,
1261                at,
1262                state.fabric_id,
1263                // A responder does not know which node is calling it.
1264                None,
1265                &state.initiator_eph_pub_key,
1266                &state.responder_eph_pub_key,
1267            )?;
1268
1269            let mut transcript = state.transcript.clone();
1270            transcript.update(sigma3.encoded());
1271            let keys = session_keys(&state.shared_secret, &state.ipk, &transcript.hash())?;
1272
1273            Ok(CaseOutcome {
1274                keys,
1275                peer: peer.clone(),
1276                peer_session_id: state.initiator_session_id,
1277                peer_session_params: state.initiator_session_params,
1278                resumption: ResumptionState {
1279                    shared_secret: state.shared_secret.clone(),
1280                    resumption_id: state.resumption_id,
1281                    fabric_index: state.fabric_index,
1282                    identity: peer,
1283                },
1284            })
1285        })();
1286
1287        self.state = if outcome.is_ok() {
1288            ResponderState::Done
1289        } else {
1290            ResponderState::Failed
1291        };
1292        outcome
1293    }
1294
1295    /// The `SigmaFinished` a responder sends once Sigma3 has been accepted (Appendix D).
1296    pub fn finished(&self, out: &mut [u8]) -> Result<usize> {
1297        if !matches!(self.state, ResponderState::Done) {
1298            bail!(InvalidState)
1299        }
1300        StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess).encode(out)
1301    }
1302
1303    /// Whether the exchange has failed and the responder must not be reused.
1304    #[must_use]
1305    pub const fn is_failed(&self) -> bool {
1306        matches!(self.state, ResponderState::Failed)
1307    }
1308}
1309
1310/// The three random values answering a `Sigma1` consumes (§4.14.2.3, §4.21).
1311///
1312/// Named rather than positional because they are three byte arrays of two different lengths
1313/// that a caller draws from one source: passed in the wrong order they still type-check where
1314/// the lengths agree, and the failure is a handshake that completes and a session nobody else
1315/// can address. Randomness is a parameter throughout this crate, so the caller draws them —
1316/// this only says which is which.
1317#[derive(Debug, Clone, Copy)]
1318pub struct Sigma2Randomness<'a> {
1319    /// The responder's ephemeral key material.
1320    pub ephemeral: &'a [u8; GROUP_SIZE_BYTES],
1321    /// `responderRandom`, which the transcript covers.
1322    pub responder: &'a [u8; RANDOM_LEN],
1323    /// The resumption id this session would be resumed by.
1324    pub resumption: &'a [u8; RESUMPTION_ID_LEN],
1325}
1326
1327/// Answers a `Sigma1` from the node's fabric table (§4.14.2.3).
1328///
1329/// Two steps sit between a decoded `Sigma1` and [`CaseResponder::handle_sigma1`], and both are
1330/// easy to get wrong in a way that works perfectly on a node with one fabric:
1331///
1332/// 1. **Which fabric the initiator named.** §4.14.2.4.1's destination identifier is a MAC only
1333///    something holding that fabric's IPK and one of this node's identities on it could have
1334///    computed, so resolving it is the lookup and the admission check at once — and the scan
1335///    over the table is constant-time, so a near miss and a wild miss cost the same.
1336/// 2. **Which credentials to answer with** — the NOC and ICAC `AddNOC` stored *for that fabric*.
1337///
1338/// Returns the responder, the fabric it resolved and the length of the `Sigma2` written to
1339/// `out`. Keep the fabric index with the responder:
1340/// [`accept_sigma3`](CaseResponder::accept_sigma3) needs it.
1341///
1342/// [`ErrorCode::NoSession`] means no fabric matched, which is the ordinary answer to a `Sigma1`
1343/// meant for another node on the link rather than a fault.
1344pub fn accept_sigma1<C: crate::config::Config, const N: usize, K: KeyStore>(
1345    sigma1: &Sigma1<'_>,
1346    fabrics: &crate::fabric::FabricTable<C, N>,
1347    keys: &mut K,
1348    local: SessionId,
1349    session_params: Option<SessionParams>,
1350    randomness: &Sigma2Randomness<'_>,
1351    out: &mut [u8],
1352) -> Result<(CaseResponder, crate::msg::FabricIndex, usize)> {
1353    let Sigma2Randomness {
1354        ephemeral: ephemeral_random,
1355        responder: responder_random,
1356        resumption: resumption_random,
1357    } = randomness;
1358    let fabric = fabrics
1359        .find_by_destination_identifier(&sigma1.initiator_random, &sigma1.destination_id)?
1360        .ok_or(Error::new(ErrorCode::NoSession))?;
1361    let index = fabric.index;
1362    let noc = fabric.credentials.noc.clone();
1363    let icac = fabric.credentials.icac.clone();
1364    let fabric = fabric.clone();
1365
1366    let mut responder = CaseResponder::new(local, session_params);
1367    let n = responder.handle_sigma1(
1368        sigma1,
1369        &fabric,
1370        &noc,
1371        icac.as_deref(),
1372        keys,
1373        ephemeral_random,
1374        responder_random,
1375        resumption_random,
1376        out,
1377    )?;
1378    Ok((responder, index, n))
1379}
1380
1381// --- Initiator --------------------------------------------------------------------------
1382
1383/// The commissioner or controller side of CASE (§4.14.2.3).
1384#[derive(Debug)]
1385pub struct CaseInitiator {
1386    session_id: SessionId,
1387    session_params: Option<SessionParams>,
1388    state: InitiatorState,
1389}
1390
1391/// As with [`ResponderState`], the size is the state a half-finished exchange must hold.
1392#[expect(
1393    clippy::large_enum_variant,
1394    reason = "no allocator, and the state is transient"
1395)]
1396#[derive(Debug)]
1397enum InitiatorState {
1398    Start,
1399    AwaitingSigma2(Box1),
1400    Done,
1401    Failed,
1402}
1403
1404/// The initiator's state between Sigma1 and Sigma2.
1405#[derive(Debug)]
1406struct Box1 {
1407    initiator_random: [u8; RANDOM_LEN],
1408    eph_handle: KeyHandle,
1409    initiator_eph_pub_key: PublicKey,
1410    ipk: SymmetricKey,
1411    fabric_index: crate::msg::FabricIndex,
1412    /// The fabric the Sigma1 was built for, so the responder's NOC can be held to it.
1413    fabric_id: crate::msg::FabricId,
1414    /// The node the destination identifier addressed. §4.14.2.3 step 5a requires the
1415    /// responder's NOC to be for exactly this node.
1416    peer_node_id: crate::msg::NodeId,
1417    transcript: Transcript,
1418}
1419
1420impl CaseInitiator {
1421    /// An initiator that will listen on `session_id`.
1422    #[must_use]
1423    pub fn new(session_id: SessionId, session_params: Option<SessionParams>) -> Self {
1424        Self {
1425            session_id,
1426            session_params,
1427            state: InitiatorState::Start,
1428        }
1429    }
1430
1431    /// Builds a Sigma1 addressed to `peer_node_id` on `fabric`.
1432    pub fn start<K: KeyStore>(
1433        &mut self,
1434        fabric: &Fabric,
1435        peer_node_id: crate::msg::NodeId,
1436        keys: &mut K,
1437        initiator_random: &[u8; RANDOM_LEN],
1438        ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1439        out: &mut [u8],
1440    ) -> Result<usize> {
1441        if !matches!(self.state, InitiatorState::Start) {
1442            bail!(InvalidState)
1443        }
1444        // The destination identifier names the peer, not this node — that is the point:
1445        // the responder recognises itself in it without either end saying a node id aloud.
1446        let destination_id = crate::fabric::destination_identifier(
1447            &fabric.ipk,
1448            initiator_random,
1449            &fabric.root_public_key,
1450            fabric.fabric_id,
1451            peer_node_id,
1452        )?;
1453        let (eph_handle, initiator_eph_pub_key) =
1454            keys.generate(KeyPurpose::Ephemeral, ephemeral_random)?;
1455
1456        let sigma1 = Sigma1 {
1457            initiator_random: *initiator_random,
1458            initiator_session_id: self.session_id,
1459            destination_id,
1460            initiator_eph_pub_key,
1461            session_params: self.session_params,
1462            resumption_id: None,
1463            initiator_resume_mic: None,
1464            encoded: &[],
1465        };
1466        let len = sigma1.encode(out)?.len();
1467        let mut transcript = Transcript::new();
1468        transcript.update(out.get(..len).ok_or_else(parse_error)?);
1469
1470        self.state = InitiatorState::AwaitingSigma2(Box1 {
1471            initiator_random: *initiator_random,
1472            eph_handle,
1473            initiator_eph_pub_key,
1474            ipk: fabric.ipk.clone(),
1475            fabric_index: fabric.index,
1476            fabric_id: fabric.fabric_id,
1477            peer_node_id,
1478            transcript,
1479        });
1480        Ok(len)
1481    }
1482
1483    /// Handles a Sigma2, verifies the responder, and writes a Sigma3.
1484    ///
1485    /// Returns the length of the Sigma3 and the established session — the initiator's keys
1486    /// are complete the moment it has sent Sigma3, before the `SigmaFinished` arrives,
1487    /// because the transcript is complete at that point.
1488    #[expect(
1489        clippy::too_many_arguments,
1490        reason = "see CaseResponder::handle_sigma1"
1491    )]
1492    pub fn handle_sigma2<K: KeyStore>(
1493        &mut self,
1494        sigma2: &Sigma2<'_>,
1495        fabric: &Fabric,
1496        root: &MatterCertificate<'_>,
1497        noc: &[u8],
1498        icac: Option<&[u8]>,
1499        keys: &mut K,
1500        at: Option<u32>,
1501        out: &mut [u8],
1502    ) -> Result<(usize, CaseOutcome)> {
1503        let result = self.build_sigma3(sigma2, fabric, root, noc, icac, keys, at, out);
1504        if result.is_err() {
1505            // The exchange is over either way, so the ephemeral must not outlive it: a key
1506            // store has a fixed number of slots and a controller that retries a failing
1507            // peer would otherwise exhaust them. `build_sigma3` destroys it on success.
1508            if let InitiatorState::AwaitingSigma2(state) = &self.state {
1509                let _ = keys.remove(state.eph_handle);
1510            }
1511            self.state = InitiatorState::Failed;
1512        }
1513        result
1514    }
1515
1516    #[expect(
1517        clippy::too_many_arguments,
1518        reason = "see CaseResponder::handle_sigma1"
1519    )]
1520    fn build_sigma3<K: KeyStore>(
1521        &mut self,
1522        sigma2: &Sigma2<'_>,
1523        fabric: &Fabric,
1524        root: &MatterCertificate<'_>,
1525        noc: &[u8],
1526        icac: Option<&[u8]>,
1527        keys: &mut K,
1528        at: Option<u32>,
1529        out: &mut [u8],
1530    ) -> Result<(usize, CaseOutcome)> {
1531        let InitiatorState::AwaitingSigma2(state) = &self.state else {
1532            bail!(InvalidState)
1533        };
1534
1535        let shared_secret = keys.ecdh(state.eph_handle, &sigma2.responder_eph_pub_key)?;
1536        let s2k = sigma2_key(
1537            &shared_secret,
1538            &state.ipk,
1539            &sigma2.responder_random,
1540            &sigma2.responder_eph_pub_key,
1541            &state.transcript.hash(),
1542        )?;
1543
1544        let mut plaintext = [0u8; MAX_ENCRYPTED2];
1545        let decrypted_len = open(&s2k, &SIGMA2_NONCE, &mut plaintext, sigma2.encrypted2)?;
1546        let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
1547        let peer = verify_peer(
1548            &tbe,
1549            root,
1550            at,
1551            state.fabric_id,
1552            Some(state.peer_node_id),
1553            &sigma2.responder_eph_pub_key,
1554            &state.initiator_eph_pub_key,
1555        )?;
1556        // A Sigma2 without a resumption ID cannot be resumed later, and the schema makes it
1557        // mandatory, so its absence is a malformed message rather than a missing option.
1558        let resumption_id = tbe.resumption_id.ok_or_else(parse_error)?;
1559
1560        let mut transcript = state.transcript.clone();
1561        transcript.update(sigma2.encoded());
1562
1563        // sigma-3-tbsdata: own chain, own ephemeral, then the peer's — the mirror of
1564        // Sigma2's, and the reason a Sigma2 signature cannot be replayed here.
1565        let mut tbs = [0u8; MAX_TBSDATA];
1566        let tbsdata = encode_tbsdata(
1567            noc,
1568            icac,
1569            &state.initiator_eph_pub_key,
1570            &sigma2.responder_eph_pub_key,
1571            &mut tbs,
1572        )?;
1573        let signature = keys.sign(fabric.operational_key, tbsdata)?;
1574
1575        let tbe3 = TbeData {
1576            noc,
1577            icac,
1578            signature,
1579            resumption_id: None,
1580        };
1581        let mut encrypted = [0u8; MAX_ENCRYPTED3];
1582        let plaintext_len = tbe3.encode(&mut encrypted)?.len();
1583        let s3k = sigma3_key(&shared_secret, &state.ipk, &transcript.hash())?;
1584        let encrypted3 = seal(&s3k, &SIGMA3_NONCE, &mut encrypted, plaintext_len)?;
1585
1586        let len = Sigma3::encode(encrypted3, out)?.len();
1587        transcript.update(out.get(..len).ok_or_else(parse_error)?);
1588
1589        let session = session_keys(&shared_secret, &state.ipk, &transcript.hash())?;
1590        let fabric_index = state.fabric_index;
1591
1592        keys.remove(state.eph_handle)?;
1593        self.state = InitiatorState::Done;
1594
1595        Ok((
1596            len,
1597            CaseOutcome {
1598                keys: session,
1599                peer: peer.clone(),
1600                peer_session_id: sigma2.responder_session_id,
1601                peer_session_params: sigma2.session_params,
1602                resumption: ResumptionState {
1603                    shared_secret,
1604                    resumption_id,
1605                    fabric_index,
1606                    identity: peer,
1607                },
1608            },
1609        ))
1610    }
1611
1612    /// Checks the responder's `SigmaFinished`.
1613    ///
1614    /// A `StatusReport` that is anything other than
1615    /// `SUCCESS`/`SESSION_ESTABLISHMENT_SUCCESS` means the responder rejected the Sigma3,
1616    /// and the session this node already derived keys for must be discarded.
1617    pub fn accept_finished(&mut self, report: &[u8]) -> Result<()> {
1618        let report = StatusReport::decode(report)?;
1619        if report.is_success()
1620            && report.secure_channel_code() == Some(SecureChannelCode::SessionEstablishmentSuccess)
1621        {
1622            Ok(())
1623        } else {
1624            self.state = InitiatorState::Failed;
1625            Err(Error::new(ErrorCode::InvalidState))
1626        }
1627    }
1628
1629    /// Whether the exchange has failed.
1630    #[must_use]
1631    pub const fn is_failed(&self) -> bool {
1632        matches!(self.state, InitiatorState::Failed)
1633    }
1634}
1635
1636/// Verifies a peer's chain, its identity and its signature over the `tbsdata` it should have
1637/// signed.
1638///
1639/// `expected_fabric` is the fabric the destination identifier selected. `expected_node` is
1640/// set only for a Sigma2, and the asymmetry is the specification's:
1641///
1642/// * §4.14.2.3's *Validate Sigma2* step 5a — "The Fabric ID **and Node ID** SHALL match the
1643///   intended identity of the receiver Node, as included in the computation of the
1644///   Destination Identifier when generating Sigma1." Without this, any node holding a valid
1645///   NOC on the same fabric could answer in place of the one that was addressed, and the
1646///   initiator would establish a perfectly sound session with the wrong device.
1647/// * *Validate Sigma3* step 4a — "The **Fabric ID** SHALL match the Fabric ID matched during
1648///   processing of the Destination Identifier". A responder does not know which node is
1649///   calling it, so there is no node id to check; any node on the fabric may connect, and
1650///   what it is then allowed to do is `acl`'s decision.
1651///
1652/// The order matters: the chain is verified before the signature, so a forged chain is
1653/// rejected before its public key is trusted for anything.
1654fn verify_peer(
1655    tbe: &TbeData<'_>,
1656    root: &MatterCertificate<'_>,
1657    at: Option<u32>,
1658    expected_fabric: crate::msg::FabricId,
1659    expected_node: Option<crate::msg::NodeId>,
1660    signer_eph_pub_key: &PublicKey,
1661    peer_eph_pub_key: &PublicKey,
1662) -> Result<VerifiedIdentity> {
1663    let noc = MatterCertificate::decode(tbe.noc)?;
1664    let icac = match tbe.icac {
1665        Some(bytes) => Some(MatterCertificate::decode(bytes)?),
1666        None => None,
1667    };
1668    // `verify_chain` applies the DN encoding rules (step d), the fabric-id agreement between
1669    // the chain's certificates (step b) and the chain back to the trusted root (step c).
1670    let identity = verify_chain(&noc, icac.as_ref(), root, at)?;
1671
1672    if identity.fabric_id != expected_fabric {
1673        bail!(CertPathInvalid)
1674    }
1675    if expected_node.is_some_and(|expected| identity.node_id != expected) {
1676        bail!(CertPathInvalid)
1677    }
1678
1679    let mut tbs = [0u8; MAX_TBSDATA];
1680    let tbsdata = encode_tbsdata(
1681        tbe.noc,
1682        tbe.icac,
1683        signer_eph_pub_key,
1684        peer_eph_pub_key,
1685        &mut tbs,
1686    )?;
1687    if !verify(&noc.public_key, tbsdata, &tbe.signature)? {
1688        bail!(CertPathInvalid)
1689    }
1690    Ok(identity)
1691}
1692
1693// --- Resumption (§4.14.2.2) ---------------------------------------------------------------
1694
1695impl CaseInitiator {
1696    /// Builds a Sigma1 that asks to resume `previous` (§4.14.2.3).
1697    ///
1698    /// It is still a complete Sigma1: if the responder has forgotten the session, it
1699    /// "SHALL be processed as a Sigma1 message without any resumption fields", and the
1700    /// exchange falls through to the full protocol without a round trip lost. So the
1701    /// ephemeral key and the destination identifier are built exactly as
1702    /// [`CaseInitiator::start`] builds them, and the resumption fields are added on top.
1703    #[expect(
1704        clippy::too_many_arguments,
1705        reason = "see CaseResponder::handle_sigma1"
1706    )]
1707    pub fn start_resumption<K: KeyStore>(
1708        &mut self,
1709        fabric: &Fabric,
1710        peer_node_id: crate::msg::NodeId,
1711        previous: &ResumptionState,
1712        keys: &mut K,
1713        initiator_random: &[u8; RANDOM_LEN],
1714        ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1715        out: &mut [u8],
1716    ) -> Result<usize> {
1717        let len = self.start(
1718            fabric,
1719            peer_node_id,
1720            keys,
1721            initiator_random,
1722            ephemeral_random,
1723            out,
1724        )?;
1725
1726        // The MIC is an AEAD over *nothing* — "Resume1MIC_P[] = {}", "Resume1MIC_A[] = {}"
1727        // — so it proves only one thing, which is the thing that matters: that this peer
1728        // holds the previous session's shared secret.
1729        let s1rk = sigma1_resume_key(
1730            &previous.shared_secret,
1731            initiator_random,
1732            &previous.resumption_id,
1733        )?;
1734        let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1735        let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s1rk, &RESUME1_NONCE, &mut empty, 0)?)?;
1736
1737        let mut sigma1 = Sigma1::decode(out.get(..len).ok_or_else(parse_error)?)?;
1738        sigma1.resumption_id = Some(previous.resumption_id);
1739        sigma1.initiator_resume_mic = Some(mic);
1740
1741        // Re-encoding into the same buffer would alias the borrow the decode holds, so the
1742        // message is rebuilt beside it and copied back.
1743        let mut rebuilt = [0u8; MAX_SIGMA1];
1744        let encoded = sigma1.encode(&mut rebuilt)?;
1745        let new_len = encoded.len();
1746        out.get_mut(..new_len)
1747            .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?
1748            .copy_from_slice(encoded);
1749
1750        // The transcript covers the message that actually went out, resumption fields and
1751        // all — it would be the wrong hash otherwise if the responder declines to resume.
1752        if let InitiatorState::AwaitingSigma2(state) = &mut self.state {
1753            state.transcript = Transcript::new();
1754            state
1755                .transcript
1756                .update(out.get(..new_len).ok_or_else(parse_error)?);
1757        }
1758        Ok(new_len)
1759    }
1760
1761    /// Handles a `Sigma2_Resume`, completing a resumed session (§4.14.2.3).
1762    ///
1763    /// The peer's identity is carried over from `previous` rather than re-derived: a
1764    /// resumption proves possession of the old session's secret, which only the peer that
1765    /// authenticated then could hold, so the identity it established still stands.
1766    pub fn accept_resume<K: KeyStore>(
1767        &mut self,
1768        message: &Sigma2Resume,
1769        previous: &ResumptionState,
1770        keys: &mut K,
1771    ) -> Result<CaseOutcome> {
1772        let InitiatorState::AwaitingSigma2(state) = &self.state else {
1773            bail!(InvalidState)
1774        };
1775        let initiator_random = state.initiator_random;
1776        let eph_handle = state.eph_handle;
1777        let fabric_index = state.fabric_index;
1778
1779        let s2rk = sigma2_resume_key(
1780            &previous.shared_secret,
1781            &initiator_random,
1782            &message.resumption_id,
1783        )?;
1784        let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1785        if let Err(e) = open(
1786            &s2rk,
1787            &RESUME2_NONCE,
1788            &mut empty,
1789            &message.sigma2_resume_mic,
1790        ) {
1791            // As in `handle_sigma2`: the ephemeral does not outlive the exchange.
1792            let _ = keys.remove(eph_handle);
1793            self.state = InitiatorState::Failed;
1794            return Err(e);
1795        }
1796
1797        let session = resumption_session_keys(
1798            &previous.shared_secret,
1799            &initiator_random,
1800            &message.resumption_id,
1801        )?;
1802        // The ephemeral was generated for a full exchange that did not happen.
1803        keys.remove(eph_handle)?;
1804        self.state = InitiatorState::Done;
1805
1806        Ok(CaseOutcome {
1807            keys: session,
1808            peer: previous.identity.clone(),
1809            peer_session_id: message.responder_session_id,
1810            peer_session_params: message.session_params,
1811            resumption: ResumptionState {
1812                // The secret carries over; only the identifier is new.
1813                shared_secret: previous.shared_secret.clone(),
1814                resumption_id: message.resumption_id,
1815                fabric_index,
1816                identity: previous.identity.clone(),
1817            },
1818        })
1819    }
1820}
1821
1822impl CaseResponder {
1823    /// Handles a Sigma1 that asks for resumption, writing a `Sigma2_Resume` (§4.14.2.3).
1824    ///
1825    /// `previous` is the remembered state the message's `resumptionID` names — a lookup the
1826    /// caller does, for the same reason the fabric lookup is the caller's.
1827    ///
1828    /// If the MIC does not verify, this returns [`ErrorCode::IntegrityCheckFailed`] and the
1829    /// responder is **still usable**: the caller should fall back to
1830    /// [`CaseResponder::handle_sigma1`] with the same message, which is exactly what
1831    /// §4.14.2.2 requires — "the information included in the Sigma1 with Resumption message
1832    /// SHALL be processed as a Sigma1 message without any resumption fields."
1833    pub fn handle_sigma1_resumption(
1834        &mut self,
1835        sigma1: &Sigma1<'_>,
1836        previous: &ResumptionState,
1837        resumption_random: &[u8; RESUMPTION_ID_LEN],
1838        out: &mut [u8],
1839    ) -> Result<(usize, CaseOutcome)> {
1840        if !matches!(self.state, ResponderState::AwaitingSigma1) {
1841            bail!(InvalidState)
1842        }
1843        let (Some(offered), Some(mic)) = (sigma1.resumption_id, sigma1.initiator_resume_mic) else {
1844            // "If Msg1 contains either a resumptionID or an initiatorResumeMIC field but
1845            // not both" the responder does not resume.
1846            bail!(InvalidArgument)
1847        };
1848        if !ct_eq(&offered, &previous.resumption_id) {
1849            bail!(InvalidArgument)
1850        }
1851
1852        let s1rk = sigma1_resume_key(
1853            &previous.shared_secret,
1854            &sigma1.initiator_random,
1855            &previous.resumption_id,
1856        )?;
1857        let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1858        // A failure here leaves the state machine untouched, so the caller can retry the
1859        // full path with the same Sigma1.
1860        open(&s1rk, &RESUME1_NONCE, &mut empty, &mic)?;
1861
1862        let s2rk = sigma2_resume_key(
1863            &previous.shared_secret,
1864            &sigma1.initiator_random,
1865            resumption_random,
1866        )?;
1867        let mut mic_buf = [0u8; AEAD_MIC_LENGTH_BYTES];
1868        let sigma2_resume_mic =
1869            fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s2rk, &RESUME2_NONCE, &mut mic_buf, 0)?)?;
1870
1871        let message = Sigma2Resume {
1872            resumption_id: *resumption_random,
1873            sigma2_resume_mic,
1874            responder_session_id: self.session_id,
1875            session_params: self.session_params,
1876        };
1877        let len = message.encode(out)?.len();
1878
1879        let keys = resumption_session_keys(
1880            &previous.shared_secret,
1881            &sigma1.initiator_random,
1882            resumption_random,
1883        )?;
1884        self.state = ResponderState::Done;
1885
1886        Ok((
1887            len,
1888            CaseOutcome {
1889                keys,
1890                peer: previous.identity.clone(),
1891                peer_session_id: sigma1.initiator_session_id,
1892                peer_session_params: sigma1.session_params,
1893                resumption: ResumptionState {
1894                    shared_secret: previous.shared_secret.clone(),
1895                    resumption_id: *resumption_random,
1896                    fabric_index: previous.fabric_index,
1897                    identity: previous.identity.clone(),
1898                },
1899            },
1900        ))
1901    }
1902}
1903
1904#[cfg(test)]
1905mod tests {
1906    use super::*;
1907    use crate::sc::SessionParams;
1908
1909    fn a_public_key() -> PublicKey {
1910        let mut k = [0x11u8; PUBLIC_KEY_SIZE_BYTES];
1911        k[0] = 0x04;
1912        PublicKey::from_bytes(k)
1913    }
1914
1915    fn full_sigma1() -> Sigma1<'static> {
1916        Sigma1 {
1917            initiator_random: [1; RANDOM_LEN],
1918            initiator_session_id: SessionId(0x1234),
1919            destination_id: [2; HASH_LEN_BYTES],
1920            initiator_eph_pub_key: a_public_key(),
1921            session_params: Some(SessionParams::announce(
1922                &crate::exchange::MrpParams::default(),
1923            )),
1924            resumption_id: Some([3; RESUMPTION_ID_LEN]),
1925            initiator_resume_mic: Some([4; AEAD_MIC_LENGTH_BYTES]),
1926            encoded: &[],
1927        }
1928    }
1929
1930    #[test]
1931    fn a_nested_structure_does_not_swallow_the_fields_after_it() {
1932        // `session-parameter-struct` is tag 5 and the resumption fields are 6 and 7, so a
1933        // decoder for the nested structure that ran past its own end-of-container would
1934        // consume them. The symptom would be an initiator that announced its MRP parameters
1935        // silently losing its resumption request and falling back to a full handshake —
1936        // a failure with no error raised anywhere, on the path that exists to be fast.
1937        let sigma1 = full_sigma1();
1938        let mut buf = [0u8; MAX_SIGMA1];
1939        let len = sigma1.encode(&mut buf).expect("encode").len();
1940        let mut round = [0u8; MAX_SIGMA1];
1941        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1942        let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1943
1944        assert_eq!(decoded.session_params, sigma1.session_params);
1945        assert_eq!(decoded.resumption_id, sigma1.resumption_id);
1946        assert_eq!(decoded.initiator_resume_mic, sigma1.initiator_resume_mic);
1947        assert!(decoded.is_resumption());
1948    }
1949
1950    #[test]
1951    fn a_sigma1_with_session_params_and_no_resumption_still_reads() {
1952        let mut sigma1 = full_sigma1();
1953        sigma1.resumption_id = None;
1954        sigma1.initiator_resume_mic = None;
1955        let mut buf = [0u8; MAX_SIGMA1];
1956        let len = sigma1.encode(&mut buf).expect("encode").len();
1957        let mut round = [0u8; MAX_SIGMA1];
1958        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1959        let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1960        assert_eq!(decoded.session_params, sigma1.session_params);
1961        assert!(!decoded.is_resumption());
1962    }
1963
1964    #[test]
1965    fn a_duplicate_tag_is_refused() {
1966        // Core §A.5.1: "All member elements within a structure SHALL have a unique tag."
1967        // Letting the last one win would mean two readers could disagree about a message
1968        // that is inside a transcript hash — and both readings would be over the same bytes,
1969        // so the disagreement survives every integrity check there is.
1970        let mut buf = [0u8; MAX_SIGMA1];
1971        let mut w = TlvWriter::new(&mut buf);
1972        w.start_structure(Tag::Anonymous).expect("start");
1973        w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
1974            .expect("random");
1975        w.unsigned(Tag::Context(2), 1).expect("session id");
1976        w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
1977            .expect("destination");
1978        w.octets(Tag::Context(4), a_public_key().as_bytes())
1979            .expect("key");
1980        // A second initiatorRandom.
1981        w.octets(Tag::Context(1), &[9u8; RANDOM_LEN])
1982            .expect("duplicate");
1983        w.end_container().expect("end");
1984        let len = w.finish().expect("finish").len();
1985
1986        let mut round = [0u8; MAX_SIGMA1];
1987        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1988        assert_eq!(
1989            Sigma1::decode(round.get(..len).expect("in range"))
1990                .map(|_| ())
1991                .unwrap_err()
1992                .code(),
1993            ErrorCode::TlvDuplicateTag
1994        );
1995    }
1996
1997    #[test]
1998    fn an_unknown_tag_is_still_skipped() {
1999        // §4.14.2.3: "Any context-specific tags not listed in the above TLV schemas SHALL be
2000        // reserved for future use, and SHALL be silently ignored." Refusing duplicates must
2001        // not turn into refusing extensions.
2002        let mut buf = [0u8; MAX_SIGMA1];
2003        let mut w = TlvWriter::new(&mut buf);
2004        w.start_structure(Tag::Anonymous).expect("start");
2005        w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
2006            .expect("random");
2007        w.unsigned(Tag::Context(2), 1).expect("session id");
2008        w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
2009            .expect("destination");
2010        w.octets(Tag::Context(4), a_public_key().as_bytes())
2011            .expect("key");
2012        w.unsigned(Tag::Context(200), 42)
2013            .expect("a tag from the future");
2014        w.end_container().expect("end");
2015        let len = w.finish().expect("finish").len();
2016
2017        let mut round = [0u8; MAX_SIGMA1];
2018        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
2019        let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
2020        assert_eq!(decoded.initiator_session_id, SessionId(1));
2021    }
2022}