Skip to main content

matter_kit/
session.rs

1//! Secure sessions: what PASE and CASE produce, and what every later message rides on
2//! (Core §4.13).
3//!
4//! A session is a pair of directional keys plus the bookkeeping that makes them safe to
5//! use: a counter that never repeats, a replay window for the peer's counters, and the
6//! identity the peer proved. Both PASE and CASE end by installing one.
7//!
8//! # Directional keys, and the trap in them
9//!
10//! Session establishment produces **two** keys — `I2RKey` for initiator-to-responder and
11//! `R2IKey` for the other way — and which one a node encrypts with depends on which end it
12//! was. §4.14.1: "The initiator SHALL use I2RKey to encrypt … and the R2IKey to decrypt …
13//! The responder SHALL use R2IKey to encrypt … and the I2RKey to decrypt."
14//!
15//! Getting that backwards produces a node that cannot talk to anything and can talk
16//! perfectly to *itself*, so it survives every test written against another instance of the
17//! same bug. [`SecureSession::encrypt_keys`] and [`SecureSession::decrypt_keys`] pick from
18//! the recorded [`Role`], so the choice is made once, in one place.
19
20use core::marker::PhantomData;
21
22use heapless::Vec;
23
24use crate::config::{AssertValid, Config};
25use crate::crypto::{SymmetricKey, kdf};
26use crate::error::{Error, ErrorCode, Result};
27use crate::exchange::MrpParams;
28use crate::msg::{
29    CounterKind, CounterWindow, FabricIndex, MessageCounter, NodeId, NonceSource, SessionId,
30    SessionKeys, Verdict,
31};
32use crate::platform::Instant;
33
34/// `SEKeys_Info` — "SessionKeys" (Core §4.14.1, §4.14.2.7).
35pub const SESSION_KEYS_INFO: &[u8] = b"SessionKeys";
36
37/// How a session was established.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum SessionKind {
40    /// PASE — from a passcode, during commissioning. Has no fabric and no operational
41    /// identity: the peer has proved it knows the passcode and nothing more.
42    Pase,
43    /// CASE — from operational certificates. The peer's Node ID is proved.
44    Case,
45}
46
47/// Which end of session establishment this node was.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub enum Role {
50    /// This node started it, and encrypts with `I2RKey`.
51    Initiator,
52    /// The peer started it, and this node encrypts with `R2IKey`.
53    Responder,
54}
55
56/// The three keys session establishment derives (§4.14.1, §4.14.2.7).
57///
58/// `I2RKey || R2IKey || AttestationChallenge`, in one KDF call.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct EstablishedKeys {
61    /// Initiator to responder.
62    pub i2r: SessionKeys,
63    /// Responder to initiator.
64    pub r2i: SessionKeys,
65    /// "SHALL only be used as a challenge during device attestation" (§6.2.3) — never as
66    /// an encryption key, which is why it is a distinct field and not a third `SessionKeys`.
67    pub attestation_challenge: SymmetricKey,
68}
69
70impl EstablishedKeys {
71    /// The keys this node **encrypts** with, given which end of establishment it was.
72    ///
73    /// §4.14.2.7 names the two directions `I2RKey` and `R2IKey`, and which one a node uses
74    /// depends entirely on its role. Swapping them does not fail loudly — it produces a
75    /// message the peer cannot authenticate, which looks like a corrupt link rather than a
76    /// key mix-up. Naming the two directions is what keeps the question from being asked at
77    /// every call site.
78    #[must_use]
79    pub const fn sending(&self, role: Role) -> &crate::msg::SessionKeys {
80        match role {
81            Role::Initiator => &self.i2r,
82            Role::Responder => &self.r2i,
83        }
84    }
85
86    /// The keys this node **decrypts** with — the other direction from [`Self::sending`].
87    #[must_use]
88    pub const fn receiving(&self, role: Role) -> &crate::msg::SessionKeys {
89        match role {
90            Role::Initiator => &self.r2i,
91            Role::Responder => &self.i2r,
92        }
93    }
94
95    /// Derives all three from a shared secret and a salt, under `"SessionKeys"`.
96    ///
97    /// PASE passes an empty salt and `Ke`; CASE passes `IPK || TranscriptHash` and the
98    /// ECDH shared secret. Both call the same KDF with the same info string, which is why
99    /// this is one function rather than two that could drift apart.
100    pub fn derive(shared_secret: &[u8], salt: &[u8]) -> Result<Self> {
101        Self::derive_with_info(shared_secret, salt, SESSION_KEYS_INFO)
102    }
103
104    /// The same derivation under a different `Info`.
105    ///
106    /// CASE resumption uses `"SessionResumptionKeys"` (§4.14.2.6.7) — the same three keys,
107    /// the same split, a different label, so that a resumed session's keys can never
108    /// collide with a fresh one's even if a secret and salt were somehow repeated.
109    pub fn derive_with_info(shared_secret: &[u8], salt: &[u8], info: &[u8]) -> Result<Self> {
110        const KEY: usize = crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES;
111        let mut out = [0u8; 3 * KEY];
112        kdf(shared_secret, salt, info, &mut out)?;
113
114        let (Some(i2r), Some(r2i), Some(challenge)) = (
115            out.get(..KEY),
116            out.get(KEY..2 * KEY),
117            out.get(2 * KEY..3 * KEY),
118        ) else {
119            return Err(Error::new(ErrorCode::Platform));
120        };
121        let keys = Self {
122            i2r: SessionKeys::from_encryption_key(SymmetricKey::from_slice(i2r)?)?,
123            r2i: SessionKeys::from_encryption_key(SymmetricKey::from_slice(r2i)?)?,
124            attestation_challenge: SymmetricKey::from_slice(challenge)?,
125        };
126
127        use zeroize::Zeroize as _;
128        out.zeroize();
129        Ok(keys)
130    }
131}
132
133/// One established secure session (§4.13.2).
134#[derive(Debug)]
135pub struct SecureSession {
136    /// The id *this node* chose, and the one peers put in messages to it.
137    pub local_session_id: SessionId,
138    /// The id the *peer* chose, which this node puts in messages to it.
139    pub peer_session_id: SessionId,
140    /// PASE or CASE.
141    pub kind: SessionKind,
142    /// Which end this node was, which decides the key direction.
143    pub role: Role,
144    /// The peer's operational Node ID. Meaningless for PASE, where nothing has proved an
145    /// identity yet, so it is [`NodeId::UNSPECIFIED`] there.
146    pub peer_node_id: NodeId,
147    /// The CASE Authenticated Tags the peer's operational certificate carried (§6.6.2.1.2).
148    ///
149    /// Kept on the session because §6.6.6.3 derives the access-control subject from *session
150    /// metadata*, never from the message — and the certificate that proved them is gone by the
151    /// time an interaction arrives. At most three: §6.5.6 allows a NOC no more.
152    pub peer_cats: heapless::Vec<crate::msg::CaseAuthenticatedTag, 3>,
153    /// This node's own Node ID on the session's fabric.
154    pub local_node_id: NodeId,
155    /// The fabric, or [`FabricIndex::NONE`] for PASE.
156    pub fabric_index: FabricIndex,
157    /// The keys, both directions.
158    pub keys: EstablishedKeys,
159    /// This node's outgoing counter for this session.
160    pub counter: MessageCounter,
161    /// The peer's counters already seen (§4.6.5).
162    pub window: CounterWindow,
163    /// The peer's MRP parameters, from discovery or session establishment.
164    pub mrp: MrpParams,
165    /// "A timestamp indicating the time at which the last message was sent or received."
166    pub session_timestamp: Instant,
167    /// "A timestamp indicating the time at which the last message was received." Drives
168    /// `PeerActiveMode`.
169    pub active_timestamp: Instant,
170    /// Where the peer was when it last sent on this session.
171    ///
172    /// §4.12.4 needs the transport to decide whether MRP runs at all, and a node that starts
173    /// an exchange of its own — a subscription report (§8.5.3), a BDX transfer, any command a
174    /// controller sends — needs an address to send to. An exchange the *peer* opened learns
175    /// this from the datagram that opened it; one this node opens has nothing to learn it
176    /// from, so the session remembers.
177    ///
178    /// `None` until a message has arrived, which for a session established by this node's own
179    /// handshake means the handshake's last message.
180    pub peer: Option<crate::platform::Peer>,
181}
182
183impl SecureSession {
184    /// Builds a session from what establishment produced.
185    ///
186    /// `initial_counter` is a full-width random word from [`Rng`](crate::platform::Rng);
187    /// [`MessageCounter::new`] narrows it to the range §4.6.1.1 specifies, so no caller has to
188    /// know that a message counter does not start just anywhere.
189    #[must_use]
190    pub fn new(
191        local_session_id: SessionId,
192        peer_session_id: SessionId,
193        kind: SessionKind,
194        role: Role,
195        keys: EstablishedKeys,
196        initial_counter: u32,
197        now: Instant,
198    ) -> Self {
199        Self {
200            local_session_id,
201            peer_session_id,
202            kind,
203            role,
204            peer_node_id: NodeId::UNSPECIFIED,
205            peer_cats: heapless::Vec::new(),
206            local_node_id: NodeId::UNSPECIFIED,
207            fabric_index: FabricIndex::NONE,
208            keys,
209            counter: MessageCounter::new(initial_counter),
210            // A secure unicast session's counter never rolls over (§4.6.5.2.1).
211            window: CounterWindow::new(CounterKind::SecureUnicast),
212            mrp: MrpParams::default(),
213            session_timestamp: now,
214            active_timestamp: now,
215            peer: None,
216        }
217    }
218
219    /// The keys this node encrypts with (§4.14.1).
220    #[must_use]
221    pub const fn encrypt_keys(&self) -> &SessionKeys {
222        match self.role {
223            Role::Initiator => &self.keys.i2r,
224            Role::Responder => &self.keys.r2i,
225        }
226    }
227
228    /// The keys this node decrypts with — the other direction.
229    #[must_use]
230    pub const fn decrypt_keys(&self) -> &SessionKeys {
231        match self.role {
232            Role::Initiator => &self.keys.r2i,
233            Role::Responder => &self.keys.i2r,
234        }
235    }
236
237    /// Where the AEAD nonce's Source Node ID comes from, for messages this node *sends*.
238    ///
239    /// §4.8.1.1: a PASE session always uses the Unspecified Node ID; a CASE session uses
240    /// the operational Node ID of whoever protected the message, which for an outgoing
241    /// message is this node.
242    #[must_use]
243    pub const fn send_nonce_source(&self) -> NonceSource {
244        match self.kind {
245            SessionKind::Pase => NonceSource::Pase,
246            SessionKind::Case => NonceSource::Case(self.local_node_id),
247        }
248    }
249
250    /// Where the nonce's Source Node ID comes from for messages this node *receives* — the
251    /// peer protected those, so it is the peer's id.
252    #[must_use]
253    pub const fn recv_nonce_source(&self) -> NonceSource {
254        match self.kind {
255            SessionKind::Pase => NonceSource::Pase,
256            SessionKind::Case => NonceSource::Case(self.peer_node_id),
257        }
258    }
259
260    /// Takes the next outgoing message counter, and marks the session used.
261    pub fn next_counter(&mut self, now: Instant) -> Result<u32> {
262        self.session_timestamp = now;
263        self.counter.take()
264    }
265
266    /// Judges an incoming counter and, if it is new, marks the session and peer active.
267    pub fn accept_counter(&mut self, counter: u32, now: Instant) -> Verdict {
268        let verdict = self.window.accept(counter);
269        self.session_timestamp = now;
270        self.active_timestamp = now;
271        verdict
272    }
273
274    /// Whether the peer counts as active (§4.13.2, `PeerActiveMode`).
275    #[must_use]
276    pub fn peer_active(&self, now: Instant) -> bool {
277        now.saturating_duration_since(self.active_timestamp) < self.mrp.active_threshold
278    }
279}
280
281/// The fixed-capacity set of established sessions.
282#[derive(Debug)]
283pub struct SessionTable<C: Config, const N: usize> {
284    sessions: Vec<SecureSession, N>,
285    /// The next local session id to hand out.
286    next_id: u16,
287    _config: PhantomData<C>,
288}
289
290impl<C: Config, const N: usize> SessionTable<C, N> {
291    /// An empty table whose first session id is `first_id`.
292    ///
293    /// §4.13.2.4 requires a fresh local session id that does not collide with a live one;
294    /// starting from a random value rather than 1 keeps a node's ids from being guessable
295    /// across a reboot.
296    #[must_use]
297    pub fn new(first_id: u16) -> Self {
298        let () = AssertValid::<C>::CHECK;
299        Self {
300            sessions: Vec::new(),
301            next_id: first_id,
302            _config: PhantomData,
303        }
304    }
305
306    /// How many sessions are established.
307    #[must_use]
308    pub fn len(&self) -> usize {
309        self.sessions.len()
310    }
311
312    /// Whether none are.
313    #[must_use]
314    pub fn is_empty(&self) -> bool {
315        self.sessions.is_empty()
316    }
317
318    /// Allocates a local session id that no live session is using (§4.13.2.4).
319    ///
320    /// Session id 0 is never returned: with a unicast session type it means the *unsecured*
321    /// session, so handing it out would make a secure session indistinguishable from no
322    /// session at all.
323    pub fn allocate_id(&mut self) -> Result<SessionId> {
324        for _ in 0..=u16::MAX {
325            let id = SessionId(self.next_id);
326            self.next_id = self.next_id.wrapping_add(1);
327            if id.0 != 0 && self.find(id).is_none() {
328                return Ok(id);
329            }
330        }
331        Err(Error::new(ErrorCode::NoSpace))
332    }
333
334    /// Installs a session.
335    pub fn insert(&mut self, session: SecureSession) -> Result<()> {
336        if self.find(session.local_session_id).is_some() {
337            return Err(Error::new(ErrorCode::InvalidState));
338        }
339        self.sessions
340            .push(session)
341            .map_err(|_| Error::new(ErrorCode::NoSpace))
342    }
343
344    /// The session a message addressed to `local_session_id` belongs to.
345    #[must_use]
346    pub fn find(&self, local_session_id: SessionId) -> Option<&SecureSession> {
347        self.sessions
348            .iter()
349            .find(|s| s.local_session_id == local_session_id)
350    }
351
352    /// The session, mutably.
353    pub fn find_mut(&mut self, local_session_id: SessionId) -> Option<&mut SecureSession> {
354        self.sessions
355            .iter_mut()
356            .find(|s| s.local_session_id == local_session_id)
357    }
358
359    /// Removes a session, returning whether one was there.
360    pub fn remove(&mut self, local_session_id: SessionId) -> bool {
361        let Some(i) = self
362            .sessions
363            .iter()
364            .position(|s| s.local_session_id == local_session_id)
365        else {
366            return false;
367        };
368        self.sessions.swap_remove(i);
369        true
370    }
371
372    /// Removes every session on a fabric — what `RemoveFabric` does.
373    pub fn remove_fabric(&mut self, fabric: FabricIndex) -> usize {
374        let before = self.sessions.len();
375        self.sessions.retain(|s| s.fabric_index != fabric);
376        before.saturating_sub(self.sessions.len())
377    }
378
379    /// The session that has gone unused longest, which is what §4.11.1.1 evicts when the
380    /// table is full.
381    #[must_use]
382    pub fn least_recently_used(&self) -> Option<SessionId> {
383        self.sessions
384            .iter()
385            .min_by_key(|s| s.session_timestamp)
386            .map(|s| s.local_session_id)
387    }
388
389    /// Every session.
390    pub fn iter(&self) -> impl Iterator<Item = &SecureSession> {
391        self.sessions.iter()
392    }
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use crate::DefaultConfig;
399
400    type Table = SessionTable<DefaultConfig, 4>;
401
402    fn keys() -> EstablishedKeys {
403        EstablishedKeys::derive(b"shared secret", &[]).expect("derive")
404    }
405
406    /// `0` as the randomness, which §4.6.1.1's `Crypto_DRBG(len = 28) + 1` turns into a first
407    /// counter of exactly 1 — the smallest a conforming session can have, and the one value
408    /// that makes the assertions below readable.
409    fn session(id: u16, role: Role) -> SecureSession {
410        SecureSession::new(
411            SessionId(id),
412            SessionId(id.wrapping_add(100)),
413            SessionKind::Pase,
414            role,
415            keys(),
416            0,
417            Instant::ZERO,
418        )
419    }
420
421    #[test]
422    fn the_three_keys_are_distinct() {
423        let k = keys();
424        assert_ne!(k.i2r.encryption, k.r2i.encryption);
425        assert_ne!(k.i2r.encryption, k.attestation_challenge);
426        assert_ne!(k.r2i.encryption, k.attestation_challenge);
427        // And the privacy key differs from the encryption key it came from.
428        assert_ne!(k.i2r.encryption, k.i2r.privacy);
429    }
430
431    #[test]
432    fn derivation_is_deterministic_and_salt_sensitive() {
433        assert_eq!(
434            EstablishedKeys::derive(b"secret", &[]).expect("a"),
435            EstablishedKeys::derive(b"secret", &[]).expect("b")
436        );
437        assert_ne!(
438            EstablishedKeys::derive(b"secret", &[]).expect("a"),
439            EstablishedKeys::derive(b"secret", b"salt").expect("b")
440        );
441        assert_ne!(
442            EstablishedKeys::derive(b"secret", &[]).expect("a"),
443            EstablishedKeys::derive(b"other", &[]).expect("b")
444        );
445    }
446
447    #[test]
448    fn the_two_ends_pick_opposite_keys() {
449        // The whole point of recording the role. An initiator encrypts with what a
450        // responder decrypts with, and the other way round.
451        let initiator = session(1, Role::Initiator);
452        let responder = session(1, Role::Responder);
453
454        assert_eq!(initiator.encrypt_keys(), responder.decrypt_keys());
455        assert_eq!(initiator.decrypt_keys(), responder.encrypt_keys());
456        assert_ne!(initiator.encrypt_keys(), initiator.decrypt_keys());
457    }
458
459    #[test]
460    fn a_pase_session_uses_the_unspecified_nonce_source() {
461        let s = session(1, Role::Initiator);
462        assert_eq!(s.send_nonce_source(), NonceSource::Pase);
463        assert_eq!(s.recv_nonce_source(), NonceSource::Pase);
464    }
465
466    #[test]
467    fn a_case_session_uses_the_right_end_for_each_direction() {
468        let mut s = session(1, Role::Initiator);
469        s.kind = SessionKind::Case;
470        s.local_node_id = NodeId(11);
471        s.peer_node_id = NodeId(22);
472        // Outgoing messages are protected by this node, so the nonce carries its id.
473        assert_eq!(s.send_nonce_source(), NonceSource::Case(NodeId(11)));
474        // Incoming ones were protected by the peer.
475        assert_eq!(s.recv_nonce_source(), NonceSource::Case(NodeId(22)));
476    }
477
478    #[test]
479    fn session_ids_are_allocated_without_collision_and_never_zero() {
480        let mut t = Table::new(0xFFFE);
481        let a = t.allocate_id().expect("a");
482        let b = t.allocate_id().expect("b");
483        let c = t.allocate_id().expect("c");
484        assert_eq!(a, SessionId(0xFFFE));
485        assert_eq!(b, SessionId(0xFFFF));
486        // Zero means the unsecured session, so it is skipped on the way round.
487        assert_eq!(c, SessionId(1));
488        assert_ne!(a, b);
489    }
490
491    #[test]
492    fn an_allocated_id_avoids_live_sessions() {
493        let mut t = Table::new(5);
494        t.insert(session(5, Role::Initiator)).expect("insert");
495        assert_eq!(t.allocate_id().expect("id"), SessionId(6));
496    }
497
498    #[test]
499    fn a_duplicate_local_id_is_refused() {
500        let mut t = Table::new(1);
501        t.insert(session(7, Role::Initiator)).expect("first");
502        assert_eq!(
503            t.insert(session(7, Role::Responder)).unwrap_err().code(),
504            ErrorCode::InvalidState
505        );
506    }
507
508    #[test]
509    fn a_full_table_is_a_value_not_an_abort() {
510        let mut t = Table::new(1);
511        for id in 1..=4 {
512            t.insert(session(id, Role::Initiator)).expect("fits");
513        }
514        assert_eq!(
515            t.insert(session(9, Role::Initiator)).unwrap_err().code(),
516            ErrorCode::NoSpace
517        );
518    }
519
520    #[test]
521    fn removing_a_fabric_removes_its_sessions() {
522        let mut t = Table::new(1);
523        for (id, fabric) in [(1u16, 1u8), (2, 1), (3, 2)] {
524            let mut s = session(id, Role::Initiator);
525            s.fabric_index = FabricIndex(fabric);
526            t.insert(s).expect("insert");
527        }
528        assert_eq!(t.remove_fabric(FabricIndex(1)), 2);
529        assert_eq!(t.len(), 1);
530        assert!(t.find(SessionId(3)).is_some());
531    }
532
533    #[test]
534    fn the_least_recently_used_session_is_the_eviction_candidate() {
535        let mut t = Table::new(1);
536        for (id, when) in [(1u16, 500u64), (2, 100), (3, 900)] {
537            let mut s = session(id, Role::Initiator);
538            s.session_timestamp = Instant::from_micros(when);
539            t.insert(s).expect("insert");
540        }
541        assert_eq!(t.least_recently_used(), Some(SessionId(2)));
542    }
543
544    #[test]
545    fn counters_and_timestamps_move_with_traffic() {
546        let mut s = session(1, Role::Initiator);
547        let t1 = Instant::from_micros(1_000);
548        assert_eq!(s.next_counter(t1).expect("counter"), 1);
549        assert_eq!(s.session_timestamp, t1);
550        assert_eq!(s.active_timestamp, Instant::ZERO, "sending is not activity");
551
552        let t2 = Instant::from_micros(2_000);
553        assert_eq!(s.accept_counter(50, t2), Verdict::New);
554        assert_eq!(s.active_timestamp, t2, "receiving is");
555        assert_eq!(s.accept_counter(50, t2), Verdict::Duplicate);
556    }
557
558    #[test]
559    fn a_peer_goes_idle_after_the_active_threshold() {
560        let mut s = session(1, Role::Initiator);
561        s.accept_counter(1, Instant::ZERO);
562        assert!(s.peer_active(Instant::ZERO));
563        let later = Instant::ZERO.saturating_add(s.mrp.active_threshold);
564        assert!(!s.peer_active(later));
565    }
566}