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.5).
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 are
197/// (D3): 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 (D80).
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    /// Handles a Sigma3, verifying the initiator's chain and establishing the session.
1200    ///
1201    /// `root` is the fabric's trusted root certificate; `at` the current Matter `epoch-s`,
1202    /// or `None` on a node without a clock (§6.4.5.1).
1203    pub fn handle_sigma3(
1204        &mut self,
1205        sigma3: &Sigma3<'_>,
1206        root: &MatterCertificate<'_>,
1207        at: Option<u32>,
1208    ) -> Result<CaseOutcome> {
1209        let ResponderState::AwaitingSigma3(state) = &self.state else {
1210            self.state = ResponderState::Failed;
1211            bail!(InvalidState)
1212        };
1213
1214        let mut plaintext = [0u8; MAX_ENCRYPTED3];
1215        let s3k = sigma3_key(&state.shared_secret, &state.ipk, &state.transcript.hash())?;
1216        let decrypted_len = match open(&s3k, &SIGMA3_NONCE, &mut plaintext, sigma3.encrypted3) {
1217            Ok(len) => len,
1218            Err(e) => {
1219                self.state = ResponderState::Failed;
1220                return Err(e);
1221            }
1222        };
1223
1224        let outcome = (|| {
1225            let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
1226            let peer = verify_peer(
1227                &tbe,
1228                root,
1229                at,
1230                state.fabric_id,
1231                // A responder does not know which node is calling it.
1232                None,
1233                &state.initiator_eph_pub_key,
1234                &state.responder_eph_pub_key,
1235            )?;
1236
1237            let mut transcript = state.transcript.clone();
1238            transcript.update(sigma3.encoded());
1239            let keys = session_keys(&state.shared_secret, &state.ipk, &transcript.hash())?;
1240
1241            Ok(CaseOutcome {
1242                keys,
1243                peer: peer.clone(),
1244                peer_session_id: state.initiator_session_id,
1245                peer_session_params: state.initiator_session_params,
1246                resumption: ResumptionState {
1247                    shared_secret: state.shared_secret.clone(),
1248                    resumption_id: state.resumption_id,
1249                    fabric_index: state.fabric_index,
1250                    identity: peer,
1251                },
1252            })
1253        })();
1254
1255        self.state = if outcome.is_ok() {
1256            ResponderState::Done
1257        } else {
1258            ResponderState::Failed
1259        };
1260        outcome
1261    }
1262
1263    /// The `SigmaFinished` a responder sends once Sigma3 has been accepted (Appendix D).
1264    pub fn finished(&self, out: &mut [u8]) -> Result<usize> {
1265        if !matches!(self.state, ResponderState::Done) {
1266            bail!(InvalidState)
1267        }
1268        StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess).encode(out)
1269    }
1270
1271    /// Whether the exchange has failed and the responder must not be reused.
1272    #[must_use]
1273    pub const fn is_failed(&self) -> bool {
1274        matches!(self.state, ResponderState::Failed)
1275    }
1276}
1277
1278// --- Initiator --------------------------------------------------------------------------
1279
1280/// The commissioner or controller side of CASE (§4.14.2.3).
1281#[derive(Debug)]
1282pub struct CaseInitiator {
1283    session_id: SessionId,
1284    session_params: Option<SessionParams>,
1285    state: InitiatorState,
1286}
1287
1288/// As with [`ResponderState`], the size is the state a half-finished exchange must hold.
1289#[expect(
1290    clippy::large_enum_variant,
1291    reason = "no allocator, and the state is transient"
1292)]
1293#[derive(Debug)]
1294enum InitiatorState {
1295    Start,
1296    AwaitingSigma2(Box1),
1297    Done,
1298    Failed,
1299}
1300
1301/// The initiator's state between Sigma1 and Sigma2.
1302#[derive(Debug)]
1303struct Box1 {
1304    initiator_random: [u8; RANDOM_LEN],
1305    eph_handle: KeyHandle,
1306    initiator_eph_pub_key: PublicKey,
1307    ipk: SymmetricKey,
1308    fabric_index: crate::msg::FabricIndex,
1309    /// The fabric the Sigma1 was built for, so the responder's NOC can be held to it.
1310    fabric_id: crate::msg::FabricId,
1311    /// The node the destination identifier addressed. §4.14.2.3 step 5a requires the
1312    /// responder's NOC to be for exactly this node.
1313    peer_node_id: crate::msg::NodeId,
1314    transcript: Transcript,
1315}
1316
1317impl CaseInitiator {
1318    /// An initiator that will listen on `session_id`.
1319    #[must_use]
1320    pub fn new(session_id: SessionId, session_params: Option<SessionParams>) -> Self {
1321        Self {
1322            session_id,
1323            session_params,
1324            state: InitiatorState::Start,
1325        }
1326    }
1327
1328    /// Builds a Sigma1 addressed to `peer_node_id` on `fabric`.
1329    pub fn start<K: KeyStore>(
1330        &mut self,
1331        fabric: &Fabric,
1332        peer_node_id: crate::msg::NodeId,
1333        keys: &mut K,
1334        initiator_random: &[u8; RANDOM_LEN],
1335        ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1336        out: &mut [u8],
1337    ) -> Result<usize> {
1338        if !matches!(self.state, InitiatorState::Start) {
1339            bail!(InvalidState)
1340        }
1341        // The destination identifier names the peer, not this node — that is the point:
1342        // the responder recognises itself in it without either end saying a node id aloud.
1343        let destination_id = crate::fabric::destination_identifier(
1344            &fabric.ipk,
1345            initiator_random,
1346            &fabric.root_public_key,
1347            fabric.fabric_id,
1348            peer_node_id,
1349        )?;
1350        let (eph_handle, initiator_eph_pub_key) =
1351            keys.generate(KeyPurpose::Ephemeral, ephemeral_random)?;
1352
1353        let sigma1 = Sigma1 {
1354            initiator_random: *initiator_random,
1355            initiator_session_id: self.session_id,
1356            destination_id,
1357            initiator_eph_pub_key,
1358            session_params: self.session_params,
1359            resumption_id: None,
1360            initiator_resume_mic: None,
1361            encoded: &[],
1362        };
1363        let len = sigma1.encode(out)?.len();
1364        let mut transcript = Transcript::new();
1365        transcript.update(out.get(..len).ok_or_else(parse_error)?);
1366
1367        self.state = InitiatorState::AwaitingSigma2(Box1 {
1368            initiator_random: *initiator_random,
1369            eph_handle,
1370            initiator_eph_pub_key,
1371            ipk: fabric.ipk.clone(),
1372            fabric_index: fabric.index,
1373            fabric_id: fabric.fabric_id,
1374            peer_node_id,
1375            transcript,
1376        });
1377        Ok(len)
1378    }
1379
1380    /// Handles a Sigma2, verifies the responder, and writes a Sigma3.
1381    ///
1382    /// Returns the length of the Sigma3 and the established session — the initiator's keys
1383    /// are complete the moment it has sent Sigma3, before the `SigmaFinished` arrives,
1384    /// because the transcript is complete at that point.
1385    #[expect(
1386        clippy::too_many_arguments,
1387        reason = "see CaseResponder::handle_sigma1"
1388    )]
1389    pub fn handle_sigma2<K: KeyStore>(
1390        &mut self,
1391        sigma2: &Sigma2<'_>,
1392        fabric: &Fabric,
1393        root: &MatterCertificate<'_>,
1394        noc: &[u8],
1395        icac: Option<&[u8]>,
1396        keys: &mut K,
1397        at: Option<u32>,
1398        out: &mut [u8],
1399    ) -> Result<(usize, CaseOutcome)> {
1400        let result = self.build_sigma3(sigma2, fabric, root, noc, icac, keys, at, out);
1401        if result.is_err() {
1402            // The exchange is over either way, so the ephemeral must not outlive it: a key
1403            // store has a fixed number of slots and a controller that retries a failing
1404            // peer would otherwise exhaust them. `build_sigma3` destroys it on success.
1405            if let InitiatorState::AwaitingSigma2(state) = &self.state {
1406                let _ = keys.remove(state.eph_handle);
1407            }
1408            self.state = InitiatorState::Failed;
1409        }
1410        result
1411    }
1412
1413    #[expect(
1414        clippy::too_many_arguments,
1415        reason = "see CaseResponder::handle_sigma1"
1416    )]
1417    fn build_sigma3<K: KeyStore>(
1418        &mut self,
1419        sigma2: &Sigma2<'_>,
1420        fabric: &Fabric,
1421        root: &MatterCertificate<'_>,
1422        noc: &[u8],
1423        icac: Option<&[u8]>,
1424        keys: &mut K,
1425        at: Option<u32>,
1426        out: &mut [u8],
1427    ) -> Result<(usize, CaseOutcome)> {
1428        let InitiatorState::AwaitingSigma2(state) = &self.state else {
1429            bail!(InvalidState)
1430        };
1431
1432        let shared_secret = keys.ecdh(state.eph_handle, &sigma2.responder_eph_pub_key)?;
1433        let s2k = sigma2_key(
1434            &shared_secret,
1435            &state.ipk,
1436            &sigma2.responder_random,
1437            &sigma2.responder_eph_pub_key,
1438            &state.transcript.hash(),
1439        )?;
1440
1441        let mut plaintext = [0u8; MAX_ENCRYPTED2];
1442        let decrypted_len = open(&s2k, &SIGMA2_NONCE, &mut plaintext, sigma2.encrypted2)?;
1443        let tbe = TbeData::decode(plaintext.get(..decrypted_len).ok_or_else(parse_error)?)?;
1444        let peer = verify_peer(
1445            &tbe,
1446            root,
1447            at,
1448            state.fabric_id,
1449            Some(state.peer_node_id),
1450            &sigma2.responder_eph_pub_key,
1451            &state.initiator_eph_pub_key,
1452        )?;
1453        // A Sigma2 without a resumption ID cannot be resumed later, and the schema makes it
1454        // mandatory, so its absence is a malformed message rather than a missing option.
1455        let resumption_id = tbe.resumption_id.ok_or_else(parse_error)?;
1456
1457        let mut transcript = state.transcript.clone();
1458        transcript.update(sigma2.encoded());
1459
1460        // sigma-3-tbsdata: own chain, own ephemeral, then the peer's — the mirror of
1461        // Sigma2's, and the reason a Sigma2 signature cannot be replayed here.
1462        let mut tbs = [0u8; MAX_TBSDATA];
1463        let tbsdata = encode_tbsdata(
1464            noc,
1465            icac,
1466            &state.initiator_eph_pub_key,
1467            &sigma2.responder_eph_pub_key,
1468            &mut tbs,
1469        )?;
1470        let signature = keys.sign(fabric.operational_key, tbsdata)?;
1471
1472        let tbe3 = TbeData {
1473            noc,
1474            icac,
1475            signature,
1476            resumption_id: None,
1477        };
1478        let mut encrypted = [0u8; MAX_ENCRYPTED3];
1479        let plaintext_len = tbe3.encode(&mut encrypted)?.len();
1480        let s3k = sigma3_key(&shared_secret, &state.ipk, &transcript.hash())?;
1481        let encrypted3 = seal(&s3k, &SIGMA3_NONCE, &mut encrypted, plaintext_len)?;
1482
1483        let len = Sigma3::encode(encrypted3, out)?.len();
1484        transcript.update(out.get(..len).ok_or_else(parse_error)?);
1485
1486        let session = session_keys(&shared_secret, &state.ipk, &transcript.hash())?;
1487        let fabric_index = state.fabric_index;
1488
1489        keys.remove(state.eph_handle)?;
1490        self.state = InitiatorState::Done;
1491
1492        Ok((
1493            len,
1494            CaseOutcome {
1495                keys: session,
1496                peer: peer.clone(),
1497                peer_session_id: sigma2.responder_session_id,
1498                peer_session_params: sigma2.session_params,
1499                resumption: ResumptionState {
1500                    shared_secret,
1501                    resumption_id,
1502                    fabric_index,
1503                    identity: peer,
1504                },
1505            },
1506        ))
1507    }
1508
1509    /// Checks the responder's `SigmaFinished`.
1510    ///
1511    /// A `StatusReport` that is anything other than
1512    /// `SUCCESS`/`SESSION_ESTABLISHMENT_SUCCESS` means the responder rejected the Sigma3,
1513    /// and the session this node already derived keys for must be discarded.
1514    pub fn accept_finished(&mut self, report: &[u8]) -> Result<()> {
1515        let report = StatusReport::decode(report)?;
1516        if report.is_success()
1517            && report.secure_channel_code() == Some(SecureChannelCode::SessionEstablishmentSuccess)
1518        {
1519            Ok(())
1520        } else {
1521            self.state = InitiatorState::Failed;
1522            Err(Error::new(ErrorCode::InvalidState))
1523        }
1524    }
1525
1526    /// Whether the exchange has failed.
1527    #[must_use]
1528    pub const fn is_failed(&self) -> bool {
1529        matches!(self.state, InitiatorState::Failed)
1530    }
1531}
1532
1533/// Verifies a peer's chain, its identity and its signature over the `tbsdata` it should have
1534/// signed.
1535///
1536/// `expected_fabric` is the fabric the destination identifier selected. `expected_node` is
1537/// set only for a Sigma2, and the asymmetry is the specification's:
1538///
1539/// * §4.14.2.3's *Validate Sigma2* step 5a — "The Fabric ID **and Node ID** SHALL match the
1540///   intended identity of the receiver Node, as included in the computation of the
1541///   Destination Identifier when generating Sigma1." Without this, any node holding a valid
1542///   NOC on the same fabric could answer in place of the one that was addressed, and the
1543///   initiator would establish a perfectly sound session with the wrong device.
1544/// * *Validate Sigma3* step 4a — "The **Fabric ID** SHALL match the Fabric ID matched during
1545///   processing of the Destination Identifier". A responder does not know which node is
1546///   calling it, so there is no node id to check; any node on the fabric may connect, and
1547///   what it is then allowed to do is `acl`'s decision.
1548///
1549/// The order matters: the chain is verified before the signature, so a forged chain is
1550/// rejected before its public key is trusted for anything.
1551fn verify_peer(
1552    tbe: &TbeData<'_>,
1553    root: &MatterCertificate<'_>,
1554    at: Option<u32>,
1555    expected_fabric: crate::msg::FabricId,
1556    expected_node: Option<crate::msg::NodeId>,
1557    signer_eph_pub_key: &PublicKey,
1558    peer_eph_pub_key: &PublicKey,
1559) -> Result<VerifiedIdentity> {
1560    let noc = MatterCertificate::decode(tbe.noc)?;
1561    let icac = match tbe.icac {
1562        Some(bytes) => Some(MatterCertificate::decode(bytes)?),
1563        None => None,
1564    };
1565    // `verify_chain` applies the DN encoding rules (step d), the fabric-id agreement between
1566    // the chain's certificates (step b) and the chain back to the trusted root (step c).
1567    let identity = verify_chain(&noc, icac.as_ref(), root, at)?;
1568
1569    if identity.fabric_id != expected_fabric {
1570        bail!(CertPathInvalid)
1571    }
1572    if expected_node.is_some_and(|expected| identity.node_id != expected) {
1573        bail!(CertPathInvalid)
1574    }
1575
1576    let mut tbs = [0u8; MAX_TBSDATA];
1577    let tbsdata = encode_tbsdata(
1578        tbe.noc,
1579        tbe.icac,
1580        signer_eph_pub_key,
1581        peer_eph_pub_key,
1582        &mut tbs,
1583    )?;
1584    if !verify(&noc.public_key, tbsdata, &tbe.signature)? {
1585        bail!(CertPathInvalid)
1586    }
1587    Ok(identity)
1588}
1589
1590// --- Resumption (§4.14.2.2) ---------------------------------------------------------------
1591
1592impl CaseInitiator {
1593    /// Builds a Sigma1 that asks to resume `previous` (§4.14.2.3).
1594    ///
1595    /// It is still a complete Sigma1: if the responder has forgotten the session, it
1596    /// "SHALL be processed as a Sigma1 message without any resumption fields", and the
1597    /// exchange falls through to the full protocol without a round trip lost. So the
1598    /// ephemeral key and the destination identifier are built exactly as
1599    /// [`CaseInitiator::start`] builds them, and the resumption fields are added on top.
1600    #[expect(
1601        clippy::too_many_arguments,
1602        reason = "see CaseResponder::handle_sigma1"
1603    )]
1604    pub fn start_resumption<K: KeyStore>(
1605        &mut self,
1606        fabric: &Fabric,
1607        peer_node_id: crate::msg::NodeId,
1608        previous: &ResumptionState,
1609        keys: &mut K,
1610        initiator_random: &[u8; RANDOM_LEN],
1611        ephemeral_random: &[u8; GROUP_SIZE_BYTES],
1612        out: &mut [u8],
1613    ) -> Result<usize> {
1614        let len = self.start(
1615            fabric,
1616            peer_node_id,
1617            keys,
1618            initiator_random,
1619            ephemeral_random,
1620            out,
1621        )?;
1622
1623        // The MIC is an AEAD over *nothing* — "Resume1MIC_P[] = {}", "Resume1MIC_A[] = {}"
1624        // — so it proves only one thing, which is the thing that matters: that this peer
1625        // holds the previous session's shared secret.
1626        let s1rk = sigma1_resume_key(
1627            &previous.shared_secret,
1628            initiator_random,
1629            &previous.resumption_id,
1630        )?;
1631        let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1632        let mic = fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s1rk, &RESUME1_NONCE, &mut empty, 0)?)?;
1633
1634        let mut sigma1 = Sigma1::decode(out.get(..len).ok_or_else(parse_error)?)?;
1635        sigma1.resumption_id = Some(previous.resumption_id);
1636        sigma1.initiator_resume_mic = Some(mic);
1637
1638        // Re-encoding into the same buffer would alias the borrow the decode holds, so the
1639        // message is rebuilt beside it and copied back.
1640        let mut rebuilt = [0u8; MAX_SIGMA1];
1641        let encoded = sigma1.encode(&mut rebuilt)?;
1642        let new_len = encoded.len();
1643        out.get_mut(..new_len)
1644            .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?
1645            .copy_from_slice(encoded);
1646
1647        // The transcript covers the message that actually went out, resumption fields and
1648        // all — it would be the wrong hash otherwise if the responder declines to resume.
1649        if let InitiatorState::AwaitingSigma2(state) = &mut self.state {
1650            state.transcript = Transcript::new();
1651            state
1652                .transcript
1653                .update(out.get(..new_len).ok_or_else(parse_error)?);
1654        }
1655        Ok(new_len)
1656    }
1657
1658    /// Handles a `Sigma2_Resume`, completing a resumed session (§4.14.2.3).
1659    ///
1660    /// The peer's identity is carried over from `previous` rather than re-derived: a
1661    /// resumption proves possession of the old session's secret, which only the peer that
1662    /// authenticated then could hold, so the identity it established still stands.
1663    pub fn accept_resume<K: KeyStore>(
1664        &mut self,
1665        message: &Sigma2Resume,
1666        previous: &ResumptionState,
1667        keys: &mut K,
1668    ) -> Result<CaseOutcome> {
1669        let InitiatorState::AwaitingSigma2(state) = &self.state else {
1670            bail!(InvalidState)
1671        };
1672        let initiator_random = state.initiator_random;
1673        let eph_handle = state.eph_handle;
1674        let fabric_index = state.fabric_index;
1675
1676        let s2rk = sigma2_resume_key(
1677            &previous.shared_secret,
1678            &initiator_random,
1679            &message.resumption_id,
1680        )?;
1681        let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1682        if let Err(e) = open(
1683            &s2rk,
1684            &RESUME2_NONCE,
1685            &mut empty,
1686            &message.sigma2_resume_mic,
1687        ) {
1688            // As in `handle_sigma2`: the ephemeral does not outlive the exchange.
1689            let _ = keys.remove(eph_handle);
1690            self.state = InitiatorState::Failed;
1691            return Err(e);
1692        }
1693
1694        let session = resumption_session_keys(
1695            &previous.shared_secret,
1696            &initiator_random,
1697            &message.resumption_id,
1698        )?;
1699        // The ephemeral was generated for a full exchange that did not happen.
1700        keys.remove(eph_handle)?;
1701        self.state = InitiatorState::Done;
1702
1703        Ok(CaseOutcome {
1704            keys: session,
1705            peer: previous.identity.clone(),
1706            peer_session_id: message.responder_session_id,
1707            peer_session_params: message.session_params,
1708            resumption: ResumptionState {
1709                // The secret carries over; only the identifier is new.
1710                shared_secret: previous.shared_secret.clone(),
1711                resumption_id: message.resumption_id,
1712                fabric_index,
1713                identity: previous.identity.clone(),
1714            },
1715        })
1716    }
1717}
1718
1719impl CaseResponder {
1720    /// Handles a Sigma1 that asks for resumption, writing a `Sigma2_Resume` (§4.14.2.3).
1721    ///
1722    /// `previous` is the remembered state the message's `resumptionID` names — a lookup the
1723    /// caller does, for the same reason the fabric lookup is the caller's.
1724    ///
1725    /// If the MIC does not verify, this returns [`ErrorCode::IntegrityCheckFailed`] and the
1726    /// responder is **still usable**: the caller should fall back to
1727    /// [`CaseResponder::handle_sigma1`] with the same message, which is exactly what
1728    /// §4.14.2.2 requires — "the information included in the Sigma1 with Resumption message
1729    /// SHALL be processed as a Sigma1 message without any resumption fields."
1730    pub fn handle_sigma1_resumption(
1731        &mut self,
1732        sigma1: &Sigma1<'_>,
1733        previous: &ResumptionState,
1734        resumption_random: &[u8; RESUMPTION_ID_LEN],
1735        out: &mut [u8],
1736    ) -> Result<(usize, CaseOutcome)> {
1737        if !matches!(self.state, ResponderState::AwaitingSigma1) {
1738            bail!(InvalidState)
1739        }
1740        let (Some(offered), Some(mic)) = (sigma1.resumption_id, sigma1.initiator_resume_mic) else {
1741            // "If Msg1 contains either a resumptionID or an initiatorResumeMIC field but
1742            // not both" the responder does not resume.
1743            bail!(InvalidArgument)
1744        };
1745        if !ct_eq(&offered, &previous.resumption_id) {
1746            bail!(InvalidArgument)
1747        }
1748
1749        let s1rk = sigma1_resume_key(
1750            &previous.shared_secret,
1751            &sigma1.initiator_random,
1752            &previous.resumption_id,
1753        )?;
1754        let mut empty = [0u8; AEAD_MIC_LENGTH_BYTES];
1755        // A failure here leaves the state machine untouched, so the caller can retry the
1756        // full path with the same Sigma1.
1757        open(&s1rk, &RESUME1_NONCE, &mut empty, &mic)?;
1758
1759        let s2rk = sigma2_resume_key(
1760            &previous.shared_secret,
1761            &sigma1.initiator_random,
1762            resumption_random,
1763        )?;
1764        let mut mic_buf = [0u8; AEAD_MIC_LENGTH_BYTES];
1765        let sigma2_resume_mic =
1766            fixed::<AEAD_MIC_LENGTH_BYTES>(seal(&s2rk, &RESUME2_NONCE, &mut mic_buf, 0)?)?;
1767
1768        let message = Sigma2Resume {
1769            resumption_id: *resumption_random,
1770            sigma2_resume_mic,
1771            responder_session_id: self.session_id,
1772            session_params: self.session_params,
1773        };
1774        let len = message.encode(out)?.len();
1775
1776        let keys = resumption_session_keys(
1777            &previous.shared_secret,
1778            &sigma1.initiator_random,
1779            resumption_random,
1780        )?;
1781        self.state = ResponderState::Done;
1782
1783        Ok((
1784            len,
1785            CaseOutcome {
1786                keys,
1787                peer: previous.identity.clone(),
1788                peer_session_id: sigma1.initiator_session_id,
1789                peer_session_params: sigma1.session_params,
1790                resumption: ResumptionState {
1791                    shared_secret: previous.shared_secret.clone(),
1792                    resumption_id: *resumption_random,
1793                    fabric_index: previous.fabric_index,
1794                    identity: previous.identity.clone(),
1795                },
1796            },
1797        ))
1798    }
1799}
1800
1801#[cfg(test)]
1802mod tests {
1803    use super::*;
1804    use crate::sc::SessionParams;
1805
1806    fn a_public_key() -> PublicKey {
1807        let mut k = [0x11u8; PUBLIC_KEY_SIZE_BYTES];
1808        k[0] = 0x04;
1809        PublicKey::from_bytes(k)
1810    }
1811
1812    fn full_sigma1() -> Sigma1<'static> {
1813        Sigma1 {
1814            initiator_random: [1; RANDOM_LEN],
1815            initiator_session_id: SessionId(0x1234),
1816            destination_id: [2; HASH_LEN_BYTES],
1817            initiator_eph_pub_key: a_public_key(),
1818            session_params: Some(SessionParams::announce(
1819                &crate::exchange::MrpParams::default(),
1820            )),
1821            resumption_id: Some([3; RESUMPTION_ID_LEN]),
1822            initiator_resume_mic: Some([4; AEAD_MIC_LENGTH_BYTES]),
1823            encoded: &[],
1824        }
1825    }
1826
1827    #[test]
1828    fn a_nested_structure_does_not_swallow_the_fields_after_it() {
1829        // `session-parameter-struct` is tag 5 and the resumption fields are 6 and 7, so a
1830        // decoder for the nested structure that ran past its own end-of-container would
1831        // consume them. The symptom would be an initiator that announced its MRP parameters
1832        // silently losing its resumption request and falling back to a full handshake —
1833        // a failure with no error raised anywhere, on the path that exists to be fast.
1834        let sigma1 = full_sigma1();
1835        let mut buf = [0u8; MAX_SIGMA1];
1836        let len = sigma1.encode(&mut buf).expect("encode").len();
1837        let mut round = [0u8; MAX_SIGMA1];
1838        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1839        let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1840
1841        assert_eq!(decoded.session_params, sigma1.session_params);
1842        assert_eq!(decoded.resumption_id, sigma1.resumption_id);
1843        assert_eq!(decoded.initiator_resume_mic, sigma1.initiator_resume_mic);
1844        assert!(decoded.is_resumption());
1845    }
1846
1847    #[test]
1848    fn a_sigma1_with_session_params_and_no_resumption_still_reads() {
1849        let mut sigma1 = full_sigma1();
1850        sigma1.resumption_id = None;
1851        sigma1.initiator_resume_mic = None;
1852        let mut buf = [0u8; MAX_SIGMA1];
1853        let len = sigma1.encode(&mut buf).expect("encode").len();
1854        let mut round = [0u8; MAX_SIGMA1];
1855        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1856        let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1857        assert_eq!(decoded.session_params, sigma1.session_params);
1858        assert!(!decoded.is_resumption());
1859    }
1860
1861    #[test]
1862    fn a_duplicate_tag_is_refused() {
1863        // Core §A.5.1: "All member elements within a structure SHALL have a unique tag."
1864        // Letting the last one win would mean two readers could disagree about a message
1865        // that is inside a transcript hash — and both readings would be over the same bytes,
1866        // so the disagreement survives every integrity check there is.
1867        let mut buf = [0u8; MAX_SIGMA1];
1868        let mut w = TlvWriter::new(&mut buf);
1869        w.start_structure(Tag::Anonymous).expect("start");
1870        w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
1871            .expect("random");
1872        w.unsigned(Tag::Context(2), 1).expect("session id");
1873        w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
1874            .expect("destination");
1875        w.octets(Tag::Context(4), a_public_key().as_bytes())
1876            .expect("key");
1877        // A second initiatorRandom.
1878        w.octets(Tag::Context(1), &[9u8; RANDOM_LEN])
1879            .expect("duplicate");
1880        w.end_container().expect("end");
1881        let len = w.finish().expect("finish").len();
1882
1883        let mut round = [0u8; MAX_SIGMA1];
1884        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1885        assert_eq!(
1886            Sigma1::decode(round.get(..len).expect("in range"))
1887                .map(|_| ())
1888                .unwrap_err()
1889                .code(),
1890            ErrorCode::TlvDuplicateTag
1891        );
1892    }
1893
1894    #[test]
1895    fn an_unknown_tag_is_still_skipped() {
1896        // §4.14.2.3: "Any context-specific tags not listed in the above TLV schemas SHALL be
1897        // reserved for future use, and SHALL be silently ignored." Refusing duplicates must
1898        // not turn into refusing extensions.
1899        let mut buf = [0u8; MAX_SIGMA1];
1900        let mut w = TlvWriter::new(&mut buf);
1901        w.start_structure(Tag::Anonymous).expect("start");
1902        w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
1903            .expect("random");
1904        w.unsigned(Tag::Context(2), 1).expect("session id");
1905        w.octets(Tag::Context(3), &[2u8; HASH_LEN_BYTES])
1906            .expect("destination");
1907        w.octets(Tag::Context(4), a_public_key().as_bytes())
1908            .expect("key");
1909        w.unsigned(Tag::Context(200), 42)
1910            .expect("a tag from the future");
1911        w.end_container().expect("end");
1912        let len = w.finish().expect("finish").len();
1913
1914        let mut round = [0u8; MAX_SIGMA1];
1915        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1916        let decoded = Sigma1::decode(round.get(..len).expect("in range")).expect("decode");
1917        assert_eq!(decoded.initiator_session_id, SessionId(1));
1918    }
1919}