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 = 16> {
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> crate::config::Capacity for SessionTable<C, N> {
291    const TOTAL: usize = N;
292    /// §11.1.4.4's `CaseSessionsPerFabric`: the sessions this table guarantees each fabric.
293    ///
294    /// The whole table divided among the fabrics, with no rounding up. §4.14.2.8 sets the
295    /// floor at three and [`SessionTable::CHECK`] refuses a smaller table at compile time, so
296    /// this never has to be clamped — and clamping is what would turn a table that is too small
297    /// into an attribute that lies about it.
298    const PER_FABRIC: usize = N / C::FABRICS;
299}
300
301impl<C: Config, const N: usize> SessionTable<C, N> {
302    /// Compile-time proof that this table can keep §4.14.2.8's promise.
303    ///
304    /// > A node SHALL support at least 3 CASE session contexts per fabric.
305    ///
306    /// Referenced by [`SessionTable::new`], so a table too small for the node's `Config` fails
307    /// the build at the first place one is constructed.
308    pub const CHECK: () = {
309        let () = AssertValid::<C>::CHECK;
310        assert!(
311            N >= 3 * C::FABRICS,
312            "SessionTable: Core §4.14.2.8 requires at least 3 CASE sessions per fabric — \
313             raise the table's N, or lower Config::FABRICS"
314        );
315    };
316
317    /// An empty table whose first session id is `first_id`.
318    ///
319    /// §4.13.2.4 requires a fresh local session id that does not collide with a live one;
320    /// starting from a random value rather than 1 keeps a node's ids from being guessable
321    /// across a reboot.
322    #[must_use]
323    pub fn new(first_id: u16) -> Self {
324        let () = Self::CHECK;
325        Self {
326            sessions: Vec::new(),
327            next_id: first_id,
328            _config: PhantomData,
329        }
330    }
331
332    /// How many sessions are established.
333    #[must_use]
334    pub fn len(&self) -> usize {
335        self.sessions.len()
336    }
337
338    /// Whether none are.
339    #[must_use]
340    pub fn is_empty(&self) -> bool {
341        self.sessions.is_empty()
342    }
343
344    /// Allocates a local session id that no live session is using (§4.13.2.4).
345    ///
346    /// Session id 0 is never returned: with a unicast session type it means the *unsecured*
347    /// session, so handing it out would make a secure session indistinguishable from no
348    /// session at all.
349    pub fn allocate_id(&mut self) -> Result<SessionId> {
350        for _ in 0..=u16::MAX {
351            let id = SessionId(self.next_id);
352            self.next_id = self.next_id.wrapping_add(1);
353            if id.0 != 0 && self.find(id).is_none() {
354                return Ok(id);
355            }
356        }
357        Err(Error::new(ErrorCode::NoSpace))
358    }
359
360    /// Installs a session.
361    pub fn insert(&mut self, session: SecureSession) -> Result<()> {
362        if self.find(session.local_session_id).is_some() {
363            return Err(Error::new(ErrorCode::InvalidState));
364        }
365        self.sessions
366            .push(session)
367            .map_err(|_| Error::new(ErrorCode::NoSpace))
368    }
369
370    /// The session a message addressed to `local_session_id` belongs to.
371    #[must_use]
372    pub fn find(&self, local_session_id: SessionId) -> Option<&SecureSession> {
373        self.sessions
374            .iter()
375            .find(|s| s.local_session_id == local_session_id)
376    }
377
378    /// The session, mutably.
379    pub fn find_mut(&mut self, local_session_id: SessionId) -> Option<&mut SecureSession> {
380        self.sessions
381            .iter_mut()
382            .find(|s| s.local_session_id == local_session_id)
383    }
384
385    /// Removes a session, returning whether one was there.
386    pub fn remove(&mut self, local_session_id: SessionId) -> bool {
387        let Some(i) = self
388            .sessions
389            .iter()
390            .position(|s| s.local_session_id == local_session_id)
391        else {
392            return false;
393        };
394        self.sessions.swap_remove(i);
395        true
396    }
397
398    /// Removes every session on a fabric — what `RemoveFabric` does.
399    pub fn remove_fabric(&mut self, fabric: FabricIndex) -> usize {
400        let before = self.sessions.len();
401        self.sessions.retain(|s| s.fabric_index != fabric);
402        before.saturating_sub(self.sessions.len())
403    }
404
405    /// The session that has gone unused longest, which is what §4.11.1.1 evicts when the
406    /// table is full.
407    #[must_use]
408    pub fn least_recently_used(&self) -> Option<SessionId> {
409        self.sessions
410            .iter()
411            .min_by_key(|s| s.session_timestamp)
412            .map(|s| s.local_session_id)
413    }
414
415    /// Every session.
416    pub fn iter(&self) -> impl Iterator<Item = &SecureSession> {
417        self.sessions.iter()
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424    use crate::DefaultConfig;
425
426    // The specification's own minimum for five fabrics: §4.14.2.8's three CASE sessions each,
427    // plus one for the PASE that commissions the next. `SessionTable::CHECK` refuses less.
428    type Table = SessionTable<DefaultConfig>;
429
430    fn keys() -> EstablishedKeys {
431        EstablishedKeys::derive(b"shared secret", &[]).expect("derive")
432    }
433
434    /// `0` as the randomness, which §4.6.1.1's `Crypto_DRBG(len = 28) + 1` turns into a first
435    /// counter of exactly 1 — the smallest a conforming session can have, and the one value
436    /// that makes the assertions below readable.
437    fn session(id: u16, role: Role) -> SecureSession {
438        SecureSession::new(
439            SessionId(id),
440            SessionId(id.wrapping_add(100)),
441            SessionKind::Pase,
442            role,
443            keys(),
444            0,
445            Instant::ZERO,
446        )
447    }
448
449    #[test]
450    fn the_three_keys_are_distinct() {
451        let k = keys();
452        assert_ne!(k.i2r.encryption, k.r2i.encryption);
453        assert_ne!(k.i2r.encryption, k.attestation_challenge);
454        assert_ne!(k.r2i.encryption, k.attestation_challenge);
455        // And the privacy key differs from the encryption key it came from.
456        assert_ne!(k.i2r.encryption, k.i2r.privacy);
457    }
458
459    #[test]
460    fn derivation_is_deterministic_and_salt_sensitive() {
461        assert_eq!(
462            EstablishedKeys::derive(b"secret", &[]).expect("a"),
463            EstablishedKeys::derive(b"secret", &[]).expect("b")
464        );
465        assert_ne!(
466            EstablishedKeys::derive(b"secret", &[]).expect("a"),
467            EstablishedKeys::derive(b"secret", b"salt").expect("b")
468        );
469        assert_ne!(
470            EstablishedKeys::derive(b"secret", &[]).expect("a"),
471            EstablishedKeys::derive(b"other", &[]).expect("b")
472        );
473    }
474
475    #[test]
476    fn the_two_ends_pick_opposite_keys() {
477        // The whole point of recording the role. An initiator encrypts with what a
478        // responder decrypts with, and the other way round.
479        let initiator = session(1, Role::Initiator);
480        let responder = session(1, Role::Responder);
481
482        assert_eq!(initiator.encrypt_keys(), responder.decrypt_keys());
483        assert_eq!(initiator.decrypt_keys(), responder.encrypt_keys());
484        assert_ne!(initiator.encrypt_keys(), initiator.decrypt_keys());
485    }
486
487    #[test]
488    fn a_pase_session_uses_the_unspecified_nonce_source() {
489        let s = session(1, Role::Initiator);
490        assert_eq!(s.send_nonce_source(), NonceSource::Pase);
491        assert_eq!(s.recv_nonce_source(), NonceSource::Pase);
492    }
493
494    #[test]
495    fn a_case_session_uses_the_right_end_for_each_direction() {
496        let mut s = session(1, Role::Initiator);
497        s.kind = SessionKind::Case;
498        s.local_node_id = NodeId(11);
499        s.peer_node_id = NodeId(22);
500        // Outgoing messages are protected by this node, so the nonce carries its id.
501        assert_eq!(s.send_nonce_source(), NonceSource::Case(NodeId(11)));
502        // Incoming ones were protected by the peer.
503        assert_eq!(s.recv_nonce_source(), NonceSource::Case(NodeId(22)));
504    }
505
506    #[test]
507    fn session_ids_are_allocated_without_collision_and_never_zero() {
508        let mut t = Table::new(0xFFFE);
509        let a = t.allocate_id().expect("a");
510        let b = t.allocate_id().expect("b");
511        let c = t.allocate_id().expect("c");
512        assert_eq!(a, SessionId(0xFFFE));
513        assert_eq!(b, SessionId(0xFFFF));
514        // Zero means the unsecured session, so it is skipped on the way round.
515        assert_eq!(c, SessionId(1));
516        assert_ne!(a, b);
517    }
518
519    #[test]
520    fn an_allocated_id_avoids_live_sessions() {
521        let mut t = Table::new(5);
522        t.insert(session(5, Role::Initiator)).expect("insert");
523        assert_eq!(t.allocate_id().expect("id"), SessionId(6));
524    }
525
526    #[test]
527    fn a_duplicate_local_id_is_refused() {
528        let mut t = Table::new(1);
529        t.insert(session(7, Role::Initiator)).expect("first");
530        assert_eq!(
531            t.insert(session(7, Role::Responder)).unwrap_err().code(),
532            ErrorCode::InvalidState
533        );
534    }
535
536    #[test]
537    fn a_full_table_is_a_value_not_an_abort() {
538        // Driven by the table's own capacity rather than by a number typed here: the table is
539        // sized by the specification's minimum for five fabrics, and a test that filled a
540        // hard-coded four would stop testing fullness the moment that minimum moved.
541        let capacity = <Table as crate::config::Capacity>::TOTAL;
542        let mut t = Table::new(1);
543        for id in 1..=capacity {
544            t.insert(session(id as u16, Role::Initiator)).expect("fits");
545        }
546        assert_eq!(
547            t.insert(session(capacity as u16 + 1, Role::Initiator))
548                .unwrap_err()
549                .code(),
550            ErrorCode::NoSpace
551        );
552    }
553
554    #[test]
555    fn removing_a_fabric_removes_its_sessions() {
556        let mut t = Table::new(1);
557        for (id, fabric) in [(1u16, 1u8), (2, 1), (3, 2)] {
558            let mut s = session(id, Role::Initiator);
559            s.fabric_index = FabricIndex(fabric);
560            t.insert(s).expect("insert");
561        }
562        assert_eq!(t.remove_fabric(FabricIndex(1)), 2);
563        assert_eq!(t.len(), 1);
564        assert!(t.find(SessionId(3)).is_some());
565    }
566
567    #[test]
568    fn the_least_recently_used_session_is_the_eviction_candidate() {
569        let mut t = Table::new(1);
570        for (id, when) in [(1u16, 500u64), (2, 100), (3, 900)] {
571            let mut s = session(id, Role::Initiator);
572            s.session_timestamp = Instant::from_micros(when);
573            t.insert(s).expect("insert");
574        }
575        assert_eq!(t.least_recently_used(), Some(SessionId(2)));
576    }
577
578    #[test]
579    fn counters_and_timestamps_move_with_traffic() {
580        let mut s = session(1, Role::Initiator);
581        let t1 = Instant::from_micros(1_000);
582        assert_eq!(s.next_counter(t1).expect("counter"), 1);
583        assert_eq!(s.session_timestamp, t1);
584        assert_eq!(s.active_timestamp, Instant::ZERO, "sending is not activity");
585
586        let t2 = Instant::from_micros(2_000);
587        assert_eq!(s.accept_counter(50, t2), Verdict::New);
588        assert_eq!(s.active_timestamp, t2, "receiving is");
589        assert_eq!(s.accept_counter(50, t2), Verdict::Duplicate);
590    }
591
592    #[test]
593    fn a_peer_goes_idle_after_the_active_threshold() {
594        let mut s = session(1, Role::Initiator);
595        s.accept_counter(1, Instant::ZERO);
596        assert!(s.peer_active(Instant::ZERO));
597        let later = Instant::ZERO.saturating_add(s.mrp.active_threshold);
598        assert!(!s.peer_active(later));
599    }
600}