1use 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
34pub const SESSION_KEYS_INFO: &[u8] = b"SessionKeys";
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum SessionKind {
40 Pase,
43 Case,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub enum Role {
50 Initiator,
52 Responder,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct EstablishedKeys {
61 pub i2r: SessionKeys,
63 pub r2i: SessionKeys,
65 pub attestation_challenge: SymmetricKey,
68}
69
70impl EstablishedKeys {
71 #[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 #[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 pub fn derive(shared_secret: &[u8], salt: &[u8]) -> Result<Self> {
101 Self::derive_with_info(shared_secret, salt, SESSION_KEYS_INFO)
102 }
103
104 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#[derive(Debug)]
135pub struct SecureSession {
136 pub local_session_id: SessionId,
138 pub peer_session_id: SessionId,
140 pub kind: SessionKind,
142 pub role: Role,
144 pub peer_node_id: NodeId,
147 pub peer_cats: heapless::Vec<crate::msg::CaseAuthenticatedTag, 3>,
153 pub local_node_id: NodeId,
155 pub fabric_index: FabricIndex,
157 pub keys: EstablishedKeys,
159 pub counter: MessageCounter,
161 pub window: CounterWindow,
163 pub mrp: MrpParams,
165 pub session_timestamp: Instant,
167 pub active_timestamp: Instant,
170 pub peer: Option<crate::platform::Peer>,
181}
182
183impl SecureSession {
184 #[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 window: CounterWindow::new(CounterKind::SecureUnicast),
212 mrp: MrpParams::default(),
213 session_timestamp: now,
214 active_timestamp: now,
215 peer: None,
216 }
217 }
218
219 #[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 #[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 #[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 #[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 pub fn next_counter(&mut self, now: Instant) -> Result<u32> {
262 self.session_timestamp = now;
263 self.counter.take()
264 }
265
266 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 #[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#[derive(Debug)]
283pub struct SessionTable<C: Config, const N: usize = 16> {
284 sessions: Vec<SecureSession, N>,
285 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 const PER_FABRIC: usize = N / C::FABRICS;
299}
300
301impl<C: Config, const N: usize> SessionTable<C, N> {
302 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 #[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 #[must_use]
334 pub fn len(&self) -> usize {
335 self.sessions.len()
336 }
337
338 #[must_use]
340 pub fn is_empty(&self) -> bool {
341 self.sessions.is_empty()
342 }
343
344 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 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 #[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 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 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 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 #[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 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 type Table = SessionTable<DefaultConfig>;
429
430 fn keys() -> EstablishedKeys {
431 EstablishedKeys::derive(b"shared secret", &[]).expect("derive")
432 }
433
434 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 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 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 assert_eq!(s.send_nonce_source(), NonceSource::Case(NodeId(11)));
502 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 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 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}