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 /// Closes an exchange.
590 pub fn close(&mut self, exchange: ExchangeKey) -> bool {
591 self.exchanges.close(exchange)
592 }
593
594 /// Processes one arriving datagram, in place (§4.7.2).
595 ///
596 /// `buf` is decrypted in place, so the returned payload borrows it. On any failure the
597 /// contents of `buf` are unspecified — §3.6.2 says a failed tag check leaves the payload
598 /// undefined — and nothing in this node's state has moved.
599 pub fn receive<'b>(
600 &mut self,
601 buf: &'b mut [u8],
602 from: Peer,
603 now: Instant,
604 ) -> Result<Received<'b>> {
605 let head = preview(buf)?;
606 if matches!(head.session_type, SessionType::Group) {
607 // §4.16: a group message is keyed by an *operational group key* and belongs to no
608 // session, so none of this function's machinery applies to it — there is no
609 // session to find, no replay window of a session's to move, and no exchange, since
610 // §4.16.2 step 2c sets only the P flag, so a group message is never
611 // reliable and never acknowledged.
612 //
613 // It is handed back rather than refused. A device with a group key store routes it
614 // to [`group::wire::receive`](crate::group::wire::receive), which is the same layer
615 // as this one for keys it holds rather than sessions; a device without one drops
616 // it. Answering `Unsupported` here made the two halves look like one missing one.
617 return Ok(Received::Group {
618 session_id: head.session_id,
619 from,
620 });
621 }
622
623 let (header, range) = if head.session_id == SessionId::UNSECURED {
624 let (header, rest) = MessageHeader::decode(buf)?;
625 if !header.is_unsecured() {
626 bail!(MessageReserved)
627 }
628 let start = buf.len().saturating_sub(rest.len());
629 (header, start..buf.len())
630 } else {
631 let session = self
632 .sessions
633 .find(head.session_id)
634 .ok_or(Error::new(ErrorCode::NoSession))?;
635 // §4.8.1.1's nonce depends on how the session was established, and getting it
636 // wrong fails the tag rather than silently mis-decrypting — but naming it here
637 // keeps the two readings from ever being confused.
638 let nonce_source = match session.kind {
639 SessionKind::Pase => NonceSource::Pase,
640 SessionKind::Case => NonceSource::Case(session.peer_node_id),
641 };
642 let keys = session.keys.receiving(session.role).clone();
643 unprotect(buf, &keys, nonce_source)?
644 };
645
646 // Authenticated. Only now may any counter move.
647 let verdict = if header.is_unsecured() {
648 self.unsecured_window.accept(header.message_counter)
649 } else {
650 let session = self
651 .sessions
652 .find_mut(head.session_id)
653 .ok_or(Error::new(ErrorCode::NoSession))?;
654 // Authenticated, so it is the peer and this is where it is. A node that opens an
655 // exchange of its own — §8.5.3's subscription reports above all — has no other way
656 // to learn the address, and an exchange with no peer sends nothing.
657 session.peer = Some(from);
658 session.accept_counter(header.message_counter, now)
659 };
660
661 let Some(payload) = buf.get(range) else {
662 bail!(MessageTruncated)
663 };
664 let (protocol_header, body) = ProtocolHeader::decode(payload)?;
665
666 // §4.13.2.1's context matching: "Else if the message carries a Source Node ID … Set
667 // Session Role to responder … Record the incoming message's Source Node ID as Ephemeral
668 // Initiator Node ID." Recorded here, before the exchange is routed, so that the very
669 // first reply carries it back as the Destination Node ID.
670 // §4.13.2.1 step 1c: "Else discard the message." A message that matches no context and
671 // carries no Source Node ID belongs to no session, and accepting it is what let this
672 // crate's own initiator get away with sending one — the two halves agreed with each
673 // other and disagreed with the specification.
674 if header.is_unsecured() && header.source.is_none() {
675 let addressed_to_our_context = matches!(
676 (self.unsecured_peer, header.destination),
677 (Some(peer), Destination::Node(id)) if peer.ephemeral_initiator == id
678 );
679 if !addressed_to_our_context {
680 bail!(NoSession)
681 }
682 }
683 if header.is_unsecured()
684 && let Some(source) = header.source
685 && self
686 .unsecured_peer
687 .is_none_or(|peer| peer.ephemeral_initiator != source)
688 {
689 // §4.13.2.1 matches a context by Ephemeral Initiator Node ID and creates a *new*
690 // one when no context matches. A different id is a different session — a second
691 // commissioner, or the same one returning for CASE after PASE — so the context is
692 // replaced rather than kept. Keeping the first would address every reply to a peer
693 // that has gone, which the CHIP SDK drops as belonging to no session of its own.
694 //
695 // One context at a time is the simplification here; the specification allows
696 // several. What makes it safe is that the *contents* are two header fields and a
697 // replay window, and admitting a second handshake at all is refused a layer up by
698 // `PaseAdmission`.
699 self.unsecured_peer = Some(UnsecuredPeer {
700 ephemeral_initiator: source,
701 we_initiated: false,
702 });
703 }
704
705 let duplicate = matches!(verdict, Verdict::Duplicate);
706 let key = self.route(header.session_id, &protocol_header, duplicate, now)?;
707 let Some(exchange) = self.exchanges.find_mut(key) else {
708 bail!(NoExchange)
709 };
710 exchange.touch(now);
711 // Where the reply goes, and — §4.12.4 — whether MRP runs on this exchange. A peer
712 // that moved (a Thread node changing address, say) is followed here.
713 exchange.peer = Some(from);
714 exchange.mrp.note_peer_activity(now);
715
716 // §4.12.1: an acknowledgement may ride on any message, so it is taken before the
717 // message's own kind is considered.
718 if let Some(acknowledged) = protocol_header.acknowledged_counter {
719 exchange.mrp.on_ack(acknowledged, now);
720 }
721
722 if protocol_header.reliability {
723 exchange
724 .mrp
725 .on_reliable_received(header.message_counter, now, duplicate);
726 }
727 let needs_ack = protocol_header.reliability;
728
729 if duplicate {
730 return Ok(Received::Duplicate {
731 exchange: key,
732 needs_ack,
733 });
734 }
735 if protocol_header.protocol == ProtocolId::SECURE_CHANNEL
736 && protocol_header.opcode == crate::sc::opcode::MRP_STANDALONE_ACK
737 {
738 // A standalone acknowledgement carries nothing above the reliability layer.
739 return Ok(Received::Acknowledged { exchange: key });
740 }
741
742 // §4.11.1.4: "If a Node has either sent or received a CloseSession StatusReport, that
743 // Node SHALL remove all state associated with the session." Both halves are the
744 // message layer's, and this is the half a node is most likely to leave out — sending
745 // one is a decision it makes, receiving one is something that happens to it.
746 //
747 // Handled here rather than handed upward because the rule is about *this* layer's
748 // state: the session, its keys, its counters and its exchanges, including the exchange
749 // this message arrived on. A node that passed it up would answer on a session the
750 // specification says is already gone.
751 if !header.is_unsecured()
752 && protocol_header.protocol == ProtocolId::SECURE_CHANNEL
753 && protocol_header.opcode == crate::sc::opcode::STATUS_REPORT
754 && matches!(
755 crate::sc::status::StatusReport::decode(body),
756 Ok(report)
757 if report.protocol == ProtocolId::SECURE_CHANNEL
758 && report.protocol_code
759 == crate::sc::status::SecureChannelCode::CloseSession as u16
760 )
761 {
762 let session = header.session_id;
763 self.close_session(session);
764 return Ok(Received::SessionClosed { session });
765 }
766
767 Ok(Received::Message {
768 exchange: key,
769 header: protocol_header,
770 needs_ack,
771 payload: body,
772 })
773 }
774
775 /// Finds or opens the exchange a message belongs to (§4.10.5.2).
776 ///
777 /// The three rules are in order, and the order is what bounds the table:
778 ///
779 /// 1. "If the unsolicited message is not marked as having a duplicate message counter,
780 /// **has a registered Protocol ID**, and the I Flag is set: create a new exchange."
781 /// 2. "Otherwise, if the message has the R Flag set: create an *ephemeral* exchange … and
782 /// send an immediate standalone acknowledgement. The message SHALL NOT be forwarded to
783 /// the upper layer."
784 /// 3. "Otherwise, processing of the message SHALL stop."
785 ///
786 /// Rule 3 is the one that matters most and is the easiest to leave out: a message this
787 /// node will never act on, and which is not even asking for an acknowledgement, must not
788 /// cost a table entry. Without it every datagram that reaches the port allocates.
789 fn route(
790 &mut self,
791 session: SessionId,
792 header: &ProtocolHeader,
793 duplicate: bool,
794 now: Instant,
795 ) -> Result<ExchangeKey> {
796 if let Some(exchange) =
797 self.exchanges
798 .find_for_message(session, header.exchange_id, header.initiator)
799 {
800 return Ok(exchange.key);
801 }
802 // Only a message *from* an initiator may open an exchange. One claiming to be from a
803 // responder with no exchange to respond to is answering a question nobody asked.
804 if !header.initiator {
805 bail!(NoExchange)
806 }
807 let params = self.mrp_params(session);
808 if !duplicate && self.protocols.contains(header.protocol) {
809 return self.exchanges.open_responder(
810 session,
811 header.exchange_id,
812 header.protocol,
813 params,
814 now,
815 );
816 }
817 if header.reliability {
818 // Rule 2. The sender is owed an acknowledgement even though nothing here will
819 // read its message — withholding it costs five retransmissions — but the entry
820 // that carries it is closed as soon as it has been sent.
821 return self.exchanges.open_ephemeral(
822 session,
823 header.exchange_id,
824 header.protocol,
825 params,
826 now,
827 );
828 }
829 // Rule 3.
830 bail!(NoExchange)
831 }
832
833 /// Builds an outgoing message on an exchange (§4.7.1).
834 ///
835 /// `reliable` sets the MRP **R** flag; a reliable message is remembered for
836 /// retransmission until it is acknowledged, and [`Messaging::poll`] is what resends it.
837 /// `randomness` is the jitter draw of §4.12.2.1 and should come from
838 /// [`Rng`](crate::platform::Rng).
839 ///
840 /// Returns how many octets of `out` the datagram occupies, and the counter it was sent
841 /// with — which is what a retransmission is identified by.
842 #[expect(
843 clippy::too_many_arguments,
844 reason = "every one is a distinct fact about the message; bundling them into a \
845 struct would only move the same list one line up"
846 )]
847 pub fn send(
848 &mut self,
849 exchange: ExchangeKey,
850 opcode: u8,
851 reliable: bool,
852 payload: &[u8],
853 now: Instant,
854 randomness: u32,
855 scratch: &mut [u8],
856 out: &mut [u8],
857 ) -> Result<(usize, u32)> {
858 let Some(open) = self.exchanges.find(exchange) else {
859 bail!(NoExchange)
860 };
861 let protocol = open.protocol;
862 // §4.12.4: "Reliable messages sent over TCP, PAFTP, or BTP SHALL utilize the
863 // underlying reliability mechanisms of those transports and SHOULD NOT set the R
864 // Flag." Running MRP on top of BTP would retransmit a message BTP has already
865 // guaranteed, and BTP would carry the duplicate faithfully.
866 let reliable = reliable && !open.is_transport_reliable();
867 let piggyback = self
868 .exchanges
869 .find_mut(exchange)
870 .and_then(|e| e.mrp.take_piggyback());
871
872 let protocol_header = ProtocolHeader {
873 initiator: exchange.role.is_initiator(),
874 acknowledged_counter: piggyback,
875 reliability: reliable,
876 exchange_id: exchange.id,
877 protocol,
878 opcode,
879 };
880
881 let counter = self.next_counter(exchange.session, now)?;
882 let written = self.frame(
883 exchange.session,
884 counter,
885 &protocol_header,
886 payload,
887 scratch,
888 out,
889 )?;
890
891 if reliable && let Some(open) = self.exchanges.find_mut(exchange) {
892 open.mrp.on_send(counter, now, randomness)?;
893 }
894 Ok((written, counter))
895 }
896
897 /// Sends the standalone acknowledgement a [`Received`] said was owed (§4.12.1).
898 ///
899 /// A standalone ack is *not* reliable — acknowledging an acknowledgement would never
900 /// terminate — and carries no payload.
901 pub fn acknowledge(
902 &mut self,
903 exchange: ExchangeKey,
904 now: Instant,
905 out: &mut [u8],
906 ) -> Result<usize> {
907 let Some(open) = self.exchanges.find_mut(exchange) else {
908 bail!(NoExchange)
909 };
910 let ephemeral = open.ephemeral;
911 let Some(acknowledged) = open.mrp.take_piggyback() else {
912 // Nothing owed: the acknowledgement was already carried by an earlier message.
913 if ephemeral {
914 self.exchanges.close(exchange);
915 }
916 return Ok(0);
917 };
918 let protocol_header = ProtocolHeader {
919 initiator: exchange.role.is_initiator(),
920 acknowledged_counter: Some(acknowledged),
921 reliability: false,
922 exchange_id: exchange.id,
923 // §4.12.7.1: "The Protocol ID SHALL be set to PROTOCOL_ID_SECURE_CHANNEL."
924 //
925 // Not the exchange's protocol, which is the natural thing to write and what this
926 // did: the opcode is Secure Channel's, so sending it under the exchange's protocol
927 // id produces a message that decodes as, say, Interaction Model opcode 0x10 — an
928 // opcode the Interaction Model does not define. The CHIP SDK prints it as
929 // `IM:----` and answers `Invalid message type`, which ends the interaction the
930 // acknowledgement was supposed to keep alive.
931 //
932 // MRP is a property of the *exchange layer*, below the protocol running on it, and
933 // this is where that shows on the wire.
934 protocol: ProtocolId::SECURE_CHANNEL,
935 opcode: crate::sc::opcode::MRP_STANDALONE_ACK,
936 };
937 let counter = self.next_counter(exchange.session, now)?;
938 // A standalone acknowledgement carries no payload, so the body being joined is the
939 // protocol header alone and the scratch never needs to be larger than one.
940 let mut scratch = [0u8; PROTOCOL_HEADER_MAX];
941 let written = self.frame(
942 exchange.session,
943 counter,
944 &protocol_header,
945 &[],
946 &mut scratch,
947 out,
948 )?;
949 // §4.12.5.2.2: "If the Exchange is marked as an ephemeral exchange the Exchange SHALL
950 // be closed." It existed only to carry this acknowledgement, and holding it open is
951 // what would make answering a stranger politely cost a table entry.
952 if ephemeral {
953 self.exchanges.close(exchange);
954 }
955 Ok(written)
956 }
957
958 /// Takes the next message counter for a session (§4.6.1).
959 fn next_counter(&mut self, session: SessionId, now: Instant) -> Result<u32> {
960 if session == SessionId::UNSECURED {
961 self.unsecured_counter.take()
962 } else {
963 self.sessions
964 .find_mut(session)
965 .ok_or(Error::new(ErrorCode::NoSession))?
966 .next_counter(now)
967 }
968 }
969
970 /// Frames, and encrypts when the session is secure.
971 fn frame(
972 &self,
973 session: SessionId,
974 counter: u32,
975 protocol_header: &ProtocolHeader,
976 payload: &[u8],
977 scratch: &mut [u8],
978 out: &mut [u8],
979 ) -> Result<usize> {
980 // §4.8's AEAD needs the protocol header and the payload contiguous before it can
981 // encrypt them, and this is where they are joined. The buffer is the caller's
982 // because its size is the *transport's*: a datagram node needs
983 // [`MAX_UDP_MESSAGE`](crate::config::MAX_UDP_MESSAGE) and nothing more, and a node on
984 // TCP needs the framer's own `N` — §4.15.2.3's Maximum Message Size, which is the whole
985 // reason §4.15 exists and is far too much to put on the stack of every node that
986 // never opens a connection.
987 let header_len = protocol_header.encode(scratch)?;
988 let end = header_len
989 .checked_add(payload.len())
990 .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
991 let Some(slot) = scratch.get_mut(header_len..end) else {
992 bail!(BufferTooSmall)
993 };
994 slot.copy_from_slice(payload);
995 let Some(body) = scratch.get(..end) else {
996 bail!(BufferTooSmall)
997 };
998
999 if session == SessionId::UNSECURED {
1000 // §4.13.2.1: the Ephemeral Initiator Node ID is "enclosed by initiator as Source
1001 // Node ID and responder as Destination Node ID". Which field it goes in is decided
1002 // by which end of the context this node is, and a message carrying neither is one
1003 // the peer cannot associate with any session — the CHIP SDK drops it outright.
1004 let (source, destination) = match self.unsecured_peer {
1005 Some(peer) if peer.we_initiated => {
1006 (Some(peer.ephemeral_initiator), Destination::None)
1007 }
1008 Some(peer) => (None, Destination::Node(peer.ephemeral_initiator)),
1009 None => (None, Destination::None),
1010 };
1011 let header = MessageHeader {
1012 session_id: SessionId::UNSECURED,
1013 message_counter: counter,
1014 source,
1015 destination,
1016 ..MessageHeader::default()
1017 };
1018 let header_len = header.encode(out)?;
1019 let total = header_len
1020 .checked_add(body.len())
1021 .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
1022 let Some(slot) = out.get_mut(header_len..total) else {
1023 bail!(BufferTooSmall)
1024 };
1025 slot.copy_from_slice(body);
1026 return Ok(total);
1027 }
1028
1029 let found = self
1030 .sessions
1031 .find(session)
1032 .ok_or(Error::new(ErrorCode::NoSession))?;
1033 let header = MessageHeader {
1034 session_id: found.peer_session_id,
1035 message_counter: counter,
1036 // §4.4.1.5: the Source Node ID is elided on a secure unicast session, where the
1037 // session itself already says who is speaking.
1038 source: None,
1039 destination: Destination::None,
1040 // §4.9 is the sender's choice on a unicast session; see
1041 // [`Messaging::set_privacy`]. A PASE session is never private: it has no
1042 // operational identity to correlate, so there would be nothing to hide.
1043 privacy: self.privacy && matches!(found.kind, SessionKind::Case),
1044 ..MessageHeader::default()
1045 };
1046 let nonce_source = match found.kind {
1047 SessionKind::Pase => NonceSource::Pase,
1048 SessionKind::Case => NonceSource::Case(found.local_node_id),
1049 };
1050 let keys = found.keys.sending(found.role);
1051 protect(&header, nonce_source, body, keys, out)
1052 }
1053
1054 /// When [`Messaging::poll`] next needs to be called.
1055 ///
1056 /// The earlier of a reliability deadline and the next moment an abandoned exchange could
1057 /// be reclaimed, so a node that honours this wake-up gets §4.10.5.3's cleanup without
1058 /// scheduling anything of its own.
1059 #[must_use]
1060 pub fn wake_at(&self) -> Option<Instant> {
1061 let reap = self.exchanges.reap_deadline(EXCHANGE_IDLE_TIMEOUT);
1062 match (self.exchanges.poll_deadline(), reap) {
1063 (Some(a), Some(b)) => Some(if a <= b { a } else { b }),
1064 (Some(a), None) => Some(a),
1065 (None, b) => b,
1066 }
1067 }
1068
1069 /// Drives the reliability timers (§4.12.2.1) and reclaims abandoned exchanges (§4.10.5.3).
1070 ///
1071 /// Returns one action at a time; call until it returns `None`.
1072 ///
1073 /// Reaping happens here rather than in a method a node has to remember to call, because an
1074 /// exchange table reclaimed only on request is one an attacker fills at leisure: every
1075 /// unsecured datagram with the **I** flag opens an entry (§4.10.5.2), and `X` of them
1076 /// would otherwise deny every later session establishment for the node's whole uptime.
1077 pub fn poll(&mut self, now: Instant, randomness: u32) -> Option<Due> {
1078 self.exchanges.reap(now, EXCHANGE_IDLE_TIMEOUT);
1079 let expired = self
1080 .exchanges
1081 .iter()
1082 .find(|e| e.mrp.poll_deadline().is_some_and(|at| at <= now))
1083 .map(|e| e.key)?;
1084 let open = self.exchanges.find_mut(expired)?;
1085 match open.mrp.on_timeout(now, randomness) {
1086 OnTimeout::Retransmit { counter, .. } => Some(Due::Retransmit {
1087 exchange: expired,
1088 counter,
1089 }),
1090 // §4.12.5.2.2: nothing to piggyback on, so the acknowledgement goes on its own.
1091 OnTimeout::SendStandaloneAck { .. } => Some(Due::Acknowledge { exchange: expired }),
1092 OnTimeout::GiveUp { .. } => {
1093 self.exchanges.close(expired);
1094 Some(Due::Abandoned { exchange: expired })
1095 }
1096 OnTimeout::Nothing => None,
1097 }
1098 }
1099}
1100
1101#[cfg(test)]
1102mod tests {
1103 use super::*;
1104 use crate::config::{Capacity, DefaultConfig};
1105 use crate::exchange::Role;
1106
1107 type Node = Messaging<DefaultConfig>;
1108
1109 fn at(ms: u64) -> Instant {
1110 Instant::from_micros(ms.saturating_mul(1000))
1111 }
1112
1113 const PEER: Peer = Peer::Udp(crate::platform::PeerAddr::new([
1114 0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1115 ]));
1116
1117 fn keys() -> crate::session::EstablishedKeys {
1118 crate::session::EstablishedKeys::derive(b"shared secret", &[]).expect("derive")
1119 }
1120
1121 fn session_on(id: u16, fabric: u8, now: Instant) -> SecureSession {
1122 let mut s = SecureSession::new(
1123 SessionId(id),
1124 SessionId(id.wrapping_add(100)),
1125 SessionKind::Case,
1126 crate::session::Role::Responder,
1127 keys(),
1128 1,
1129 now,
1130 );
1131 s.fabric_index = crate::msg::FabricIndex(fabric);
1132 s.peer = Some(PEER);
1133 s
1134 }
1135
1136 /// §4.11.1.4: "The CloseSession StatusReport SHALL only be sent encrypted within an
1137 /// exchange associated with a PASE or CASE session." So one that arrives on the *unsecured*
1138 /// session closes nothing — otherwise anybody who can reach the port could end a
1139 /// commissioned node's sessions with a datagram costing them nothing to send.
1140 #[test]
1141 fn an_unsecured_close_session_report_closes_nothing() {
1142 let mut node = Node::new(1, 100, 7);
1143 let mut scratch = [0u8; 512];
1144 let mut wire = [0u8; 512];
1145 node.install_session(session_on(1, 1, at(0)), at(0), 0, &mut scratch, &mut wire)
1146 .expect("install");
1147
1148 // A stranger's unsecured datagram carrying exactly the report a peer would send.
1149 let mut attacker = Node::new(2, 200, 9);
1150 let report = crate::sc::status::StatusReport {
1151 general: crate::sc::status::GeneralCode::Success,
1152 protocol: ProtocolId::SECURE_CHANNEL,
1153 protocol_code: crate::sc::status::SecureChannelCode::CloseSession as u16,
1154 data: &[],
1155 };
1156 let mut body = [0u8; 16];
1157 let len = report.encode(&mut body).expect("encode");
1158 let exchange = attacker
1159 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1160 .expect("open");
1161 let (sent, _) = attacker
1162 .send(
1163 exchange,
1164 crate::sc::opcode::STATUS_REPORT,
1165 false,
1166 body.get(..len).expect("body"),
1167 at(0),
1168 0,
1169 &mut scratch,
1170 &mut wire,
1171 )
1172 .expect("send");
1173
1174 let received = node.receive(wire.get_mut(..sent).expect("wire"), PEER, at(1));
1175 assert!(
1176 matches!(received, Ok(Received::Message { .. })),
1177 "an unsecured status report is an ordinary message, got {received:?}"
1178 );
1179 assert!(
1180 node.sessions().find(SessionId(1)).is_some(),
1181 "no unauthenticated datagram may close a session"
1182 );
1183 }
1184
1185 /// §4.16: a group datagram belongs to the group key store, and this layer says so rather
1186 /// than refusing it. Refusing made a node that holds group keys look like a node that
1187 /// cannot receive groupcast at all.
1188 #[test]
1189 fn a_group_datagram_is_handed_back_rather_than_refused() {
1190 let mut node = Node::new(1, 100, 7);
1191 // §4.4.1.2's session type bits: a group message names its Group Session Id and carries
1192 // the session type in the low bits of the security flags.
1193 let mut datagram = [0u8; 32];
1194 datagram[0] = 0b0000_0000; // message flags: no source, no destination
1195 datagram[1..3].copy_from_slice(&0x1234u16.to_le_bytes()); // group session id
1196 datagram[3] = 0b0000_0001; // security flags: session type = group
1197 datagram[4..8].copy_from_slice(&7u32.to_le_bytes()); // message counter
1198
1199 let received = node.receive(&mut datagram, PEER, at(0));
1200 assert!(
1201 matches!(
1202 received,
1203 Ok(Received::Group { session_id, from })
1204 if session_id == SessionId(0x1234) && from == PEER
1205 ),
1206 "expected a group hand-off, got {received:?}"
1207 );
1208 assert_eq!(
1209 node.exchanges().len(),
1210 0,
1211 "a group message opens nothing: §4.16.2 step 2c sets only the P flag"
1212 );
1213 }
1214
1215 /// §4.11.1.4: "If a Node has either sent or received a CloseSession StatusReport, that
1216 /// Node SHALL remove all state associated with the session." The receiving half is the
1217 /// one a node leaves out, because sending one is a decision and receiving one is not.
1218 #[test]
1219 fn a_close_session_report_from_the_peer_closes_the_session_here_too() {
1220 let mut a = Node::new(1, 100, 7);
1221 let mut b = Node::new(2, 200, 9);
1222 let mut scratch = [0u8; 512];
1223 let mut wire = [0u8; 512];
1224
1225 // The same keys at both ends, with opposite roles, is a session the two share.
1226 let mut left = SecureSession::new(
1227 SessionId(1),
1228 SessionId(2),
1229 SessionKind::Case,
1230 crate::session::Role::Initiator,
1231 keys(),
1232 1,
1233 at(0),
1234 );
1235 left.peer = Some(PEER);
1236 let mut right = SecureSession::new(
1237 SessionId(2),
1238 SessionId(1),
1239 SessionKind::Case,
1240 crate::session::Role::Responder,
1241 keys(),
1242 1,
1243 at(0),
1244 );
1245 right.peer = Some(PEER);
1246 a.install_session(left, at(0), 0, &mut scratch, &mut wire)
1247 .expect("install");
1248 b.install_session(right, at(0), 0, &mut scratch, &mut wire)
1249 .expect("install");
1250 b.open(SessionId(2), ProtocolId::INTERACTION_MODEL, at(0))
1251 .expect("an exchange that the close has to take with it");
1252
1253 // A closes its end, which frames the report §4.11.1.4 owes the peer: a new exchange,
1254 // and no R flag.
1255 let report = crate::sc::status::StatusReport {
1256 general: crate::sc::status::GeneralCode::Success,
1257 protocol: ProtocolId::SECURE_CHANNEL,
1258 protocol_code: crate::sc::status::SecureChannelCode::CloseSession as u16,
1259 data: &[],
1260 };
1261 let mut body = [0u8; 16];
1262 let len = report.encode(&mut body).expect("encode");
1263 let exchange = a
1264 .open(SessionId(1), ProtocolId::SECURE_CHANNEL, at(0))
1265 .expect("open");
1266 let (sent, _) = a
1267 .send(
1268 exchange,
1269 crate::sc::opcode::STATUS_REPORT,
1270 false,
1271 body.get(..len).expect("body"),
1272 at(0),
1273 0,
1274 &mut scratch,
1275 &mut wire,
1276 )
1277 .expect("send");
1278
1279 let received = b.receive(wire.get_mut(..sent).expect("wire"), PEER, at(1));
1280 assert!(
1281 matches!(received, Ok(Received::SessionClosed { session }) if session == SessionId(2)),
1282 "expected the session to be closed, got {received:?}"
1283 );
1284 assert!(b.sessions().find(SessionId(2)).is_none());
1285 assert_eq!(
1286 b.exchanges().len(),
1287 0,
1288 "§4.13.3.1: all state associated with the session"
1289 );
1290 }
1291
1292 /// §4.11.1.1: a full session table evicts the least recently used session rather than
1293 /// refusing the handshake. Refusing it is a node that can be commissioned
1294 /// as many times as its session table is long, and never again.
1295 #[test]
1296 fn a_full_session_table_evicts_the_least_recently_used_session() {
1297 // Filled from the table's own capacity, so the test stays about *fullness* rather than
1298 // about a number that used to be the capacity.
1299 const CAP: u16 = SessionTable::<DefaultConfig, 16>::TOTAL as u16;
1300 let mut node = Node::new(1, 100, 7);
1301 let mut scratch = [0u8; 512];
1302 let mut out = [0u8; 512];
1303 for i in 0..CAP {
1304 let evicted = node
1305 .install_session(
1306 session_on(i + 1, 1, at(u64::from(i))),
1307 at(u64::from(i)),
1308 0,
1309 &mut scratch,
1310 &mut out,
1311 )
1312 .expect("install");
1313 assert!(evicted.is_none(), "there was room for session {i}");
1314 }
1315 assert_eq!(node.sessions().len(), usize::from(CAP));
1316
1317 let evicted = node
1318 .install_session(
1319 session_on(CAP + 1, 1, at(u64::from(CAP) + 1)),
1320 at(u64::from(CAP) + 1),
1321 0,
1322 &mut scratch,
1323 &mut out,
1324 )
1325 .expect("install")
1326 .expect("the table was full, so one had to go");
1327
1328 // Step 1: the least recently used, which is the one installed first.
1329 assert_eq!(evicted.session, SessionId(1));
1330 // Step 2a: a datagram for its peer, framed before the session went away.
1331 assert_eq!(evicted.peer, Some(PEER));
1332 assert!(evicted.len > 0, "the CloseSession report was framed");
1333 // Step 2b: and the session itself is gone, with the new one in its place.
1334 assert!(node.sessions().find(SessionId(1)).is_none());
1335 assert!(node.sessions().find(SessionId(CAP + 1)).is_some());
1336 assert_eq!(node.sessions().len(), usize::from(CAP));
1337 }
1338
1339 /// §4.13.3.1: closing a session removes "all state associated with" it, which includes
1340 /// the exchanges on it. An exchange that outlives its session can never be answered on,
1341 /// and holds a slot in a fixed-capacity table until it times out.
1342 #[test]
1343 fn closing_a_session_closes_its_exchanges() {
1344 let mut node = Node::new(1, 100, 7);
1345 let mut scratch = [0u8; 512];
1346 let mut out = [0u8; 512];
1347 node.install_session(session_on(1, 1, at(0)), at(0), 0, &mut scratch, &mut out)
1348 .expect("install");
1349 node.open(SessionId(1), ProtocolId::INTERACTION_MODEL, at(0))
1350 .expect("open");
1351 node.open(SessionId(1), ProtocolId::INTERACTION_MODEL, at(0))
1352 .expect("open");
1353 assert_eq!(node.exchanges().len(), 2);
1354
1355 assert!(node.close_session(SessionId(1)));
1356 assert_eq!(node.exchanges().len(), 0, "the exchanges went with it");
1357 assert!(node.sessions().find(SessionId(1)).is_none());
1358 }
1359
1360 /// §11.18.6.12: `RemoveFabric` takes the fabric's sessions — and their exchanges — while
1361 /// leaving every other fabric's alone.
1362 #[test]
1363 fn removing_a_fabric_takes_its_sessions_and_their_exchanges() {
1364 let mut node = Node::new(1, 100, 7);
1365 let mut scratch = [0u8; 512];
1366 let mut out = [0u8; 512];
1367 node.install_session(session_on(1, 1, at(0)), at(0), 0, &mut scratch, &mut out)
1368 .expect("install");
1369 node.install_session(session_on(2, 2, at(1)), at(1), 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(2), ProtocolId::INTERACTION_MODEL, at(0))
1374 .expect("open");
1375
1376 assert_eq!(node.remove_fabric(crate::msg::FabricIndex(1)), 1);
1377 assert!(node.sessions().find(SessionId(1)).is_none());
1378 assert!(node.sessions().find(SessionId(2)).is_some());
1379 assert_eq!(
1380 node.exchanges().len(),
1381 1,
1382 "only the removed fabric's exchange went"
1383 );
1384 }
1385
1386 /// The unsecured session is what PASE runs over before any key exists.
1387 #[test]
1388 fn an_unsecured_message_round_trips_through_a_new_exchange() {
1389 let mut initiator = Node::new(1, 100, 7);
1390 let mut responder = Node::new(2, 200, 9);
1391
1392 let key = initiator
1393 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1394 .expect("open");
1395 let mut wire = [0u8; 512];
1396 let mut scratch = [0u8; 512];
1397 let (len, counter) = initiator
1398 .send(
1399 key,
1400 0x20,
1401 true,
1402 b"pbkdf-param-request",
1403 at(0),
1404 0,
1405 &mut scratch,
1406 &mut wire,
1407 )
1408 .expect("send");
1409
1410 let received = responder
1411 .receive(&mut wire[..len], PEER, at(1))
1412 .expect("receive");
1413 let Received::Message {
1414 exchange,
1415 header,
1416 needs_ack,
1417 payload,
1418 } = received
1419 else {
1420 panic!("expected a message, got {received:?}");
1421 };
1422 assert_eq!(payload, b"pbkdf-param-request");
1423 assert_eq!(header.opcode, 0x20);
1424 assert!(needs_ack, "a reliable message owes an acknowledgement");
1425 // The responder opened its own half of the exchange, with the peer's id.
1426 assert_eq!(exchange.role, Role::Responder);
1427 assert_eq!(exchange.id, key.id);
1428
1429 // ...and the acknowledgement it sends clears the initiator's retransmission.
1430 let mut ack = [0u8; 512];
1431 let ack_len = responder
1432 .acknowledge(exchange, at(1), &mut ack)
1433 .expect("ack");
1434 assert!(ack_len > 0);
1435 assert!(initiator.wake_at().is_some(), "waiting for the ack");
1436 let back = initiator
1437 .receive(&mut ack[..ack_len], PEER, at(2))
1438 .expect("receive ack");
1439 assert!(matches!(back, Received::Acknowledged { .. }));
1440 assert!(
1441 !initiator
1442 .exchanges()
1443 .find(key)
1444 .expect("still open")
1445 .mrp
1446 .is_awaiting_ack(),
1447 "acknowledged, so no retransmission is outstanding"
1448 );
1449 let _ = counter;
1450 }
1451
1452 /// Builds one unsecured datagram from a stranger, with the exchange id and protocol of
1453 /// its choosing — which is everything an off-path attacker controls before any key exists.
1454 fn stranger_datagram(
1455 exchange_id: u16,
1456 protocol: ProtocolId,
1457 reliable: bool,
1458 counter: u32,
1459 out: &mut [u8],
1460 ) -> usize {
1461 let mut sender = Node::new(1, exchange_id, counter);
1462 sender.register(Protocols::SECURE_CHANNEL.with(Protocols::INTERACTION_MODEL));
1463 let key = sender
1464 .open_unsecured(protocol, at(0), 0xE0E0_1234_5678_9ABC)
1465 .expect("open");
1466 let mut scratch = [0u8; 512];
1467 let (len, _) = sender
1468 .send(key, 0x20, reliable, b"x", at(0), 0, &mut scratch, out)
1469 .expect("send");
1470 len
1471 }
1472
1473 /// The exhaustion attack, and the shape CVE-2024-3297 had: every unsecured message with
1474 /// the **I** flag opens an exchange (§4.10.5.2), so a stranger who varies the exchange id
1475 /// fills the table. Without reclamation the node can never open another exchange — which
1476 /// means it can never establish another session, PASE or CASE, for the rest of its uptime.
1477 #[test]
1478 fn a_stranger_cannot_fill_the_exchange_table_for_good() {
1479 let mut node = Node::new(2, 200, 9);
1480 let mut wire = [0u8; 512];
1481
1482 // The whole table, from the table rather than from a literal.
1483 const CAP: u16 = ExchangeTable::<DefaultConfig, 64>::TOTAL as u16;
1484 for id in 0..CAP {
1485 let len = stranger_datagram(
1486 id,
1487 ProtocolId::SECURE_CHANNEL,
1488 true,
1489 u32::from(id) + 1,
1490 &mut wire,
1491 );
1492 let _ = node.receive(&mut wire[..len], PEER, at(0));
1493 }
1494 assert_eq!(
1495 node.exchanges().len(),
1496 usize::from(CAP),
1497 "the table is full"
1498 );
1499
1500 // A legitimate peer arrives while the attacker's entries are still fresh, and is
1501 // refused — which is correct, and is why the entries must not be permanent.
1502 let len = stranger_datagram(CAP + 1, ProtocolId::SECURE_CHANNEL, true, 900, &mut wire);
1503 assert!(node.receive(&mut wire[..len], PEER, at(1)).is_err());
1504
1505 // A minute later nothing has happened on any of them, so they go.
1506 assert!(
1507 node.wake_at().is_some(),
1508 "the node knows it has something to reclaim"
1509 );
1510 node.poll(at(61_000), 0);
1511 assert_eq!(node.exchanges().len(), 0, "every abandoned entry reclaimed");
1512
1513 // ...and the node answers again.
1514 let len = stranger_datagram(901, ProtocolId::SECURE_CHANNEL, true, 901, &mut wire);
1515 assert!(
1516 node.receive(&mut wire[..len], PEER, at(62_000)).is_ok(),
1517 "a node that cannot open an exchange can never establish a session again"
1518 );
1519 }
1520
1521 /// Reclaiming on the timer is not enough on its own: a node whose timers are slow, or
1522 /// which is simply busy, must still not be refusing legitimate peers on behalf of entries
1523 /// that expired long ago.
1524 #[test]
1525 fn a_full_table_reclaims_before_refusing() {
1526 const FULL: usize = ExchangeTable::<DefaultConfig, 64>::TOTAL;
1527 let mut node = Node::new(2, 200, 9);
1528 let mut wire = [0u8; 512];
1529 for id in 0..FULL as u16 {
1530 let len = stranger_datagram(
1531 id,
1532 ProtocolId::SECURE_CHANNEL,
1533 true,
1534 u32::from(id) + 1,
1535 &mut wire,
1536 );
1537 let _ = node.receive(&mut wire[..len], PEER, at(0));
1538 }
1539 assert_eq!(node.exchanges().len(), FULL);
1540
1541 // No `poll` in between — the pressure itself is the trigger.
1542 let len = stranger_datagram(
1543 FULL as u16 + 1,
1544 ProtocolId::SECURE_CHANNEL,
1545 true,
1546 900,
1547 &mut wire,
1548 );
1549 assert!(
1550 node.receive(&mut wire[..len], PEER, at(61_000)).is_ok(),
1551 "the entry that would have refused this one had been idle for a minute"
1552 );
1553 }
1554
1555 /// §4.10.5.2 rule 1: "has a registered Protocol ID". An unregistered protocol is not
1556 /// something this node will ever act on, so it must not cost a table entry.
1557 #[test]
1558 fn an_unregistered_protocol_opens_no_exchange() {
1559 let mut node = Node::new(2, 200, 9);
1560 node.register(Protocols::SECURE_CHANNEL);
1561 let mut wire = [0u8; 512];
1562
1563 // The Interaction Model is not registered on this node.
1564 let len = stranger_datagram(5, ProtocolId::INTERACTION_MODEL, false, 5, &mut wire);
1565 assert!(node.receive(&mut wire[..len], PEER, at(0)).is_err());
1566 assert_eq!(node.exchanges().len(), 0, "rule 3: processing SHALL stop");
1567
1568 // Secure Channel is, so that one is answered.
1569 let len = stranger_datagram(6, ProtocolId::SECURE_CHANNEL, false, 6, &mut wire);
1570 assert!(node.receive(&mut wire[..len], PEER, at(0)).is_ok());
1571 assert_eq!(node.exchanges().len(), 1);
1572 }
1573
1574 /// §4.10.5.2 rule 2: an unregistered protocol that *asks* for an acknowledgement still
1575 /// gets one — withholding it costs the sender five retransmissions — but on an ephemeral
1576 /// exchange that §4.12.5.2.2 closes as soon as the acknowledgement is sent.
1577 #[test]
1578 fn an_unregistered_reliable_message_is_acknowledged_on_an_ephemeral_exchange() {
1579 let mut node = Node::new(2, 200, 9);
1580 node.register(Protocols::SECURE_CHANNEL);
1581 let mut wire = [0u8; 512];
1582 let len = stranger_datagram(7, ProtocolId::BDX, true, 7, &mut wire);
1583
1584 let received = node.receive(&mut wire[..len], PEER, at(0)).expect("routed");
1585 let Received::Message { exchange, .. } = received else {
1586 panic!("expected the ephemeral exchange, got {received:?}")
1587 };
1588 assert_eq!(node.exchanges().len(), 1);
1589 assert!(
1590 node.exchanges().find(exchange).is_some_and(|e| e.ephemeral),
1591 "it is ephemeral"
1592 );
1593
1594 let mut ack = [0u8; 512];
1595 assert!(node.acknowledge(exchange, at(0), &mut ack).expect("ack") > 0);
1596 assert_eq!(
1597 node.exchanges().len(),
1598 0,
1599 "§4.12.5.2.2: the ephemeral exchange SHALL be closed once it has acknowledged"
1600 );
1601 }
1602
1603 /// An exchange that is still trying to deliver something is not abandoned, however quiet
1604 /// the peer has been — §4.10.5.3 step 2b.
1605 #[test]
1606 fn an_exchange_with_a_pending_retransmission_is_never_reaped() {
1607 let mut node = Node::new(1, 100, 7);
1608 let key = node
1609 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1610 .expect("open");
1611 let mut wire = [0u8; 512];
1612 let mut scratch = [0u8; 512];
1613 let _ = node
1614 .send(key, 0x20, true, b"x", at(0), 0, &mut scratch, &mut wire)
1615 .expect("send");
1616
1617 // Far past the idle timeout, and never acknowledged.
1618 node.exchanges_mut()
1619 .reap(at(600_000), EXCHANGE_IDLE_TIMEOUT);
1620 assert_eq!(
1621 node.exchanges().len(),
1622 1,
1623 "a retransmission still pending keeps the exchange open"
1624 );
1625 }
1626
1627 /// §4.13.2.1's Unsecured Session Context, and the rule that no test of this crate against
1628 /// itself could catch.
1629 ///
1630 /// > Ephemeral Initiator Node ID: Randomly selected for each session by the initiator from
1631 /// > the Operational Node ID range and **enclosed by initiator as Source Node ID and
1632 /// > responder as Destination Node ID.**
1633 ///
1634 /// Both halves have to hold, and a stack that encloses *neither* is self-consistent: two
1635 /// nodes built from it commission each other perfectly. The CHIP SDK drops such a message
1636 /// before it reaches any protocol — "Received malformed unsecure packet with source 0x0
1637 /// destination 0x0" — so the symptom is a device no certified controller can pair with,
1638 /// while every test passes.
1639 #[test]
1640 fn an_unsecured_response_carries_the_initiators_ephemeral_node_id() {
1641 const EPHEMERAL: crate::msg::NodeId = crate::msg::NodeId(0x0102_0304_0506_0708);
1642
1643 let mut initiator = Node::new(1, 100, 7);
1644 initiator
1645 .open_unsecured_as_initiator(EPHEMERAL)
1646 .expect("an operational node id");
1647 let mut responder = Node::new(2, 200, 9);
1648
1649 // `open` rather than `open_unsecured`, because the context is the one this test named.
1650 let key = initiator
1651 .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1652 .expect("open");
1653 let mut wire = [0u8; 512];
1654 let mut scratch = [0u8; 512];
1655 let (len, _) = initiator
1656 .send(
1657 key,
1658 0x20,
1659 true,
1660 b"request",
1661 at(0),
1662 0,
1663 &mut scratch,
1664 &mut wire,
1665 )
1666 .expect("send");
1667
1668 // The initiator encloses it as the Source Node ID: flag bit 2 of octet 0, then eight
1669 // octets little-endian after the four-octet counter.
1670 assert_eq!(wire[0] & 0x04, 0x04, "S flag set");
1671 assert_eq!(
1672 u64::from_le_bytes(wire[8..16].try_into().expect("eight octets")),
1673 EPHEMERAL.0,
1674 "and it is the ephemeral id"
1675 );
1676
1677 let received = responder
1678 .receive(&mut wire[..len], PEER, at(1))
1679 .expect("receive");
1680 let Received::Message { exchange, .. } = received else {
1681 panic!("expected a message, got {received:?}")
1682 };
1683 assert_eq!(
1684 responder.unsecured_ephemeral_id(),
1685 Some(EPHEMERAL),
1686 "the responder recorded it as the context's ephemeral initiator id"
1687 );
1688
1689 // ...and encloses it as the *Destination* Node ID on the way back.
1690 let mut back = [0u8; 512];
1691 let (len, _) = responder
1692 .send(
1693 exchange,
1694 0x21,
1695 true,
1696 b"response",
1697 at(1),
1698 0,
1699 &mut scratch,
1700 &mut back,
1701 )
1702 .expect("send");
1703 assert_eq!(back[0] & 0x04, 0, "no S flag on the responder's message");
1704 assert_eq!(back[0] & 0x03, 0x01, "DSIZ = 1, a 64-bit Node ID");
1705 assert_eq!(
1706 u64::from_le_bytes(back[8..16].try_into().expect("eight octets")),
1707 EPHEMERAL.0,
1708 "the destination is the initiator's ephemeral id"
1709 );
1710
1711 // The initiator accepts what comes back.
1712 let round = initiator
1713 .receive(&mut back[..len], PEER, at(2))
1714 .expect("the initiator accepts its own ephemeral id as the destination");
1715 assert!(matches!(round, Received::Message { .. }));
1716 }
1717
1718 /// §4.13.2.1 matches a context by Ephemeral Initiator Node ID and creates a new one when
1719 /// none matches. A node that kept the first would answer a second initiator — the same
1720 /// commissioner coming back for CASE after PASE, most of the time — with replies addressed
1721 /// to a peer that has gone, which the CHIP SDK drops before any protocol sees them.
1722 #[test]
1723 fn a_second_initiator_replaces_the_unsecured_context() {
1724 const FIRST: crate::msg::NodeId = crate::msg::NodeId(0x1111_1111_1111_1111);
1725 const SECOND: crate::msg::NodeId = crate::msg::NodeId(0x2222_2222_2222_2222);
1726
1727 let mut responder = Node::new(2, 200, 9);
1728 let mut wire = [0u8; 512];
1729 let mut scratch = [0u8; 512];
1730
1731 for (n, (ephemeral, counter)) in [(FIRST, 1u32), (SECOND, 2u32)].into_iter().enumerate() {
1732 let mut initiator = Node::new(1, 100 + u16::try_from(n).expect("fits"), counter);
1733 initiator
1734 .open_unsecured_as_initiator(ephemeral)
1735 .expect("operational");
1736 let key = initiator
1737 .open(SessionId::UNSECURED, ProtocolId::SECURE_CHANNEL, at(0))
1738 .expect("open");
1739 let (len, _) = initiator
1740 .send(key, 0x20, true, b"x", at(0), 0, &mut scratch, &mut wire)
1741 .expect("send");
1742 let received = responder
1743 .receive(&mut wire[..len], PEER, at(1))
1744 .expect("receive");
1745 let Received::Message { exchange, .. } = received else {
1746 panic!("expected a message")
1747 };
1748 assert_eq!(
1749 responder.unsecured_ephemeral_id(),
1750 Some(ephemeral),
1751 "the newest initiator owns the context"
1752 );
1753
1754 let mut back = [0u8; 512];
1755 let _ = responder
1756 .send(
1757 exchange,
1758 0x21,
1759 true,
1760 b"y",
1761 at(1),
1762 0,
1763 &mut scratch,
1764 &mut back,
1765 )
1766 .expect("send");
1767 assert_eq!(
1768 u64::from_le_bytes(back[8..16].try_into().expect("eight octets")),
1769 ephemeral.0,
1770 "and the reply is addressed to it"
1771 );
1772 }
1773 }
1774
1775 /// §4.13.2.1 constrains the ephemeral id to the Operational Node ID range, because it is
1776 /// what the responder will put in a Destination Node ID field.
1777 #[test]
1778 fn an_ephemeral_id_outside_the_operational_range_is_refused() {
1779 let mut node = Node::new(1, 100, 7);
1780 assert!(
1781 node.open_unsecured_as_initiator(crate::msg::NodeId::UNSPECIFIED)
1782 .is_err()
1783 );
1784 assert!(
1785 node.open_unsecured_as_initiator(crate::msg::NodeId(1))
1786 .is_ok()
1787 );
1788 }
1789
1790 /// §4.12.2.2: a duplicate is acknowledged and not delivered.
1791 #[test]
1792 fn a_duplicate_is_acknowledged_and_not_delivered_twice() {
1793 let mut initiator = Node::new(1, 100, 7);
1794 let mut responder = Node::new(2, 200, 9);
1795 let key = initiator
1796 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1797 .expect("open");
1798
1799 let mut wire = [0u8; 512];
1800 let mut scratch = [0u8; 512];
1801 let (len, _) = initiator
1802 .send(key, 0x20, true, b"once", at(0), 0, &mut scratch, &mut wire)
1803 .expect("send");
1804 let copy = wire;
1805
1806 let first = responder
1807 .receive(&mut wire[..len], PEER, at(1))
1808 .expect("first");
1809 assert!(matches!(first, Received::Message { .. }));
1810
1811 let mut again = copy;
1812 let second = responder
1813 .receive(&mut again[..len], PEER, at(2))
1814 .expect("second");
1815 match second {
1816 Received::Duplicate { needs_ack, .. } => {
1817 assert!(needs_ack, "still acknowledged — the sender's ack was lost");
1818 }
1819 other => panic!("a repeat must not reach the application: {other:?}"),
1820 }
1821 }
1822
1823 /// A message for a session this node does not have is refused, not guessed at.
1824 #[test]
1825 fn a_message_for_an_unknown_session_is_refused() {
1826 let mut node = Node::new(1, 100, 7);
1827 let mut wire = [0u8; 64];
1828 // Flags: version 0, no source/destination. Session id 0x1234, unicast.
1829 wire[0] = 0x00;
1830 wire[1] = 0x34;
1831 wire[2] = 0x12;
1832 wire[3] = 0x00;
1833 let err = node
1834 .receive(&mut wire, PEER, at(0))
1835 .expect_err("no session");
1836 assert_eq!(err.code(), ErrorCode::NoSession);
1837 }
1838
1839 /// A response to an exchange that was never opened is refused (§4.4.3.1).
1840 #[test]
1841 fn a_message_from_a_responder_cannot_open_an_exchange() {
1842 let mut initiator = Node::new(1, 100, 7);
1843 let mut responder = Node::new(2, 200, 9);
1844 let key = initiator
1845 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1846 .expect("open");
1847 let mut wire = [0u8; 512];
1848 let mut scratch = [0u8; 512];
1849 let (len, _) = initiator
1850 .send(
1851 key,
1852 0x20,
1853 false,
1854 b"hello",
1855 at(0),
1856 0,
1857 &mut scratch,
1858 &mut wire,
1859 )
1860 .expect("send");
1861 // Clear the I flag in the protocol header: now it claims to be a *response*.
1862 //
1863 // The offset is the *message* header's real length, which is not a constant: an
1864 // unsecured initiator encloses its Ephemeral Initiator Node ID (§4.13.2.1), so the
1865 // header is eight octets longer than a bare one. Decoding it is the only way to know.
1866 let (sent_header, _) = MessageHeader::decode(&wire[..len]).expect("decode");
1867 let header_len = sent_header.encoded_len();
1868 wire[header_len] &= !0x01;
1869
1870 let err = responder
1871 .receive(&mut wire[..len], PEER, at(1))
1872 .expect_err("a response answers a question nobody asked");
1873 assert_eq!(err.code(), ErrorCode::NoExchange);
1874 }
1875
1876 /// The retransmission timer fires, and names the counter to resend (§4.12.2.1).
1877 #[test]
1878 fn an_unacknowledged_message_is_retransmitted_with_its_own_counter() {
1879 let mut initiator = Node::new(1, 100, 7);
1880 let key = initiator
1881 .open_unsecured(ProtocolId::SECURE_CHANNEL, at(0), 0xE0E0_1234_5678_9ABC)
1882 .expect("open");
1883 let mut wire = [0u8; 512];
1884 let mut scratch = [0u8; 512];
1885 let (_, counter) = initiator
1886 .send(key, 0x20, true, b"lost", at(0), 0, &mut scratch, &mut wire)
1887 .expect("send");
1888
1889 let deadline = initiator.wake_at().expect("a reliable send arms a timer");
1890 match initiator.poll(deadline, 0) {
1891 Some(Due::Retransmit {
1892 exchange,
1893 counter: again,
1894 }) => {
1895 assert_eq!(exchange, key);
1896 assert_eq!(
1897 again, counter,
1898 "the same counter: a new one would be a new message and a reused nonce"
1899 );
1900 }
1901 other => panic!("expected a retransmission, got {other:?}"),
1902 }
1903 }
1904}