matter_kit/messaging.rs
1//! Message processing: a datagram in, a protocol message out (Core §4.7).
2//!
3//! Everything below this module is sans-I/O and, until now, unconnected. [`msg`](crate::msg)
4//! frames and encrypts, [`session`](crate::session) holds the keys, [`exchange`](crate::exchange)
5//! holds the conversations and their reliability state — and nothing put the three together.
6//! This is that seam, and it is the whole of §4.7.1 "Message Transmission" and §4.7.2 "Message
7//! Reception".
8//!
9//! # Why it is a type and not a function
10//!
11//! Reception is not a pure decode. Three pieces of state change on the way through, and all
12//! three are security-relevant:
13//!
14//! * the **session's** replay window (§4.6.5), which decides whether a counter is new;
15//! * the **exchange's** MRP state (§4.12), which decides whether an acknowledgement is owed
16//! and whether a retransmission is still outstanding;
17//! * the **exchange table** itself, since a message may open an exchange the peer initiated.
18//!
19//! A receiver that decoded without updating them would accept replays. One that updated them
20//! before authenticating would let an unauthenticated sender move a window it has no key for
21//! — which is why the order here is fixed: find the session, **decrypt**, and only then touch
22//! any counter.
23//!
24//! # A duplicate is acknowledged and dropped
25//!
26//! §4.12.2.2 is emphatic, and it is the rule most easily got wrong in the direction that
27//! looks like it works:
28//!
29//! > The receiver SHALL send an acknowledgment message to the sender for each instance of an
30//! > authenticated, reliable message, including duplicates. The reliability layer SHALL only
31//! > propagate the first instance of a message to the next higher layer.
32//!
33//! Drop a duplicate silently and the sender retransmits until it gives up; deliver it twice
34//! and the application acts on it twice. [`Received::Duplicate`] is neither.
35
36use crate::config::Config;
37use crate::error::{Error, ErrorCode, Result, bail};
38use crate::exchange::{EXCHANGE_IDLE_TIMEOUT, ExchangeKey, ExchangeTable, MrpParams, OnTimeout};
39use crate::msg::{CounterKind, CounterWindow, MessageCounter, Verdict};
40use crate::msg::{
41 Destination, MessageHeader, NonceSource, ProtocolHeader, ProtocolId, SessionId, SessionType,
42 preview, protect, unprotect,
43};
44use crate::platform::{Instant, Peer};
45use crate::session::{SecureSession, SessionKind, SessionTable};
46
47/// The largest a Protocol Header can be (§4.4.3): the exchange flags, the opcode, the
48/// exchange id, a 32-bit protocol id and an acknowledged counter.
49///
50/// Only [`Messaging::acknowledge`] needs it: a standalone acknowledgement has no payload, so
51/// the body it frames is the header on its own.
52const PROTOCOL_HEADER_MAX: usize = 16;
53
54/// What arrived, once the message has been authenticated and routed.
55#[derive(Debug)]
56#[non_exhaustive]
57pub enum Received<'a> {
58 /// A group datagram (§4.16), which belongs to the group key store rather than here.
59 ///
60 /// Nothing about it has been decrypted or authenticated: a group message is keyed by an
61 /// operational group key, and which key it is has to be found by trying every installed
62 /// one whose session id matches (§4.17.3.6). Hand `buf` — unchanged — to
63 /// [`group::wire::receive`](crate::group::wire::receive), which does that and returns the
64 /// payload; a node that holds no group keys drops it.
65 Group {
66 /// The Group Session Id from the header, which selects the candidate keys.
67 session_id: SessionId,
68 /// Where it came from.
69 from: Peer,
70 },
71 /// The peer closed the session, and this node has done the same (§4.11.1.4).
72 ///
73 /// The session, its keys and its exchanges are gone by the time this is returned — that
74 /// is what "SHALL remove all state associated with the session" means, and it is done
75 /// here rather than left to the caller because none of that state is the caller's.
76 ///
77 /// What *is* the caller's is everything keyed on a session above this layer: §8.5's
78 /// subscriptions above all, which report on a session and have nowhere to go once it has
79 /// gone, and the §5.5 commissioning channel, which a closed PASE session releases.
80 SessionClosed {
81 /// The session that was closed.
82 session: SessionId,
83 },
84 /// A protocol message for the layer above.
85 Message {
86 /// The exchange it belongs to.
87 exchange: ExchangeKey,
88 /// The protocol header it carried.
89 header: ProtocolHeader,
90 /// Whether an acknowledgement is owed, which [`Messaging::acknowledge`] sends.
91 needs_ack: bool,
92 /// The application payload, decrypted in place.
93 payload: &'a [u8],
94 },
95 /// An authenticated message this node has already seen (§4.12.2.2).
96 ///
97 /// Not delivered upward. Still acknowledged, because the sender's retransmission means
98 /// its last acknowledgement was lost, not that its message was.
99 Duplicate {
100 /// The exchange it belongs to.
101 exchange: ExchangeKey,
102 /// Whether an acknowledgement is owed.
103 needs_ack: bool,
104 },
105 /// A standalone acknowledgement, consumed entirely by the reliability layer.
106 Acknowledged {
107 /// The exchange it acknowledged.
108 exchange: ExchangeKey,
109 },
110}
111
112/// What a timer expiry asks the caller to do.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum Due {
115 /// Retransmit the message with this counter on this exchange (§4.12.2.1).
116 ///
117 /// "Logical retransmission is of a given message as identified by its message counter",
118 /// so the caller resends the *same bytes*, not a re-encoding: a new counter would be a
119 /// new message and would reuse a nonce.
120 Retransmit {
121 /// Which exchange.
122 exchange: ExchangeKey,
123 /// The counter of the message to resend.
124 counter: u32,
125 },
126 /// An acknowledgement has waited long enough for a message to ride on (§4.12.5.2.2).
127 ///
128 /// [`Messaging::acknowledge`] writes it.
129 Acknowledge {
130 /// Which exchange owes it.
131 exchange: ExchangeKey,
132 },
133 /// `MRP_MAX_TRANSMISSIONS` passed with no acknowledgement; the exchange is closed.
134 Abandoned {
135 /// Which exchange was given up on.
136 exchange: ExchangeKey,
137 },
138}
139
140/// Which protocols the upper layer will accept (§4.10.3.1).
141///
142/// "The Interaction Model layer indicates to the Exchange Layer which Protocols it will accept.
143/// Any message for a Protocol ID that is not registered with the Exchange Layer SHALL be
144/// dropped."
145///
146/// This is not bookkeeping. §4.10.5.2 opens an exchange for any unsolicited message with the
147/// **I** flag, and on the unsecured session that is any datagram at all — so the set of
148/// protocols a node answers is also the set an attacker can make it allocate for. A node that
149/// registers only what it serves refuses the rest before the exchange table is touched.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
151pub struct Protocols(u8);
152
153impl Protocols {
154 const fn bit(protocol: ProtocolId) -> Option<u8> {
155 if protocol.vendor.0 != crate::msg::VendorId::COMMON.0 {
156 return None;
157 }
158 match protocol.id {
159 0x0000..=0x0004 => Some(1u8 << protocol.id),
160 _ => None,
161 }
162 }
163
164 /// Nothing registered — every unsolicited message is dropped.
165 pub const NONE: Self = Self(0);
166
167 /// Secure Channel (§4.11). Every node needs it: it is how sessions are established.
168 pub const SECURE_CHANNEL: Self = Self(1 << 0);
169 /// The Interaction Model (ch. 8) — what a node that serves clusters registers.
170 pub const INTERACTION_MODEL: Self = Self(1 << 1);
171 /// BDX (§11.22), for a node that transfers files.
172 pub const BDX: Self = Self(1 << 2);
173 /// User Directed Commissioning (§5.3).
174 pub const USER_DIRECTED_COMMISSIONING: Self = Self(1 << 3);
175 /// The range reserved for testing.
176 pub const FOR_TESTING: Self = Self(1 << 4);
177
178 /// What an ordinary device registers: Secure Channel and the Interaction Model.
179 pub const DEVICE: Self = Self(Self::SECURE_CHANNEL.0 | Self::INTERACTION_MODEL.0);
180
181 /// Both of these, registered.
182 #[must_use]
183 pub const fn with(self, other: Self) -> Self {
184 Self(self.0 | other.0)
185 }
186
187 /// Whether `protocol` is registered.
188 ///
189 /// A vendor-specific protocol id is never registered: §4.10.3.1's registration is by
190 /// identity, and this node serves none.
191 #[must_use]
192 pub const fn contains(self, protocol: ProtocolId) -> bool {
193 match Self::bit(protocol) {
194 Some(bit) => self.0 & bit != 0,
195 None => false,
196 }
197 }
198}
199
200/// §4.13.2.1's Unsecured Session Context, reduced to what framing needs.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202struct UnsecuredPeer {
203 /// The Ephemeral Initiator Node ID, whichever end chose it.
204 ephemeral_initiator: crate::msg::NodeId,
205 /// Whether *this* node is the initiator, which decides which header field carries it.
206 we_initiated: bool,
207}
208
209/// A session that was evicted to make room for a new one (§4.11.1.1).
210///
211/// The session and its exchanges are already gone. What is left is the `CLOSE_SESSION`
212/// status report the specification owes the evicted peer, framed and ready in the caller's
213/// output buffer.
214#[derive(Debug, Clone, Copy)]
215#[must_use = "§4.11.1.1 step 2a owes the evicted peer a CloseSession status report"]
216pub struct Evicted {
217 /// The session that was removed.
218 pub session: SessionId,
219 /// Where its peer was, if the session knew — nothing to send to if it did not.
220 pub peer: Option<Peer>,
221 /// How many octets of the output buffer the report occupies. Zero if it could not be
222 /// framed, which is not a reason to abandon the eviction.
223 pub len: usize,
224}
225
226/// A node's message processing: sessions, exchanges, and the framing between them.
227///
228/// `S` sizes the session table and `X` the exchange table. Both default to a device-sized
229/// node that satisfies every specification minimum for five fabrics, and
230/// [`SessionTable::CHECK`](crate::session::SessionTable::CHECK) refuses an `S` that cannot.
231#[derive(Debug)]
232pub struct Messaging<C: Config, const S: usize = 16, const X: usize = 64> {
233 sessions: SessionTable<C, S>,
234 exchanges: ExchangeTable<C, X>,
235 /// The counter for messages sent on the unsecured session (§4.6.1.2).
236 unsecured_counter: MessageCounter,
237 /// Duplicate detection for the unsecured session.
238 ///
239 /// §4.6.5 applies to unencrypted messages too, and this is the window that makes a PASE
240 /// handshake replay-resistant before any key exists.
241 unsecured_window: CounterWindow,
242 /// §4.13.2.1's Unsecured Session Context: the **Ephemeral Initiator Node ID**, and which
243 /// end of it this node is.
244 ///
245 /// "Randomly selected for each session by the initiator from the Operational Node ID range
246 /// and enclosed by initiator as Source Node ID and responder as Destination Node ID."
247 ///
248 /// One context, not a table. §4.13.2.1 allows several, keyed by ephemeral id, but a device
249 /// answers one session establishment at a time — which
250 /// [`PaseAdmission`](crate::commissioning::PaseAdmission) now enforces — and a controller
251 /// commissions one device at a time.
252 unsecured_peer: Option<UnsecuredPeer>,
253 /// Whether to apply §4.9's privacy processing to outgoing secure unicast messages.
254 privacy: bool,
255 /// §4.10.3.1's registered protocols.
256 protocols: Protocols,
257}
258
259impl<C: Config, const S: usize, const X: usize> Messaging<C, S, X> {
260 /// A node with no sessions and no exchanges.
261 ///
262 /// `first_session_id`, `first_exchange_id` and `initial_counter` should all come from
263 /// [`Rng`](crate::platform::Rng). §4.6.1.1 requires the counter to start at random: one
264 /// that always starts at zero leaks how many times a device has rebooted and makes nonce
265 /// reuse across a factory reset far too easy. A full-width random number is what to pass —
266 /// [`MessageCounter::new`](crate::msg::MessageCounter::new) narrows it to the twenty-eight
267 /// bits §4.6.1.1 allows, so the caller does not have to know that it must.
268 #[must_use]
269 pub fn new(first_session_id: u16, first_exchange_id: u16, initial_counter: u32) -> Self {
270 Self {
271 sessions: SessionTable::new(first_session_id),
272 exchanges: ExchangeTable::new(first_exchange_id),
273 unsecured_counter: MessageCounter::new(initial_counter),
274 unsecured_window: CounterWindow::new(CounterKind::Rollover),
275 unsecured_peer: None,
276 privacy: false,
277 protocols: Protocols::DEVICE,
278 }
279 }
280
281 /// Registers the protocols this node's upper layer will accept (§4.10.3.1).
282 ///
283 /// Defaults to [`Protocols::DEVICE`] — Secure Channel and the Interaction Model — which is
284 /// what a node that serves clusters needs. A node that also transfers files registers
285 /// [`Protocols::BDX`] on top; one that does neither registers less.
286 pub const fn register(&mut self, protocols: Protocols) {
287 self.protocols = protocols;
288 }
289
290 /// Which protocols are registered.
291 #[must_use]
292 pub const fn protocols(&self) -> Protocols {
293 self.protocols
294 }
295
296 /// Applies §4.9's privacy processing to outgoing secure unicast messages.
297 ///
298 /// Off by default, and deliberately. The **P** flag is only *required* on group messages
299 /// (§4.16.2 step 2c, §4.18): on a secure unicast session it is the sender's choice, and what it
300 /// buys is hiding the message counter from a passive observer on the link — the counter
301 /// is already authenticated, and anyone with the key can read it either way. What it
302 /// costs is depending on every peer having exercised its deobfuscation path, which is
303 /// not a bet worth making by default for a property this small.
304 ///
305 /// Receiving a private message never needs this: the flag is in the message, and
306 /// [`Messaging::receive`] honours it whatever this is set to.
307 pub const fn set_privacy(&mut self, privacy: bool) {
308 self.privacy = privacy;
309 }
310
311 /// Opens §4.13.2.1's Unsecured Session Context as the **initiator**.
312 ///
313 /// `ephemeral` is the Ephemeral Initiator Node ID this node encloses as the Source Node ID
314 /// of every unsecured message it sends, and which the responder will echo back as the
315 /// Destination Node ID. §4.13.2.1: "Initiators SHALL select a new random ephemeral node ID
316 /// for each unsecured session", from the Operational Node ID range — so it comes from
317 /// [`Rng`](crate::platform::Rng) and is *not* the node's operational identity. A node that
318 /// reused one identity across sessions would let a passive observer link them.
319 ///
320 /// # Errors
321 ///
322 /// [`ErrorCode::InvalidArgument`] unless `ephemeral` is in the Operational Node ID range.
323 pub fn open_unsecured_as_initiator(&mut self, ephemeral: crate::msg::NodeId) -> Result<()> {
324 if !ephemeral.is_operational() {
325 bail!(InvalidArgument)
326 }
327 self.unsecured_peer = Some(UnsecuredPeer {
328 ephemeral_initiator: ephemeral,
329 we_initiated: true,
330 });
331 Ok(())
332 }
333
334 /// Opens an unsecured exchange as the initiator, establishing §4.13.2.1's Unsecured Session
335 /// Context in the same call.
336 ///
337 /// This is how a commissioner starts PASE, and how any node starts CASE: both handshakes
338 /// run on the unsecured session before there is a key. The context is not optional —
339 /// §4.13.2.1 has the initiator "enclose" its Ephemeral Initiator Node ID as the Source Node
340 /// ID of every message, and a message with neither a Source nor a Destination is one the
341 /// specification tells the responder to discard.
342 ///
343 /// `randomness` comes from the caller's [`Rng`](crate::platform::Rng) and becomes the
344 /// ephemeral id, which is a *new* one for each unsecured session by §4.13.2.1.
345 pub fn open_unsecured(
346 &mut self,
347 protocol: ProtocolId,
348 now: Instant,
349 randomness: u64,
350 ) -> Result<ExchangeKey> {
351 self.open_unsecured_as_initiator(crate::msg::NodeId::ephemeral(randomness))?;
352 let params = self.mrp_params(SessionId::UNSECURED);
353 self.exchanges
354 .open_initiator(SessionId::UNSECURED, protocol, params, None, now)
355 }
356
357 /// Forgets the Unsecured Session Context, so the next handshake starts a new one.
358 ///
359 /// §4.13.2.1 requires a *new* ephemeral id per unsecured session, so a node that runs PASE
360 /// and then CASE against the same peer closes the first context before opening the second.
361 pub const fn close_unsecured(&mut self) {
362 self.unsecured_peer = None;
363 }
364
365 /// The Ephemeral Initiator Node ID of the current Unsecured Session Context, if there is one.
366 #[must_use]
367 pub const fn unsecured_ephemeral_id(&self) -> Option<crate::msg::NodeId> {
368 match self.unsecured_peer {
369 Some(peer) => Some(peer.ephemeral_initiator),
370 None => None,
371 }
372 }
373
374 /// The session table.
375 pub const fn sessions(&self) -> &SessionTable<C, S> {
376 &self.sessions
377 }
378
379 /// The session table, mutably — for the fields a completed handshake fills in
380 /// afterwards, such as §11.18.6.8 step 10a's accessing fabric.
381 ///
382 /// Installing a session goes through [`Messaging::install_session`] instead: a session
383 /// and its exchanges are one lifetime, and this reference only reaches one of them.
384 pub const fn sessions_mut(&mut self) -> &mut SessionTable<C, S> {
385 &mut self.sessions
386 }
387
388 /// Installs the session a handshake produced, evicting one if there is no room
389 /// (§4.11.1.1).
390 ///
391 /// A session table that answers `NoSpace` is a node that can be commissioned exactly
392 /// as many times as the session table is long and then never again — and the failure appears at the
393 /// *next* administrator, not at the one who filled it. §4.11.1.1 is explicit about the
394 /// alternative and about its three steps, in order:
395 ///
396 /// 1. the least recently used session, by `SessionTimestamp`;
397 /// 2. a `StatusReport(SUCCESS, SECURE_CHANNEL, CLOSE_SESSION)` **to that peer**, and
398 /// only then "remove all state associated with the session";
399 /// 3. the new session's own establishment message, which the caller was sending anyway.
400 ///
401 /// Step 2's two halves are why this takes buffers and returns an [`Evicted`]: the report
402 /// has to be framed while the session that encrypts it still exists, and put on the wire
403 /// by whoever owns the socket. The removal has already happened when this returns; what
404 /// is left is a datagram the caller sends to [`Evicted::peer`]. Dropping it costs the
405 /// peer nothing worse than a session it believes in until its next message fails, which
406 /// is why this is `must_use` rather than an error.
407 ///
408 /// `Ok(None)` is the ordinary case: there was room and nothing was evicted.
409 pub fn install_session(
410 &mut self,
411 session: SecureSession,
412 now: Instant,
413 randomness: u32,
414 scratch: &mut [u8],
415 out: &mut [u8],
416 ) -> Result<Option<Evicted>> {
417 if self.sessions.len() < S {
418 self.sessions.insert(session)?;
419 return Ok(None);
420 }
421 let Some(victim) = self.sessions.least_recently_used() else {
422 // No room and nothing to evict means `S == 0`, which `AssertValid` forbids.
423 bail!(NoSpace)
424 };
425 let peer = self.sessions.find(victim).and_then(|s| s.peer);
426 // Framed before the removal, because it is encrypted under the evicted session's own
427 // keys: a report built afterwards has nothing to encrypt it with.
428 let report = crate::sc::status::StatusReport {
429 general: crate::sc::status::GeneralCode::Success,
430 protocol: ProtocolId::SECURE_CHANNEL,
431 protocol_code: crate::sc::status::SecureChannelCode::CloseSession as u16,
432 data: &[],
433 };
434 let mut body = [0u8; 16];
435 let len = report.encode(&mut body)?;
436 let Some(body) = body.get(..len) else {
437 bail!(BufferTooSmall)
438 };
439 let exchange = self.open(victim, ProtocolId::SECURE_CHANNEL, now)?;
440 let framed = self
441 .send(
442 exchange,
443 crate::sc::opcode::STATUS_REPORT,
444 false,
445 body,
446 now,
447 randomness,
448 scratch,
449 out,
450 )
451 .map(|(n, _)| n);
452 // §4.13.3.1: "remove all state associated with the session" — the exchanges on it
453 // included, and including the one just used to say goodbye.
454 self.close_session(victim);
455 self.sessions.insert(session)?;
456 Ok(Some(Evicted {
457 session: victim,
458 peer,
459 len: framed.unwrap_or(0),
460 }))
461 }
462
463 /// Removes a session and everything associated with it (§4.13.3.1).
464 ///
465 /// Returns whether there was one. The exchanges on that session go with it: an exchange
466 /// outlives its session only as an entry nothing can ever answer on, holding a slot in a
467 /// fixed-capacity table until it times out.
468 pub fn close_session(&mut self, session: SessionId) -> bool {
469 self.exchanges.close_session(session);
470 self.sessions.remove(session)
471 }
472
473 /// Removes every session on a fabric, and their exchanges — what `RemoveFabric`
474 /// (§11.18.6.12) owes at the message layer.
475 ///
476 /// Returns how many sessions went. The clusters' half of the same command is
477 /// [`Lifecycle::FabricRemoved`](crate::im::Lifecycle::FabricRemoved).
478 pub fn remove_fabric(&mut self, fabric: crate::msg::FabricIndex) -> usize {
479 let doomed: heapless::Vec<SessionId, S> = self
480 .sessions
481 .iter()
482 .filter(|s| s.fabric_index == fabric)
483 .map(|s| s.local_session_id)
484 .collect();
485 for session in &doomed {
486 self.exchanges.close_session(*session);
487 }
488 self.sessions.remove_fabric(fabric)
489 }
490
491 /// The exchange table.
492 pub const fn exchanges(&self) -> &ExchangeTable<C, X> {
493 &self.exchanges
494 }
495
496 /// The exchange table, mutably.
497 pub const fn exchanges_mut(&mut self) -> &mut ExchangeTable<C, X> {
498 &mut self.exchanges
499 }
500
501 /// Opens an exchange this node initiates, to a peer it has not named yet.
502 ///
503 /// The peer is learned from the first message that comes back. Prefer
504 /// [`Messaging::open_to`] where it is already known: until it is, this node assumes UDP
505 /// and runs MRP, which is right for UDP and one wasted round trip on BTP.
506 pub fn open(
507 &mut self,
508 session: SessionId,
509 protocol: ProtocolId,
510 now: Instant,
511 ) -> Result<ExchangeKey> {
512 // §4.13.2.1 gives an unsecured initiator one obligation before it sends anything: an
513 // Unsecured Session Context, whose Ephemeral Initiator Node ID it "encloses as Source
514 // Node ID". Without one, [`Messaging::send`] has no id to put in the header and emits a
515 // message carrying neither a Source nor a Destination — which the specification tells
516 // the receiver to discard, and which the CHIP SDK does. The message is built, counted
517 // and dropped, and nothing anywhere says so.
518 //
519 // So an unsecured exchange is opened through [`Messaging::open_unsecured`], which
520 // establishes the context in the same call, and this door is closed rather than left
521 // to be remembered.
522 if session == SessionId::UNSECURED && self.unsecured_peer.is_none() {
523 bail!(InvalidState)
524 }
525 let params = self.mrp_params(session);
526 // Where the peer last was, which is the only answer available and the right one: a
527 // session exists because that peer authenticated itself from there. Opening with no
528 // peer produces an exchange that cannot send — [`Stack::send`] builds the message and
529 // [`Stack::peer`] then has no address to give the caller, so the message is built,
530 // counted, and dropped, with no error anywhere. Use [`Stack::open_to`] to name a
531 // different address, for a peer just rediscovered at a new one.
532 let peer = self.sessions.find(session).and_then(|s| s.peer);
533 self.exchanges
534 .open_initiator(session, protocol, params, peer, now)
535 }
536
537 /// Opens an exchange to a peer this node has already found.
538 ///
539 /// Naming the transport is what lets §4.12.4 be honoured: a BLE peer's exchange never
540 /// sets the **R** flag, because BTP has already delivered the message or closed the
541 /// session trying.
542 pub fn open_to(
543 &mut self,
544 session: SessionId,
545 protocol: ProtocolId,
546 peer: Peer,
547 now: Instant,
548 ) -> Result<ExchangeKey> {
549 // The same obligation as [`Messaging::open`]: an unsecured initiator has to have
550 // §4.13.2.1's context before it sends, or its message carries no Source Node ID and the
551 // responder is told to discard it. [`Messaging::open_unsecured_to`] does both.
552 if session == SessionId::UNSECURED && self.unsecured_peer.is_none() {
553 bail!(InvalidState)
554 }
555 let params = self.mrp_params(session);
556 self.exchanges
557 .open_initiator(session, protocol, params, Some(peer), now)
558 }
559
560 /// [`Messaging::open_unsecured`], to a peer whose address is already known.
561 ///
562 /// What a commissioner uses: it found the device over BLE or mDNS, so it has somewhere to
563 /// send before any session exists.
564 pub fn open_unsecured_to(
565 &mut self,
566 protocol: ProtocolId,
567 peer: Peer,
568 now: Instant,
569 randomness: u64,
570 ) -> Result<ExchangeKey> {
571 self.open_unsecured_as_initiator(crate::msg::NodeId::ephemeral(randomness))?;
572 let params = self.mrp_params(SessionId::UNSECURED);
573 self.exchanges
574 .open_initiator(SessionId::UNSECURED, protocol, params, Some(peer), now)
575 }
576
577 /// Where an exchange's peer is, once it is known.
578 #[must_use]
579 pub fn peer(&self, exchange: ExchangeKey) -> Option<Peer> {
580 self.exchanges.find(exchange).and_then(|e| e.peer)
581 }
582
583 fn mrp_params(&self, session: SessionId) -> MrpParams {
584 self.sessions
585 .find(session)
586 .map_or_else(MrpParams::default, |s| s.mrp)
587 }
588
589 /// Whether a reliable message this node sent on `exchange` is still awaiting its
590 /// acknowledgement (§4.12.2).
591 ///
592 /// An exchange in that state must not be closed: closing it drops the retransmission, and a
593 /// lost final message — the last chunk of a read, a command's response — is then never
594 /// delivered at all.
595 #[must_use]
596 pub fn is_awaiting_ack(&self, exchange: ExchangeKey) -> bool {
597 self.exchanges
598 .find(exchange)
599 .is_some_and(|e| e.mrp.is_awaiting_ack())
600 }
601
602 /// Closes an exchange.
603 pub fn close(&mut self, exchange: ExchangeKey) -> bool {
604 self.exchanges.close(exchange)
605 }
606
607 /// Processes one arriving datagram, in place (§4.7.2).
608 ///
609 /// `buf` is decrypted in place, so the returned payload borrows it. On any failure the
610 /// contents of `buf` are unspecified — §3.6.2 says a failed tag check leaves the payload
611 /// undefined — and nothing in this node's state has moved.
612 pub fn receive<'b>(
613 &mut self,
614 buf: &'b mut [u8],
615 from: Peer,
616 now: Instant,
617 ) -> Result<Received<'b>> {
618 let head = preview(buf)?;
619 if matches!(head.session_type, SessionType::Group) {
620 // §4.16: a group message is keyed by an *operational group key* and belongs to no
621 // session, so none of this function's machinery applies to it — there is no
622 // session to find, no replay window of a session's to move, and no exchange, since
623 // §4.16.2 step 2c sets only the P flag, so a group message is never
624 // reliable and never acknowledged.
625 //
626 // It is handed back rather than refused. A device with a group key store routes it
627 // to [`group::wire::receive`](crate::group::wire::receive), which is the same layer
628 // as this one for keys it holds rather than sessions; a device without one drops
629 // it. Answering `Unsupported` here made the two halves look like one missing one.
630 return Ok(Received::Group {
631 session_id: head.session_id,
632 from,
633 });
634 }
635
636 let (header, range) = if head.session_id == SessionId::UNSECURED {
637 let (header, rest) = MessageHeader::decode(buf)?;
638 if !header.is_unsecured() {
639 bail!(MessageReserved)
640 }
641 let start = buf.len().saturating_sub(rest.len());
642 (header, start..buf.len())
643 } else {
644 let session = self
645 .sessions
646 .find(head.session_id)
647 .ok_or(Error::new(ErrorCode::NoSession))?;
648 // §4.8.1.1's nonce depends on how the session was established, and getting it
649 // wrong fails the tag rather than silently mis-decrypting — but naming it here
650 // keeps the two readings from ever being confused.
651 let nonce_source = match session.kind {
652 SessionKind::Pase => NonceSource::Pase,
653 SessionKind::Case => NonceSource::Case(session.peer_node_id),
654 };
655 let keys = session.keys.receiving(session.role).clone();
656 unprotect(buf, &keys, nonce_source)?
657 };
658
659 // Authenticated. Only now may any counter move.
660 let verdict = if header.is_unsecured() {
661 self.unsecured_window.accept(header.message_counter)
662 } else {
663 let session = self
664 .sessions
665 .find_mut(head.session_id)
666 .ok_or(Error::new(ErrorCode::NoSession))?;
667 // Authenticated, so it is the peer and this is where it is. A node that opens an
668 // exchange of its own — §8.5.3's subscription reports above all — has no other way
669 // to learn the address, and an exchange with no peer sends nothing.
670 session.peer = Some(from);
671 session.accept_counter(header.message_counter, now)
672 };
673
674 let Some(payload) = buf.get(range) else {
675 bail!(MessageTruncated)
676 };
677 let (protocol_header, body) = ProtocolHeader::decode(payload)?;
678
679 // §4.13.2.1's context matching: "Else if the message carries a Source Node ID … Set
680 // Session Role to responder … Record the incoming message's Source Node ID as Ephemeral
681 // Initiator Node ID." Recorded here, before the exchange is routed, so that the very
682 // first reply carries it back as the Destination Node ID.
683 // §4.13.2.1 step 1c: "Else discard the message." A message that matches no context and
684 // carries no Source Node ID belongs to no session, and accepting it is what let this
685 // crate's own initiator get away with sending one — the two halves agreed with each
686 // other and disagreed with the specification.
687 if header.is_unsecured() && header.source.is_none() {
688 let addressed_to_our_context = matches!(
689 (self.unsecured_peer, header.destination),
690 (Some(peer), Destination::Node(id)) if peer.ephemeral_initiator == id
691 );
692 if !addressed_to_our_context {
693 bail!(NoSession)
694 }
695 }
696 if header.is_unsecured()
697 && let Some(source) = header.source
698 && self
699 .unsecured_peer
700 .is_none_or(|peer| peer.ephemeral_initiator != source)
701 {
702 // §4.13.2.1 matches a context by Ephemeral Initiator Node ID and creates a *new*
703 // one when no context matches. A different id is a different session — a second
704 // commissioner, or the same one returning for CASE after PASE — so the context is
705 // replaced rather than kept. Keeping the first would address every reply to a peer
706 // that has gone, which the CHIP SDK drops as belonging to no session of its own.
707 //
708 // One context at a time is the simplification here; the specification allows
709 // several. What makes it safe is that the *contents* are two header fields and a
710 // replay window, and admitting a second handshake at all is refused a layer up by
711 // `PaseAdmission`.
712 //
713 // The old context's exchanges go with it. They belong to a peer that is no longer
714 // this context's, and an exchange id is the initiator's to choose: left in place, the
715 // new initiator's first message can land on the old one's exchange — whose reply may
716 // still be awaiting an acknowledgement nobody will send — and be answered with that
717 // exchange's state, or not at all.
718 if self.unsecured_peer.is_some() {
719 self.exchanges.close_session(SessionId::UNSECURED);
720 }
721 self.unsecured_peer = Some(UnsecuredPeer {
722 ephemeral_initiator: source,
723 we_initiated: false,
724 });
725 }
726
727 let duplicate = matches!(verdict, Verdict::Duplicate);
728 let key = self.route(header.session_id, &protocol_header, duplicate, now)?;
729 let Some(exchange) = self.exchanges.find_mut(key) else {
730 bail!(NoExchange)
731 };
732 exchange.touch(now);
733 // Where the reply goes, and — §4.12.4 — whether MRP runs on this exchange. A peer
734 // that moved (a Thread node changing address, say) is followed here.
735 exchange.peer = Some(from);
736 exchange.mrp.note_peer_activity(now);
737
738 // §4.12.1: an acknowledgement may ride on any message, so it is taken before the
739 // message's own kind is considered.
740 if let Some(acknowledged) = protocol_header.acknowledged_counter {
741 exchange.mrp.on_ack(acknowledged, now);
742 }
743
744 if protocol_header.reliability {
745 exchange
746 .mrp
747 .on_reliable_received(header.message_counter, now, duplicate);
748 }
749 let needs_ack = protocol_header.reliability;
750
751 if duplicate {
752 return Ok(Received::Duplicate {
753 exchange: key,
754 needs_ack,
755 });
756 }
757 if protocol_header.protocol == ProtocolId::SECURE_CHANNEL
758 && protocol_header.opcode == crate::sc::opcode::MRP_STANDALONE_ACK
759 {
760 // A standalone acknowledgement carries nothing above the reliability layer.
761 return Ok(Received::Acknowledged { exchange: key });
762 }
763
764 // §4.11.1.4: "If a Node has either sent or received a CloseSession StatusReport, that
765 // Node SHALL remove all state associated with the session." Both halves are the
766 // message layer's, and this is the half a node is most likely to leave out — sending
767 // one is a decision it makes, receiving one is something that happens to it.
768 //
769 // Handled here rather than handed upward because the rule is about *this* layer's
770 // state: the session, its keys, its counters and its exchanges, including the exchange
771 // this message arrived on. A node that passed it up would answer on a session the
772 // specification says is already gone.
773 if !header.is_unsecured()
774 && protocol_header.protocol == ProtocolId::SECURE_CHANNEL
775 && protocol_header.opcode == crate::sc::opcode::STATUS_REPORT
776 && matches!(
777 crate::sc::status::StatusReport::decode(body),
778 Ok(report)
779 if report.protocol == ProtocolId::SECURE_CHANNEL
780 && report.protocol_code
781 == crate::sc::status::SecureChannelCode::CloseSession as u16
782 )
783 {
784 let session = header.session_id;
785 self.close_session(session);
786 return Ok(Received::SessionClosed { session });
787 }
788
789 Ok(Received::Message {
790 exchange: key,
791 header: protocol_header,
792 needs_ack,
793 payload: body,
794 })
795 }
796
797 /// Finds or opens the exchange a message belongs to (§4.10.5.2).
798 ///
799 /// The three rules are in order, and the order is what bounds the table:
800 ///
801 /// 1. "If the unsolicited message is not marked as having a duplicate message counter,
802 /// **has a registered Protocol ID**, and the I Flag is set: create a new exchange."
803 /// 2. "Otherwise, if the message has the R Flag set: create an *ephemeral* exchange … and
804 /// send an immediate standalone acknowledgement. The message SHALL NOT be forwarded to
805 /// the upper layer."
806 /// 3. "Otherwise, processing of the message SHALL stop."
807 ///
808 /// Rule 3 is the one that matters most and is the easiest to leave out: a message this
809 /// node will never act on, and which is not even asking for an acknowledgement, must not
810 /// cost a table entry. Without it every datagram that reaches the port allocates.
811 fn route(
812 &mut self,
813 session: SessionId,
814 header: &ProtocolHeader,
815 duplicate: bool,
816 now: Instant,
817 ) -> Result<ExchangeKey> {
818 if let Some(exchange) =
819 self.exchanges
820 .find_for_message(session, header.exchange_id, header.initiator)
821 {
822 return Ok(exchange.key);
823 }
824 // Only a message *from* an initiator may open an exchange. One claiming to be from a
825 // responder with no exchange to respond to is answering a question nobody asked.
826 if !header.initiator {
827 bail!(NoExchange)
828 }
829 let params = self.mrp_params(session);
830 if !duplicate && self.protocols.contains(header.protocol) {
831 return self.exchanges.open_responder(
832 session,
833 header.exchange_id,
834 header.protocol,
835 params,
836 now,
837 );
838 }
839 if header.reliability {
840 // Rule 2. The sender is owed an acknowledgement even though nothing here will
841 // read its message — withholding it costs five retransmissions — but the entry
842 // that carries it is closed as soon as it has been sent.
843 return self.exchanges.open_ephemeral(
844 session,
845 header.exchange_id,
846 header.protocol,
847 params,
848 now,
849 );
850 }
851 // Rule 3.
852 bail!(NoExchange)
853 }
854
855 /// Builds an outgoing message on an exchange (§4.7.1).
856 ///
857 /// `reliable` sets the MRP **R** flag; a reliable message is remembered for
858 /// retransmission until it is acknowledged, and [`Messaging::poll`] is what resends it.
859 /// `randomness` is the jitter draw of §4.12.2.1 and should come from
860 /// [`Rng`](crate::platform::Rng).
861 ///
862 /// Returns how many octets of `out` the datagram occupies, and the counter it was sent
863 /// with — which is what a retransmission is identified by.
864 #[expect(
865 clippy::too_many_arguments,
866 reason = "every one is a distinct fact about the message; bundling them into a \
867 struct would only move the same list one line up"
868 )]
869 pub fn send(
870 &mut self,
871 exchange: ExchangeKey,
872 opcode: u8,
873 reliable: bool,
874 payload: &[u8],
875 now: Instant,
876 randomness: u32,
877 scratch: &mut [u8],
878 out: &mut [u8],
879 ) -> Result<(usize, u32)> {
880 let Some(open) = self.exchanges.find(exchange) else {
881 bail!(NoExchange)
882 };
883 let protocol = open.protocol;
884 // §4.12.4: "Reliable messages sent over TCP, PAFTP, or BTP SHALL utilize the
885 // underlying reliability mechanisms of those transports and SHOULD NOT set the R
886 // Flag." Running MRP on top of BTP would retransmit a message BTP has already
887 // guaranteed, and BTP would carry the duplicate faithfully.
888 let reliable = reliable && !open.is_transport_reliable();
889 let piggyback = self
890 .exchanges
891 .find_mut(exchange)
892 .and_then(|e| e.mrp.take_piggyback());
893
894 let protocol_header = ProtocolHeader {
895 initiator: exchange.role.is_initiator(),
896 acknowledged_counter: piggyback,
897 reliability: reliable,
898 exchange_id: exchange.id,
899 protocol,
900 opcode,
901 };
902
903 let counter = self.next_counter(exchange.session, now)?;
904 let written = self.frame(
905 exchange.session,
906 counter,
907 &protocol_header,
908 payload,
909 scratch,
910 out,
911 )?;
912
913 if reliable && let Some(open) = self.exchanges.find_mut(exchange) {
914 open.mrp.on_send(counter, now, randomness)?;
915 }
916 Ok((written, counter))
917 }
918
919 /// Sends the standalone acknowledgement a [`Received`] said was owed (§4.12.1).
920 ///
921 /// A standalone ack is *not* reliable — acknowledging an acknowledgement would never
922 /// terminate — and carries no payload.
923 pub fn acknowledge(
924 &mut self,
925 exchange: ExchangeKey,
926 now: Instant,
927 out: &mut [u8],
928 ) -> Result<usize> {
929 let Some(open) = self.exchanges.find_mut(exchange) else {
930 bail!(NoExchange)
931 };
932 let ephemeral = open.ephemeral;
933 let Some(acknowledged) = open.mrp.take_piggyback() else {
934 // Nothing owed: the acknowledgement was already carried by an earlier message.
935 if ephemeral {
936 self.exchanges.close(exchange);
937 }
938 return Ok(0);
939 };
940 let protocol_header = ProtocolHeader {
941 initiator: exchange.role.is_initiator(),
942 acknowledged_counter: Some(acknowledged),
943 reliability: false,
944 exchange_id: exchange.id,
945 // §4.12.7.1: "The Protocol ID SHALL be set to PROTOCOL_ID_SECURE_CHANNEL."
946 //
947 // Not the exchange's protocol, which is the natural thing to write and what this
948 // did: the opcode is Secure Channel's, so sending it under the exchange's protocol
949 // id produces a message that decodes as, say, Interaction Model opcode 0x10 — an
950 // opcode the Interaction Model does not define. The CHIP SDK prints it as
951 // `IM:----` and answers `Invalid message type`, which ends the interaction the
952 // acknowledgement was supposed to keep alive.
953 //
954 // MRP is a property of the *exchange layer*, below the protocol running on it, and
955 // this is where that shows on the wire.
956 protocol: ProtocolId::SECURE_CHANNEL,
957 opcode: crate::sc::opcode::MRP_STANDALONE_ACK,
958 };
959 let counter = self.next_counter(exchange.session, now)?;
960 // A standalone acknowledgement carries no payload, so the body being joined is the
961 // protocol header alone and the scratch never needs to be larger than one.
962 let mut scratch = [0u8; PROTOCOL_HEADER_MAX];
963 let written = self.frame(
964 exchange.session,
965 counter,
966 &protocol_header,
967 &[],
968 &mut scratch,
969 out,
970 )?;
971 // §4.12.5.2.2: "If the Exchange is marked as an ephemeral exchange the Exchange SHALL
972 // be closed." It existed only to carry this acknowledgement, and holding it open is
973 // what would make answering a stranger politely cost a table entry.
974 if ephemeral {
975 self.exchanges.close(exchange);
976 }
977 Ok(written)
978 }
979
980 /// Takes the next message counter for a session (§4.6.1).
981 fn next_counter(&mut self, session: SessionId, now: Instant) -> Result<u32> {
982 if session == SessionId::UNSECURED {
983 self.unsecured_counter.take()
984 } else {
985 self.sessions
986 .find_mut(session)
987 .ok_or(Error::new(ErrorCode::NoSession))?
988 .next_counter(now)
989 }
990 }
991
992 /// Frames, and encrypts when the session is secure.
993 fn frame(
994 &self,
995 session: SessionId,
996 counter: u32,
997 protocol_header: &ProtocolHeader,
998 payload: &[u8],
999 scratch: &mut [u8],
1000 out: &mut [u8],
1001 ) -> Result<usize> {
1002 // §4.8's AEAD needs the protocol header and the payload contiguous before it can
1003 // encrypt them, and this is where they are joined. The buffer is the caller's
1004 // because its size is the *transport's*: a datagram node needs
1005 // [`MAX_UDP_MESSAGE`](crate::config::MAX_UDP_MESSAGE) and nothing more, and a node on
1006 // TCP needs the framer's own `N` — §4.15.2.3's Maximum Message Size, which is the whole
1007 // reason §4.15 exists and is far too much to put on the stack of every node that
1008 // never opens a connection.
1009 let header_len = protocol_header.encode(scratch)?;
1010 let end = header_len
1011 .checked_add(payload.len())
1012 .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
1013 let Some(slot) = scratch.get_mut(header_len..end) else {
1014 bail!(BufferTooSmall)
1015 };
1016 slot.copy_from_slice(payload);
1017 let Some(body) = scratch.get(..end) else {
1018 bail!(BufferTooSmall)
1019 };
1020
1021 if session == SessionId::UNSECURED {
1022 // §4.13.2.1: the Ephemeral Initiator Node ID is "enclosed by initiator as Source
1023 // Node ID and responder as Destination Node ID". Which field it goes in is decided
1024 // by which end of the context this node is, and a message carrying neither is one
1025 // the peer cannot associate with any session — the CHIP SDK drops it outright.
1026 let (source, destination) = match self.unsecured_peer {
1027 Some(peer) if peer.we_initiated => {
1028 (Some(peer.ephemeral_initiator), Destination::None)
1029 }
1030 Some(peer) => (None, Destination::Node(peer.ephemeral_initiator)),
1031 None => (None, Destination::None),
1032 };
1033 let header = MessageHeader {
1034 session_id: SessionId::UNSECURED,
1035 message_counter: counter,
1036 source,
1037 destination,
1038 ..MessageHeader::default()
1039 };
1040 let header_len = header.encode(out)?;
1041 let total = header_len
1042 .checked_add(body.len())
1043 .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
1044 let Some(slot) = out.get_mut(header_len..total) else {
1045 bail!(BufferTooSmall)
1046 };
1047 slot.copy_from_slice(body);
1048 return Ok(total);
1049 }
1050
1051 let found = self
1052 .sessions
1053 .find(session)
1054 .ok_or(Error::new(ErrorCode::NoSession))?;
1055 let header = MessageHeader {
1056 session_id: found.peer_session_id,
1057 message_counter: counter,
1058 // §4.4.1.5: the Source Node ID is elided on a secure unicast session, where the
1059 // session itself already says who is speaking.
1060 source: None,
1061 destination: Destination::None,
1062 // §4.9 is the sender's choice on a unicast session; see
1063 // [`Messaging::set_privacy`]. A PASE session is never private: it has no
1064 // operational identity to correlate, so there would be nothing to hide.
1065 privacy: self.privacy && matches!(found.kind, SessionKind::Case),
1066 ..MessageHeader::default()
1067 };
1068 let nonce_source = match found.kind {
1069 SessionKind::Pase => NonceSource::Pase,
1070 SessionKind::Case => NonceSource::Case(found.local_node_id),
1071 };
1072 let keys = found.keys.sending(found.role);
1073 protect(&header, nonce_source, body, keys, out)
1074 }
1075
1076 /// When [`Messaging::poll`] next needs to be called.
1077 ///
1078 /// The earlier of a reliability deadline and the next moment an abandoned exchange could
1079 /// be reclaimed, so a node that honours this wake-up gets §4.10.5.3's cleanup without
1080 /// scheduling anything of its own.
1081 #[must_use]
1082 pub fn wake_at(&self) -> Option<Instant> {
1083 let reap = self.exchanges.reap_deadline(EXCHANGE_IDLE_TIMEOUT);
1084 match (self.exchanges.poll_deadline(), reap) {
1085 (Some(a), Some(b)) => Some(if a <= b { a } else { b }),
1086 (Some(a), None) => Some(a),
1087 (None, b) => b,
1088 }
1089 }
1090
1091 /// Drives the reliability timers (§4.12.2.1) and reclaims abandoned exchanges (§4.10.5.3).
1092 ///
1093 /// Returns one action at a time; call until it returns `None`.
1094 ///
1095 /// Reaping happens here rather than in a method a node has to remember to call, because an
1096 /// exchange table reclaimed only on request is one an attacker fills at leisure: every
1097 /// unsecured datagram with the **I** flag opens an entry (§4.10.5.2), and `X` of them
1098 /// would otherwise deny every later session establishment for the node's whole uptime.
1099 pub fn poll(&mut self, now: Instant, randomness: u32) -> Option<Due> {
1100 self.exchanges.reap(now, EXCHANGE_IDLE_TIMEOUT);
1101 let expired = self
1102 .exchanges
1103 .iter()
1104 .find(|e| e.mrp.poll_deadline().is_some_and(|at| at <= now))
1105 .map(|e| e.key)?;
1106 let open = self.exchanges.find_mut(expired)?;
1107 match open.mrp.on_timeout(now, randomness) {
1108 OnTimeout::Retransmit { counter, .. } => Some(Due::Retransmit {
1109 exchange: expired,
1110 counter,
1111 }),
1112 // §4.12.5.2.2: nothing to piggyback on, so the acknowledgement goes on its own.
1113 OnTimeout::SendStandaloneAck { .. } => Some(Due::Acknowledge { exchange: expired }),
1114 OnTimeout::GiveUp { .. } => {
1115 self.exchanges.close(expired);
1116 Some(Due::Abandoned { exchange: expired })
1117 }
1118 OnTimeout::Nothing => None,
1119 }
1120 }
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125 use super::*;
1126 use crate::config::{Capacity, DefaultConfig};
1127 use crate::exchange::Role;
1128
1129 type Node = Messaging<DefaultConfig>;
1130
1131 fn at(ms: u64) -> Instant {
1132 Instant::from_micros(ms.saturating_mul(1000))
1133 }
1134
1135 const PEER: Peer = Peer::Udp(crate::platform::PeerAddr::new([
1136 0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1137 ]));
1138
1139 fn keys() -> crate::session::EstablishedKeys {
1140 crate::session::EstablishedKeys::derive(b"shared secret", &[]).expect("derive")
1141 }
1142
1143 fn session_on(id: u16, fabric: u8, now: Instant) -> SecureSession {
1144 let mut s = SecureSession::new(
1145 SessionId(id),
1146 SessionId(id.wrapping_add(100)),
1147 SessionKind::Case,
1148 crate::session::Role::Responder,
1149 keys(),
1150 1,
1151 now,
1152 );
1153 s.fabric_index = crate::msg::FabricIndex(fabric);
1154 s.peer = Some(PEER);
1155 s
1156 }
1157
1158 /// §4.11.1.4: "The CloseSession StatusReport SHALL only be sent encrypted within an
1159 /// exchange associated with a PASE or CASE session." So one that arrives on the *unsecured*
1160 /// session closes nothing — otherwise anybody who can reach the port could end a
1161 /// commissioned node's sessions with a datagram costing them nothing to send.
1162 #[test]
1163 fn an_unsecured_close_session_report_closes_nothing() {
1164 let mut node = Node::new(1, 100, 7);
1165 let mut scratch = [0u8; 512];
1166 let mut wire = [0u8; 512];
1167 node.install_session(session_on(1, 1, at(0)), at(0), 0, &mut scratch, &mut wire)
1168 .expect("install");
1169
1170 // A stranger's unsecured datagram carrying exactly the report a peer would send.
1171 let mut attacker = Node::new(2, 200, 9);
1172 let report = crate::sc::status::StatusReport {
1173 general: crate::sc::status::GeneralCode::Success,
1174 protocol: ProtocolId::SECURE_CHANNEL,
1175 protocol_code: crate::sc::status::SecureChannelCode::CloseSession as u16,
1176 data: &[],
1177 };
1178 let mut body = [0u8; 16];
1179 let len = report.encode(&mut body).expect("encode");
1180 let exchange = attacker
1181 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1182 .expect("open");
1183 let (sent, _) = attacker
1184 .send(
1185 exchange,
1186 crate::sc::opcode::STATUS_REPORT,
1187 false,
1188 body.get(..len).expect("body"),
1189 at(0),
1190 0,
1191 &mut scratch,
1192 &mut wire,
1193 )
1194 .expect("send");
1195
1196 let received = node.receive(wire.get_mut(..sent).expect("wire"), PEER, at(1));
1197 assert!(
1198 matches!(received, Ok(Received::Message { .. })),
1199 "an unsecured status report is an ordinary message, got {received:?}"
1200 );
1201 assert!(
1202 node.sessions().find(SessionId(1)).is_some(),
1203 "no unauthenticated datagram may close a session"
1204 );
1205 }
1206
1207 /// §4.16: a group datagram belongs to the group key store, and this layer says so rather
1208 /// than refusing it. Refusing made a node that holds group keys look like a node that
1209 /// cannot receive groupcast at all.
1210 #[test]
1211 fn a_group_datagram_is_handed_back_rather_than_refused() {
1212 let mut node = Node::new(1, 100, 7);
1213 // §4.4.1.2's session type bits: a group message names its Group Session Id and carries
1214 // the session type in the low bits of the security flags.
1215 let mut datagram = [0u8; 32];
1216 datagram[0] = 0b0000_0000; // message flags: no source, no destination
1217 datagram[1..3].copy_from_slice(&0x1234u16.to_le_bytes()); // group session id
1218 datagram[3] = 0b0000_0001; // security flags: session type = group
1219 datagram[4..8].copy_from_slice(&7u32.to_le_bytes()); // message counter
1220
1221 let received = node.receive(&mut datagram, PEER, at(0));
1222 assert!(
1223 matches!(
1224 received,
1225 Ok(Received::Group { session_id, from })
1226 if session_id == SessionId(0x1234) && from == PEER
1227 ),
1228 "expected a group hand-off, got {received:?}"
1229 );
1230 assert_eq!(
1231 node.exchanges().len(),
1232 0,
1233 "a group message opens nothing: §4.16.2 step 2c sets only the P flag"
1234 );
1235 }
1236
1237 /// §4.11.1.4: "If a Node has either sent or received a CloseSession StatusReport, that
1238 /// Node SHALL remove all state associated with the session." The receiving half is the
1239 /// one a node leaves out, because sending one is a decision and receiving one is not.
1240 #[test]
1241 fn a_close_session_report_from_the_peer_closes_the_session_here_too() {
1242 let mut a = Node::new(1, 100, 7);
1243 let mut b = Node::new(2, 200, 9);
1244 let mut scratch = [0u8; 512];
1245 let mut wire = [0u8; 512];
1246
1247 // The same keys at both ends, with opposite roles, is a session the two share.
1248 let mut left = SecureSession::new(
1249 SessionId(1),
1250 SessionId(2),
1251 SessionKind::Case,
1252 crate::session::Role::Initiator,
1253 keys(),
1254 1,
1255 at(0),
1256 );
1257 left.peer = Some(PEER);
1258 let mut right = SecureSession::new(
1259 SessionId(2),
1260 SessionId(1),
1261 SessionKind::Case,
1262 crate::session::Role::Responder,
1263 keys(),
1264 1,
1265 at(0),
1266 );
1267 right.peer = Some(PEER);
1268 a.install_session(left, at(0), 0, &mut scratch, &mut wire)
1269 .expect("install");
1270 b.install_session(right, at(0), 0, &mut scratch, &mut wire)
1271 .expect("install");
1272 b.open(SessionId(2), ProtocolId::INTERACTION_MODEL, at(0))
1273 .expect("an exchange that the close has to take with it");
1274
1275 // A closes its end, which frames the report §4.11.1.4 owes the peer: a new exchange,
1276 // and no R flag.
1277 let report = crate::sc::status::StatusReport {
1278 general: crate::sc::status::GeneralCode::Success,
1279 protocol: ProtocolId::SECURE_CHANNEL,
1280 protocol_code: crate::sc::status::SecureChannelCode::CloseSession as u16,
1281 data: &[],
1282 };
1283 let mut body = [0u8; 16];
1284 let len = report.encode(&mut body).expect("encode");
1285 let exchange = a
1286 .open(SessionId(1), ProtocolId::SECURE_CHANNEL, at(0))
1287 .expect("open");
1288 let (sent, _) = a
1289 .send(
1290 exchange,
1291 crate::sc::opcode::STATUS_REPORT,
1292 false,
1293 body.get(..len).expect("body"),
1294 at(0),
1295 0,
1296 &mut scratch,
1297 &mut wire,
1298 )
1299 .expect("send");
1300
1301 let received = b.receive(wire.get_mut(..sent).expect("wire"), PEER, at(1));
1302 assert!(
1303 matches!(received, Ok(Received::SessionClosed { session }) if session == SessionId(2)),
1304 "expected the session to be closed, got {received:?}"
1305 );
1306 assert!(b.sessions().find(SessionId(2)).is_none());
1307 assert_eq!(
1308 b.exchanges().len(),
1309 0,
1310 "§4.13.3.1: all state associated with the session"
1311 );
1312 }
1313
1314 /// §4.11.1.1: a full session table evicts the least recently used session rather than
1315 /// refusing the handshake. Refusing it is a node that can be commissioned
1316 /// as many times as its session table is long, and never again.
1317 #[test]
1318 fn a_full_session_table_evicts_the_least_recently_used_session() {
1319 // Filled from the table's own capacity, so the test stays about *fullness* rather than
1320 // about a number that used to be the capacity.
1321 const CAP: u16 = SessionTable::<DefaultConfig, 16>::TOTAL as u16;
1322 let mut node = Node::new(1, 100, 7);
1323 let mut scratch = [0u8; 512];
1324 let mut out = [0u8; 512];
1325 for i in 0..CAP {
1326 let evicted = node
1327 .install_session(
1328 session_on(i + 1, 1, at(u64::from(i))),
1329 at(u64::from(i)),
1330 0,
1331 &mut scratch,
1332 &mut out,
1333 )
1334 .expect("install");
1335 assert!(evicted.is_none(), "there was room for session {i}");
1336 }
1337 assert_eq!(node.sessions().len(), usize::from(CAP));
1338
1339 let evicted = node
1340 .install_session(
1341 session_on(CAP + 1, 1, at(u64::from(CAP) + 1)),
1342 at(u64::from(CAP) + 1),
1343 0,
1344 &mut scratch,
1345 &mut out,
1346 )
1347 .expect("install")
1348 .expect("the table was full, so one had to go");
1349
1350 // Step 1: the least recently used, which is the one installed first.
1351 assert_eq!(evicted.session, SessionId(1));
1352 // Step 2a: a datagram for its peer, framed before the session went away.
1353 assert_eq!(evicted.peer, Some(PEER));
1354 assert!(evicted.len > 0, "the CloseSession report was framed");
1355 // Step 2b: and the session itself is gone, with the new one in its place.
1356 assert!(node.sessions().find(SessionId(1)).is_none());
1357 assert!(node.sessions().find(SessionId(CAP + 1)).is_some());
1358 assert_eq!(node.sessions().len(), usize::from(CAP));
1359 }
1360
1361 /// §4.13.3.1: closing a session removes "all state associated with" it, which includes
1362 /// the exchanges on it. An exchange that outlives its session can never be answered on,
1363 /// and holds a slot in a fixed-capacity table until it times out.
1364 #[test]
1365 fn closing_a_session_closes_its_exchanges() {
1366 let mut node = Node::new(1, 100, 7);
1367 let mut scratch = [0u8; 512];
1368 let mut out = [0u8; 512];
1369 node.install_session(session_on(1, 1, at(0)), at(0), 0, &mut scratch, &mut out)
1370 .expect("install");
1371 node.open(SessionId(1), ProtocolId::INTERACTION_MODEL, at(0))
1372 .expect("open");
1373 node.open(SessionId(1), ProtocolId::INTERACTION_MODEL, at(0))
1374 .expect("open");
1375 assert_eq!(node.exchanges().len(), 2);
1376
1377 assert!(node.close_session(SessionId(1)));
1378 assert_eq!(node.exchanges().len(), 0, "the exchanges went with it");
1379 assert!(node.sessions().find(SessionId(1)).is_none());
1380 }
1381
1382 /// §11.18.6.12: `RemoveFabric` takes the fabric's sessions — and their exchanges — while
1383 /// leaving every other fabric's alone.
1384 #[test]
1385 fn removing_a_fabric_takes_its_sessions_and_their_exchanges() {
1386 let mut node = Node::new(1, 100, 7);
1387 let mut scratch = [0u8; 512];
1388 let mut out = [0u8; 512];
1389 node.install_session(session_on(1, 1, at(0)), at(0), 0, &mut scratch, &mut out)
1390 .expect("install");
1391 node.install_session(session_on(2, 2, at(1)), at(1), 0, &mut scratch, &mut out)
1392 .expect("install");
1393 node.open(SessionId(1), ProtocolId::INTERACTION_MODEL, at(0))
1394 .expect("open");
1395 node.open(SessionId(2), ProtocolId::INTERACTION_MODEL, at(0))
1396 .expect("open");
1397
1398 assert_eq!(node.remove_fabric(crate::msg::FabricIndex(1)), 1);
1399 assert!(node.sessions().find(SessionId(1)).is_none());
1400 assert!(node.sessions().find(SessionId(2)).is_some());
1401 assert_eq!(
1402 node.exchanges().len(),
1403 1,
1404 "only the removed fabric's exchange went"
1405 );
1406 }
1407
1408 /// The unsecured session is what PASE runs over before any key exists.
1409 #[test]
1410 fn an_unsecured_message_round_trips_through_a_new_exchange() {
1411 let mut initiator = Node::new(1, 100, 7);
1412 let mut responder = Node::new(2, 200, 9);
1413
1414 let key = initiator
1415 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1416 .expect("open");
1417 let mut wire = [0u8; 512];
1418 let mut scratch = [0u8; 512];
1419 let (len, counter) = initiator
1420 .send(
1421 key,
1422 0x20,
1423 true,
1424 b"pbkdf-param-request",
1425 at(0),
1426 0,
1427 &mut scratch,
1428 &mut wire,
1429 )
1430 .expect("send");
1431
1432 let received = responder
1433 .receive(&mut wire[..len], PEER, at(1))
1434 .expect("receive");
1435 let Received::Message {
1436 exchange,
1437 header,
1438 needs_ack,
1439 payload,
1440 } = received
1441 else {
1442 panic!("expected a message, got {received:?}");
1443 };
1444 assert_eq!(payload, b"pbkdf-param-request");
1445 assert_eq!(header.opcode, 0x20);
1446 assert!(needs_ack, "a reliable message owes an acknowledgement");
1447 // The responder opened its own half of the exchange, with the peer's id.
1448 assert_eq!(exchange.role, Role::Responder);
1449 assert_eq!(exchange.id, key.id);
1450
1451 // ...and the acknowledgement it sends clears the initiator's retransmission.
1452 let mut ack = [0u8; 512];
1453 let ack_len = responder
1454 .acknowledge(exchange, at(1), &mut ack)
1455 .expect("ack");
1456 assert!(ack_len > 0);
1457 assert!(initiator.wake_at().is_some(), "waiting for the ack");
1458 let back = initiator
1459 .receive(&mut ack[..ack_len], PEER, at(2))
1460 .expect("receive ack");
1461 assert!(matches!(back, Received::Acknowledged { .. }));
1462 assert!(
1463 !initiator
1464 .exchanges()
1465 .find(key)
1466 .expect("still open")
1467 .mrp
1468 .is_awaiting_ack(),
1469 "acknowledged, so no retransmission is outstanding"
1470 );
1471 let _ = counter;
1472 }
1473
1474 /// Builds one unsecured datagram from a stranger, with the exchange id and protocol of
1475 /// its choosing — which is everything an off-path attacker controls before any key exists.
1476 fn stranger_datagram(
1477 exchange_id: u16,
1478 protocol: ProtocolId,
1479 reliable: bool,
1480 counter: u32,
1481 out: &mut [u8],
1482 ) -> usize {
1483 let mut sender = Node::new(1, exchange_id, counter);
1484 sender.register(Protocols::SECURE_CHANNEL.with(Protocols::INTERACTION_MODEL));
1485 let key = sender
1486 .open_unsecured(protocol, at(0), 0xE0E0_1234_5678_9ABC)
1487 .expect("open");
1488 let mut scratch = [0u8; 512];
1489 let (len, _) = sender
1490 .send(key, 0x20, reliable, b"x", at(0), 0, &mut scratch, out)
1491 .expect("send");
1492 len
1493 }
1494
1495 /// The exhaustion attack, and the shape CVE-2024-3297 had: every unsecured message with
1496 /// the **I** flag opens an exchange (§4.10.5.2), so a stranger who varies the exchange id
1497 /// fills the table. Without reclamation the node can never open another exchange — which
1498 /// means it can never establish another session, PASE or CASE, for the rest of its uptime.
1499 #[test]
1500 fn a_stranger_cannot_fill_the_exchange_table_for_good() {
1501 let mut node = Node::new(2, 200, 9);
1502 let mut wire = [0u8; 512];
1503
1504 // The whole table, from the table rather than from a literal.
1505 const CAP: u16 = ExchangeTable::<DefaultConfig, 64>::TOTAL as u16;
1506 for id in 0..CAP {
1507 let len = stranger_datagram(
1508 id,
1509 ProtocolId::SECURE_CHANNEL,
1510 true,
1511 u32::from(id) + 1,
1512 &mut wire,
1513 );
1514 let _ = node.receive(&mut wire[..len], PEER, at(0));
1515 }
1516 assert_eq!(
1517 node.exchanges().len(),
1518 usize::from(CAP),
1519 "the table is full"
1520 );
1521
1522 // A legitimate peer arrives while the attacker's entries are still fresh, and is
1523 // refused — which is correct, and is why the entries must not be permanent.
1524 let len = stranger_datagram(CAP + 1, ProtocolId::SECURE_CHANNEL, true, 900, &mut wire);
1525 assert!(node.receive(&mut wire[..len], PEER, at(1)).is_err());
1526
1527 // A minute later nothing has happened on any of them, so they go.
1528 assert!(
1529 node.wake_at().is_some(),
1530 "the node knows it has something to reclaim"
1531 );
1532 node.poll(at(61_000), 0);
1533 assert_eq!(node.exchanges().len(), 0, "every abandoned entry reclaimed");
1534
1535 // ...and the node answers again.
1536 let len = stranger_datagram(901, ProtocolId::SECURE_CHANNEL, true, 901, &mut wire);
1537 assert!(
1538 node.receive(&mut wire[..len], PEER, at(62_000)).is_ok(),
1539 "a node that cannot open an exchange can never establish a session again"
1540 );
1541 }
1542
1543 /// Reclaiming on the timer is not enough on its own: a node whose timers are slow, or
1544 /// which is simply busy, must still not be refusing legitimate peers on behalf of entries
1545 /// that expired long ago.
1546 #[test]
1547 fn a_full_table_reclaims_before_refusing() {
1548 const FULL: usize = ExchangeTable::<DefaultConfig, 64>::TOTAL;
1549 let mut node = Node::new(2, 200, 9);
1550 let mut wire = [0u8; 512];
1551 for id in 0..FULL as u16 {
1552 let len = stranger_datagram(
1553 id,
1554 ProtocolId::SECURE_CHANNEL,
1555 true,
1556 u32::from(id) + 1,
1557 &mut wire,
1558 );
1559 let _ = node.receive(&mut wire[..len], PEER, at(0));
1560 }
1561 assert_eq!(node.exchanges().len(), FULL);
1562
1563 // No `poll` in between — the pressure itself is the trigger.
1564 let len = stranger_datagram(
1565 FULL as u16 + 1,
1566 ProtocolId::SECURE_CHANNEL,
1567 true,
1568 900,
1569 &mut wire,
1570 );
1571 assert!(
1572 node.receive(&mut wire[..len], PEER, at(61_000)).is_ok(),
1573 "the entry that would have refused this one had been idle for a minute"
1574 );
1575 }
1576
1577 /// §4.10.5.2 rule 1: "has a registered Protocol ID". An unregistered protocol is not
1578 /// something this node will ever act on, so it must not cost a table entry.
1579 #[test]
1580 fn an_unregistered_protocol_opens_no_exchange() {
1581 let mut node = Node::new(2, 200, 9);
1582 node.register(Protocols::SECURE_CHANNEL);
1583 let mut wire = [0u8; 512];
1584
1585 // The Interaction Model is not registered on this node.
1586 let len = stranger_datagram(5, ProtocolId::INTERACTION_MODEL, false, 5, &mut wire);
1587 assert!(node.receive(&mut wire[..len], PEER, at(0)).is_err());
1588 assert_eq!(node.exchanges().len(), 0, "rule 3: processing SHALL stop");
1589
1590 // Secure Channel is, so that one is answered.
1591 let len = stranger_datagram(6, ProtocolId::SECURE_CHANNEL, false, 6, &mut wire);
1592 assert!(node.receive(&mut wire[..len], PEER, at(0)).is_ok());
1593 assert_eq!(node.exchanges().len(), 1);
1594 }
1595
1596 /// §4.10.5.2 rule 2: an unregistered protocol that *asks* for an acknowledgement still
1597 /// gets one — withholding it costs the sender five retransmissions — but on an ephemeral
1598 /// exchange that §4.12.5.2.2 closes as soon as the acknowledgement is sent.
1599 #[test]
1600 fn an_unregistered_reliable_message_is_acknowledged_on_an_ephemeral_exchange() {
1601 let mut node = Node::new(2, 200, 9);
1602 node.register(Protocols::SECURE_CHANNEL);
1603 let mut wire = [0u8; 512];
1604 let len = stranger_datagram(7, ProtocolId::BDX, true, 7, &mut wire);
1605
1606 let received = node.receive(&mut wire[..len], PEER, at(0)).expect("routed");
1607 let Received::Message { exchange, .. } = received else {
1608 panic!("expected the ephemeral exchange, got {received:?}")
1609 };
1610 assert_eq!(node.exchanges().len(), 1);
1611 assert!(
1612 node.exchanges().find(exchange).is_some_and(|e| e.ephemeral),
1613 "it is ephemeral"
1614 );
1615
1616 let mut ack = [0u8; 512];
1617 assert!(node.acknowledge(exchange, at(0), &mut ack).expect("ack") > 0);
1618 assert_eq!(
1619 node.exchanges().len(),
1620 0,
1621 "§4.12.5.2.2: the ephemeral exchange SHALL be closed once it has acknowledged"
1622 );
1623 }
1624
1625 /// An exchange that is still trying to deliver something is not abandoned, however quiet
1626 /// the peer has been — §4.10.5.3 step 2b.
1627 #[test]
1628 fn an_exchange_with_a_pending_retransmission_is_never_reaped() {
1629 let mut node = Node::new(1, 100, 7);
1630 let key = node
1631 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1632 .expect("open");
1633 let mut wire = [0u8; 512];
1634 let mut scratch = [0u8; 512];
1635 let _ = node
1636 .send(key, 0x20, true, b"x", at(0), 0, &mut scratch, &mut wire)
1637 .expect("send");
1638
1639 // Far past the idle timeout, and never acknowledged.
1640 node.exchanges_mut()
1641 .reap(at(600_000), EXCHANGE_IDLE_TIMEOUT);
1642 assert_eq!(
1643 node.exchanges().len(),
1644 1,
1645 "a retransmission still pending keeps the exchange open"
1646 );
1647 }
1648
1649 /// §4.13.2.1's Unsecured Session Context, and the rule that no test of this crate against
1650 /// itself could catch.
1651 ///
1652 /// > Ephemeral Initiator Node ID: Randomly selected for each session by the initiator from
1653 /// > the Operational Node ID range and **enclosed by initiator as Source Node ID and
1654 /// > responder as Destination Node ID.**
1655 ///
1656 /// Both halves have to hold, and a stack that encloses *neither* is self-consistent: two
1657 /// nodes built from it commission each other perfectly. The CHIP SDK drops such a message
1658 /// before it reaches any protocol — "Received malformed unsecure packet with source 0x0
1659 /// destination 0x0" — so the symptom is a device no certified controller can pair with,
1660 /// while every test passes.
1661 #[test]
1662 fn an_unsecured_response_carries_the_initiators_ephemeral_node_id() {
1663 const EPHEMERAL: crate::msg::NodeId = crate::msg::NodeId(0x0102_0304_0506_0708);
1664
1665 let mut initiator = Node::new(1, 100, 7);
1666 initiator
1667 .open_unsecured_as_initiator(EPHEMERAL)
1668 .expect("an operational node id");
1669 let mut responder = Node::new(2, 200, 9);
1670
1671 // `open` rather than `open_unsecured`, because the context is the one this test named.
1672 let key = initiator
1673 .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1674 .expect("open");
1675 let mut wire = [0u8; 512];
1676 let mut scratch = [0u8; 512];
1677 let (len, _) = initiator
1678 .send(
1679 key,
1680 0x20,
1681 true,
1682 b"request",
1683 at(0),
1684 0,
1685 &mut scratch,
1686 &mut wire,
1687 )
1688 .expect("send");
1689
1690 // The initiator encloses it as the Source Node ID: flag bit 2 of octet 0, then eight
1691 // octets little-endian after the four-octet counter.
1692 assert_eq!(wire[0] & 0x04, 0x04, "S flag set");
1693 assert_eq!(
1694 u64::from_le_bytes(wire[8..16].try_into().expect("eight octets")),
1695 EPHEMERAL.0,
1696 "and it is the ephemeral id"
1697 );
1698
1699 let received = responder
1700 .receive(&mut wire[..len], PEER, at(1))
1701 .expect("receive");
1702 let Received::Message { exchange, .. } = received else {
1703 panic!("expected a message, got {received:?}")
1704 };
1705 assert_eq!(
1706 responder.unsecured_ephemeral_id(),
1707 Some(EPHEMERAL),
1708 "the responder recorded it as the context's ephemeral initiator id"
1709 );
1710
1711 // ...and encloses it as the *Destination* Node ID on the way back.
1712 let mut back = [0u8; 512];
1713 let (len, _) = responder
1714 .send(
1715 exchange,
1716 0x21,
1717 true,
1718 b"response",
1719 at(1),
1720 0,
1721 &mut scratch,
1722 &mut back,
1723 )
1724 .expect("send");
1725 assert_eq!(back[0] & 0x04, 0, "no S flag on the responder's message");
1726 assert_eq!(back[0] & 0x03, 0x01, "DSIZ = 1, a 64-bit Node ID");
1727 assert_eq!(
1728 u64::from_le_bytes(back[8..16].try_into().expect("eight octets")),
1729 EPHEMERAL.0,
1730 "the destination is the initiator's ephemeral id"
1731 );
1732
1733 // The initiator accepts what comes back.
1734 let round = initiator
1735 .receive(&mut back[..len], PEER, at(2))
1736 .expect("the initiator accepts its own ephemeral id as the destination");
1737 assert!(matches!(round, Received::Message { .. }));
1738 }
1739
1740 /// §4.13.2.1 matches a context by Ephemeral Initiator Node ID and creates a new one when
1741 /// none matches. A node that kept the first would answer a second initiator — the same
1742 /// commissioner coming back for CASE after PASE, most of the time — with replies addressed
1743 /// to a peer that has gone, which the CHIP SDK drops before any protocol sees them.
1744 #[test]
1745 fn a_second_initiator_replaces_the_unsecured_context() {
1746 const FIRST: crate::msg::NodeId = crate::msg::NodeId(0x1111_1111_1111_1111);
1747 const SECOND: crate::msg::NodeId = crate::msg::NodeId(0x2222_2222_2222_2222);
1748
1749 let mut responder = Node::new(2, 200, 9);
1750 let mut wire = [0u8; 512];
1751 let mut scratch = [0u8; 512];
1752
1753 for (n, (ephemeral, counter)) in [(FIRST, 1u32), (SECOND, 2u32)].into_iter().enumerate() {
1754 let mut initiator = Node::new(1, 100 + u16::try_from(n).expect("fits"), counter);
1755 initiator
1756 .open_unsecured_as_initiator(ephemeral)
1757 .expect("operational");
1758 let key = initiator
1759 .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1760 .expect("open");
1761 let (len, _) = initiator
1762 .send(key, 0x20, true, b"x", at(0), 0, &mut scratch, &mut wire)
1763 .expect("send");
1764 let received = responder
1765 .receive(&mut wire[..len], PEER, at(1))
1766 .expect("receive");
1767 let Received::Message { exchange, .. } = received else {
1768 panic!("expected a message")
1769 };
1770 assert_eq!(
1771 responder.unsecured_ephemeral_id(),
1772 Some(ephemeral),
1773 "the newest initiator owns the context"
1774 );
1775
1776 let mut back = [0u8; 512];
1777 let _ = responder
1778 .send(
1779 exchange,
1780 0x21,
1781 true,
1782 b"y",
1783 at(1),
1784 0,
1785 &mut scratch,
1786 &mut back,
1787 )
1788 .expect("send");
1789 assert_eq!(
1790 u64::from_le_bytes(back[8..16].try_into().expect("eight octets")),
1791 ephemeral.0,
1792 "and the reply is addressed to it"
1793 );
1794 }
1795 }
1796
1797 /// §4.13.2.1 constrains the ephemeral id to the Operational Node ID range, because it is
1798 /// what the responder will put in a Destination Node ID field.
1799 #[test]
1800 fn an_ephemeral_id_outside_the_operational_range_is_refused() {
1801 let mut node = Node::new(1, 100, 7);
1802 assert!(
1803 node.open_unsecured_as_initiator(crate::msg::NodeId::UNSPECIFIED)
1804 .is_err()
1805 );
1806 assert!(
1807 node.open_unsecured_as_initiator(crate::msg::NodeId(1))
1808 .is_ok()
1809 );
1810 }
1811
1812 /// §4.12.2.2: a duplicate is acknowledged and not delivered.
1813 #[test]
1814 fn a_duplicate_is_acknowledged_and_not_delivered_twice() {
1815 let mut initiator = Node::new(1, 100, 7);
1816 let mut responder = Node::new(2, 200, 9);
1817 let key = initiator
1818 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1819 .expect("open");
1820
1821 let mut wire = [0u8; 512];
1822 let mut scratch = [0u8; 512];
1823 let (len, _) = initiator
1824 .send(key, 0x20, true, b"once", at(0), 0, &mut scratch, &mut wire)
1825 .expect("send");
1826 let copy = wire;
1827
1828 let first = responder
1829 .receive(&mut wire[..len], PEER, at(1))
1830 .expect("first");
1831 assert!(matches!(first, Received::Message { .. }));
1832
1833 let mut again = copy;
1834 let second = responder
1835 .receive(&mut again[..len], PEER, at(2))
1836 .expect("second");
1837 match second {
1838 Received::Duplicate { needs_ack, .. } => {
1839 assert!(needs_ack, "still acknowledged — the sender's ack was lost");
1840 }
1841 other => panic!("a repeat must not reach the application: {other:?}"),
1842 }
1843 }
1844
1845 /// A message for a session this node does not have is refused, not guessed at.
1846 #[test]
1847 fn a_message_for_an_unknown_session_is_refused() {
1848 let mut node = Node::new(1, 100, 7);
1849 let mut wire = [0u8; 64];
1850 // Flags: version 0, no source/destination. Session id 0x1234, unicast.
1851 wire[0] = 0x00;
1852 wire[1] = 0x34;
1853 wire[2] = 0x12;
1854 wire[3] = 0x00;
1855 let err = node
1856 .receive(&mut wire, PEER, at(0))
1857 .expect_err("no session");
1858 assert_eq!(err.code(), ErrorCode::NoSession);
1859 }
1860
1861 /// A response to an exchange that was never opened is refused (§4.4.3.1).
1862 #[test]
1863 fn a_message_from_a_responder_cannot_open_an_exchange() {
1864 let mut initiator = Node::new(1, 100, 7);
1865 let mut responder = Node::new(2, 200, 9);
1866 let key = initiator
1867 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1868 .expect("open");
1869 let mut wire = [0u8; 512];
1870 let mut scratch = [0u8; 512];
1871 let (len, _) = initiator
1872 .send(
1873 key,
1874 0x20,
1875 false,
1876 b"hello",
1877 at(0),
1878 0,
1879 &mut scratch,
1880 &mut wire,
1881 )
1882 .expect("send");
1883 // Clear the I flag in the protocol header: now it claims to be a *response*.
1884 //
1885 // The offset is the *message* header's real length, which is not a constant: an
1886 // unsecured initiator encloses its Ephemeral Initiator Node ID (§4.13.2.1), so the
1887 // header is eight octets longer than a bare one. Decoding it is the only way to know.
1888 let (sent_header, _) = MessageHeader::decode(&wire[..len]).expect("decode");
1889 let header_len = sent_header.encoded_len();
1890 wire[header_len] &= !0x01;
1891
1892 let err = responder
1893 .receive(&mut wire[..len], PEER, at(1))
1894 .expect_err("a response answers a question nobody asked");
1895 assert_eq!(err.code(), ErrorCode::NoExchange);
1896 }
1897
1898 /// The retransmission timer fires, and names the counter to resend (§4.12.2.1).
1899 #[test]
1900 fn an_unacknowledged_message_is_retransmitted_with_its_own_counter() {
1901 let mut initiator = Node::new(1, 100, 7);
1902 let key = initiator
1903 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1904 .expect("open");
1905 let mut wire = [0u8; 512];
1906 let mut scratch = [0u8; 512];
1907 let (_, counter) = initiator
1908 .send(key, 0x20, true, b"lost", at(0), 0, &mut scratch, &mut wire)
1909 .expect("send");
1910
1911 let deadline = initiator.wake_at().expect("a reliable send arms a timer");
1912 match initiator.poll(deadline, 0) {
1913 Some(Due::Retransmit {
1914 exchange,
1915 counter: again,
1916 }) => {
1917 assert_eq!(exchange, key);
1918 assert_eq!(
1919 again, counter,
1920 "the same counter: a new one would be a new message and a reused nonce"
1921 );
1922 }
1923 other => panic!("expected a retransmission, got {other:?}"),
1924 }
1925 }
1926}