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> {
284 sessions: Vec<SecureSession, N>,
285 next_id: u16,
287 _config: PhantomData<C>,
288}
289
290impl<C: Config, const N: usize> SessionTable<C, N> {
291 #[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 #[must_use]
308 pub fn len(&self) -> usize {
309 self.sessions.len()
310 }
311
312 #[must_use]
314 pub fn is_empty(&self) -> bool {
315 self.sessions.is_empty()
316 }
317
318 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 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 #[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 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 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 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 #[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 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 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 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 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 assert_eq!(s.send_nonce_source(), NonceSource::Case(NodeId(11)));
474 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 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}