Skip to main content

zigbee_core/aps/apsme/
mod.rs

1//! Application Support Sub-Layer Management Entity
2//!
3//! The APSME shall provide a management service to allow an application to
4//! interact with the stack.
5//!
6//! It provides the following services:
7//! * Binding management
8//! * AIB management
9//! * Security
10//! * Group management
11#![allow(dead_code)]
12
13use core::ops::Not;
14use core::sync::atomic::AtomicBool;
15use core::sync::atomic::AtomicU8;
16use core::sync::atomic::Ordering;
17
18use basemgt::ApsmeAddGroupConfirm;
19use basemgt::ApsmeAddGroupRequest;
20use basemgt::ApsmeBindConfirm;
21use basemgt::ApsmeBindRequest;
22use basemgt::ApsmeBindRequestStatus;
23use basemgt::ApsmeGetConfirm;
24use basemgt::ApsmeGetConfirmStatus;
25use basemgt::ApsmeRemoveAllGroupsConfirm;
26use basemgt::ApsmeRemoveAllGroupsRequest;
27use basemgt::ApsmeRemoveGroupConfirm;
28use basemgt::ApsmeRemoveGroupRequest;
29use basemgt::ApsmeSetConfirm;
30use basemgt::ApsmeUnbindConfirm;
31use basemgt::ApsmeUnbindRequest;
32use basemgt::ApsmeUnbindRequestStatus;
33use byte::BytesExt;
34use embedded_hal_async::delay::DelayNs;
35use spin::Mutex;
36use zigbee_types::IeeeAddress;
37use zigbee_types::ShortAddress;
38use zigbee_types::StorageVec;
39use zigbee_types::sync::Event;
40use zigbee_types::sync::Signal;
41use zigbee_types::sync::with_timeout;
42
43use super::aib;
44use super::aib::Aib;
45use super::aib::DeviceKeyPairDescriptor;
46use super::aib::KeyAttribute;
47use super::aib::LinkKeyType;
48use super::apsde::ApsdeSapIndication;
49use super::apsde::ApsdeSapIndicationStatus;
50use super::apsde::SecurityStatus;
51use super::binding::BindingError;
52use super::binding::create_binding_link;
53use super::binding::remove_binding_link;
54use super::frame::CommandFrame;
55use super::frame::Frame;
56use super::frame::command::Command;
57use super::frame::command::StandardNetworkKeyDescriptor;
58use super::frame::command::TransportKey;
59use super::frame::command::TrustCenterLinkKeyDescriptor;
60use super::frame::frame_control::DeliveryMode;
61use super::frame::frame_control::FrameControl;
62use super::frame::frame_control::FrameType;
63use super::frame::header::Header;
64use super::types::Address;
65use super::types::DstAddrMode;
66use super::types::SrcAddrMode;
67use super::types::SrcEndpoint;
68use super::types::TxOptions;
69use crate::aps::APS_DUPLICATE_REJECTION_TABLE_SIZE;
70use crate::aps::APS_MAX_PENDING_ACKS;
71use crate::aps::APSC_ACK_WAIT_DURATION_MS;
72use crate::aps::APSC_MAX_FRAME_RETRIES;
73use crate::nwk::nib::NetworkSecurityMaterialDescriptor;
74use crate::nwk::nib::Nib;
75use crate::nwk::nlme::NetworkError;
76use crate::nwk::nlme::Nlme;
77use crate::security::SecurityContext;
78
79pub mod basemgt;
80pub mod groupmgt;
81
82// standard network key type of a security material descriptor (3.5.2)
83const STANDARD_NETWORK_KEY: u8 = 0x01;
84
85/// Application support sub-layer management service - service access point
86///
87/// 2.2.4.2
88///
89/// Supports the transport of management commands between the NHLE and the
90/// APSME.
91pub trait ApsmeSap {
92    /// 2.2.4.3.1 - request to bind two devices together, or to bind a device to
93    /// a group
94    fn bind_request(&self, request: ApsmeBindRequest) -> ApsmeBindConfirm;
95    /// 2.2.4.3.3 - request to unbind two devices, or to unbind a device from a
96    /// group
97    fn unbind_request(&self, request: ApsmeUnbindRequest) -> ApsmeUnbindConfirm;
98    /// 2.2.4.5.1 - APSME-ADD-GROUP.request
99    fn add_group(&self, request: ApsmeAddGroupRequest) -> ApsmeAddGroupConfirm;
100    /// 2.2.4.5.3 - APSME-REMOVE-GROUP.request
101    fn remove_group(&self, request: ApsmeRemoveGroupRequest) -> ApsmeRemoveGroupConfirm;
102    /// 2.2.4.5.5 - APSME-REMOVE-ALL-GROUPS.request
103    fn remove_all_groups(
104        &self,
105        request: ApsmeRemoveAllGroupsRequest,
106    ) -> ApsmeRemoveAllGroupsConfirm;
107}
108
109// identifies the acknowledgement expected for a transmitted frame
110// (2.2.8.4.4): same cluster and APS counter, source endpoint equal to the
111// destination endpoint the frame was sent to
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113struct AckKey {
114    destination: u16,
115    dst_endpoint: u8,
116    cluster_id: u16,
117    counter: u8,
118}
119
120// one outstanding acknowledged transmission; each slot carries its own
121// event because several senders can wait at once and an Event holds a
122// single waker
123#[derive(Default)]
124struct PendingAck {
125    key: Mutex<Option<AckKey>>,
126    acked: Event,
127}
128
129// duplicate rejection table (2.2.8.4.2), keyed on source address and APS
130// counter; without a clock the spec's "timing information" degrades to
131// insertion-order eviction: an entry is remembered until the ring wraps
132#[derive(Default)]
133struct DuplicateTable {
134    entries: [Option<(u16, u8)>; APS_DUPLICATE_REJECTION_TABLE_SIZE],
135    next: usize,
136}
137
138impl DuplicateTable {
139    // records the frame and reports whether it was seen before
140    fn seen(&mut self, source: u16, counter: u8) -> bool {
141        if self.entries.contains(&Some((source, counter))) {
142            return true;
143        }
144        self.entries[self.next] = Some((source, counter));
145        self.next = (self.next + 1) % APS_DUPLICATE_REJECTION_TABLE_SIZE;
146        false
147    }
148}
149
150// APS Management Entity (2.2.4)
151pub(crate) struct Apsme {
152    pub(crate) supports_binding_table: bool,
153    // whether the device is currently on a network; APS services are only
154    // available to a joined device (2.2.8.4.1)
155    joined: AtomicBool,
156    // transmissions waiting for their acknowledgement (2.2.8.4.4)
157    pending_acks: [PendingAck; APS_MAX_PENDING_ACKS],
158    // frames already delivered to the next higher layer (2.2.8.4.2)
159    duplicates: Mutex<DuplicateTable>,
160    // apsCounter AIB attribute (4.4.11)
161    pub(crate) aps_counter: AtomicU8,
162    // gates handling of Transport-Key/Confirm-Key so replayed or
163    // unsolicited frames cannot downgrade an established key (4.4.10)
164    tc_exchange_active: AtomicBool,
165    // carries whether a transported TC link key was accepted and installed
166    // (4.4.10, BDB 10.2.5 step 9)
167    pub(crate) tc_key_received: Signal<bool>,
168    // carries the Confirm-Key status (4.4.9), 0x00 = success
169    pub(crate) tc_key_verified: Signal<u8>,
170}
171
172impl Apsme {
173    pub(crate) fn new(initial_counter: u8) -> Self {
174        Self {
175            supports_binding_table: true,
176            joined: AtomicBool::new(false),
177            pending_acks: Default::default(),
178            duplicates: Mutex::new(DuplicateTable::default()),
179            aps_counter: AtomicU8::new(initial_counter),
180            tc_exchange_active: AtomicBool::new(false),
181            tc_key_received: Signal::new(),
182            tc_key_verified: Signal::new(),
183        }
184    }
185
186    // arm the TC link key exchange: clear stale events from a previous
187    // attempt and accept Transport-Key/Confirm-Key until disarmed
188    pub(crate) fn begin_tc_key_exchange(&self) {
189        self.tc_key_received.reset();
190        self.tc_key_verified.reset();
191        self.tc_exchange_active.store(true, Ordering::Release);
192    }
193
194    // disarm the TC link key exchange; subsequent key-transport commands
195    // are ignored again
196    pub(crate) fn end_tc_key_exchange(&self) {
197        self.tc_exchange_active.store(false, Ordering::Release);
198    }
199
200    // next APS counter value (4.4.11), wrapping
201    fn next_aps_counter(&self) -> u8 {
202        self.aps_counter
203            .fetch_add(1, Ordering::Relaxed)
204            .wrapping_add(1)
205    }
206
207    /// Track whether the device is on a network, following the ZDO join gate.
208    pub(crate) fn set_joined(&self, joined: bool) {
209        self.joined.store(joined, Ordering::Release);
210    }
211
212    fn is_joined(&self) -> bool {
213        self.joined.load(Ordering::Acquire)
214    }
215
216    // build and send an APS command frame to a specific destination (4.4);
217    // when aps_secure is true the frame is encrypted with the link key for
218    // dest_ieee before handing it to the NWK layer, which always applies
219    // network-key encryption on top
220    pub(crate) async fn send_command<M: zigbee_mac::mlme::Mlme>(
221        &self,
222        nlme: &Nlme<M>,
223        destination: ShortAddress,
224        dest_ieee: IeeeAddress,
225        command: Command,
226        aps_secure: bool,
227    ) -> Result<(), NetworkError> {
228        let frame_control = FrameControl::default()
229            .set_frame_type(FrameType::Command)
230            .set_security_flag(aps_secure);
231
232        let header = Header {
233            frame_control,
234            destination_endpoint: None,
235            group_address: None,
236            cluster_id: None,
237            profile_id: None,
238            source_endpoint: None,
239            counter: self.next_aps_counter(),
240            extended_header: None,
241        };
242
243        let mut buf = [0u8; 128];
244        let len = if aps_secure {
245            let aps_frame = Frame::ApsCommand(CommandFrame { header, command });
246            let cx = SecurityContext::get();
247            cx.encrypt_aps_frame_in_place(aps_frame, &mut buf, dest_ieee, TxOptions::default())?
248        } else {
249            let offset = &mut 0;
250            buf.write_with(offset, header, ())?;
251            buf.write_with(offset, command, ())?;
252            *offset
253        };
254
255        nlme.send_data(destination, true, &buf[..len]).await
256    }
257
258    // poll the parent once (MLME-POLL, 3.6.6) and process the retrieved APS
259    // frame; a data frame yields an APSDE-DATA.indication (2.2.4.1.3), a
260    // command frame is handled internally (4.4) and yields Ok(None)
261    pub(crate) async fn poll_aps_frame<'a, M: zigbee_mac::mlme::Mlme>(
262        &self,
263        nlme: &Nlme<M>,
264        buf: &'a mut [u8],
265    ) -> Result<Option<ApsdeSapIndication<'a>>, NetworkError> {
266        let Some(nwk_data) = nlme.poll_nwk_frame(buf).await? else {
267            return Ok(None);
268        };
269        self.process_nwk_data(nlme, nwk_data).await
270    }
271
272    // passively wait for the next inbound APS frame (rx-on-when-idle
273    // devices) and process it like poll_aps_frame
274    pub(crate) async fn receive_aps_frame<'a, M: zigbee_mac::mlme::Mlme>(
275        &self,
276        nlme: &Nlme<M>,
277        buf: &'a mut [u8],
278    ) -> Result<Option<ApsdeSapIndication<'a>>, NetworkError> {
279        let Some(nwk_data) = nlme.receive_nwk_frame(buf).await? else {
280            return Ok(None);
281        };
282        self.process_nwk_data(nlme, nwk_data).await
283    }
284
285    // process one inbound NWK data frame into an APSDE-DATA.indication
286    // (2.2.4.1.3); APS command frames are handled internally (4.4)
287    async fn process_nwk_data<'a, M: zigbee_mac::mlme::Mlme>(
288        &self,
289        nlme: &Nlme<M>,
290        mut nwk_data: crate::nwk::frame::DataFrame<'a>,
291    ) -> Result<Option<ApsdeSapIndication<'a>>, NetworkError> {
292        let src_short = nwk_data.header.source.0;
293        // the NWK destination, not our own address: the higher layer answers a
294        // broadcast differently from a unicast (2.4.4.2.7)
295        let dst_short = nwk_data.header.destination.0;
296        let aps_bytes = nwk_data.payload;
297
298        let offset = &mut 0;
299        let header: Header = aps_bytes.read_with(offset, ())?;
300        let hdr_len = *offset;
301        let secured = header.frame_control.security_flag();
302
303        // acknowledgement of one of our own transmissions (2.2.8.4.4)
304        if header.frame_control.frame_type() == FrameType::Acknowledgement {
305            self.resolve_ack(AckKey {
306                destination: src_short,
307                dst_endpoint: header.source_endpoint.unwrap_or(0),
308                cluster_id: header.cluster_id.unwrap_or(0),
309                counter: header.counter,
310            });
311            return Ok(None);
312        }
313
314        // APS command frame (4.4): process internally, no application data.
315        // a broadcast Switch-Key carries no APS security (4.4.6.1.3), so the
316        // frame is only decrypted when the security sub-field says so
317        if header.frame_control.frame_type() == FrameType::Command {
318            let from_trust_center = self.is_trust_center(nlme, aib::get_ref(), src_short);
319            let command = if secured {
320                // SAFETY: re-borrows the same buffer; decryption is in place
321                let aps_buf = unsafe { nwk_data.payload_as_mut() };
322                let cx = SecurityContext::get();
323                match cx.decrypt_aps_frame_in_place(aps_buf)? {
324                    Frame::ApsCommand(CommandFrame { command, .. }) => command,
325                    _ => return Ok(None),
326                }
327            } else {
328                let command: Command = aps_bytes[hdr_len..].read_with(&mut 0, ())?;
329                // 4.4.1.1 protects every APS command except the broadcast
330                // Switch-Key (4.4.6.1.3), so only that one is honored in the
331                // clear: any other carries no proof of origin, its addresses
332                // being plaintext the sender chose
333                if !matches!(command, Command::SwitchKey(_)) {
334                    log::warn!("[APS] rx unsecured APS command (ignored)");
335                    return Ok(None);
336                }
337                command
338            };
339            self.handle_aps_command(aib::get_ref(), nlme.nib(), &command, from_trust_center);
340            return Ok(None);
341        }
342
343        if header.frame_control.frame_type() != FrameType::Data {
344            return Ok(None);
345        }
346
347        // an APS-encrypted data frame is decrypted with the link key of its
348        // sender before it is dispatched (4.4.1.2)
349        let (asdu, security_status) = if secured {
350            // SAFETY: re-borrows the same buffer; decryption is in place
351            let aps_buf = unsafe { nwk_data.payload_as_mut() };
352            let cx = SecurityContext::get();
353            match cx.decrypt_aps_frame_in_place(aps_buf)? {
354                Frame::Data(data) => (data.payload, SecurityStatus::SecuredLinkKey),
355                _ => return Ok(None),
356            }
357        } else {
358            (&aps_bytes[hdr_len..], SecurityStatus::SecuredNwkKey)
359        };
360
361        // acknowledge before rejecting a duplicate: a retransmission means our
362        // previous acknowledgement was lost (2.2.8.4.2/2.2.8.4.4)
363        if header.frame_control.ack_request()
364            && let Err(e) = self.send_ack(nlme, ShortAddress(src_short), &header).await
365        {
366            log::debug!("[APS] tx ack failed: {e:?}");
367        }
368
369        if self.duplicates.lock().seen(src_short, header.counter) {
370            log::debug!(
371                "[APS] duplicate frame from {src_short:#06x} counter {}",
372                header.counter
373            );
374            return Ok(None);
375        }
376
377        let src_endpoint =
378            SrcEndpoint::new(header.source_endpoint.unwrap_or(0)).unwrap_or_default();
379
380        Ok(Some(ApsdeSapIndication {
381            dst_addr_mode: DstAddrMode::Network,
382            dst_address: Address::Network(dst_short),
383            dst_endpoint: header.destination_endpoint.unwrap_or(0),
384            src_addr_mode: SrcAddrMode::Short,
385            src_address: Address::Network(src_short),
386            src_endpoint,
387            profile_id: header.profile_id.unwrap_or(0),
388            cluster_id: header.cluster_id.unwrap_or(0),
389            asdu,
390            status: ApsdeSapIndicationStatus::Success,
391            security_status,
392            link_quality: 0,
393            rx_time: 0,
394        }))
395    }
396
397    // whether a frame received from `src` came from the Trust Center; the
398    // Switch-Key command carries no source address (4.4.10.5), so it is
399    // identified by the NWK source of the frame it arrived in
400    fn is_trust_center<M: zigbee_mac::mlme::Mlme>(
401        &self,
402        nlme: &Nlme<M>,
403        aib: &Aib,
404        src: u16,
405    ) -> bool {
406        let tc_ieee = *aib.trust_center_address();
407        nlme.short_address_for_ieee(tc_ieee)
408            .map_or(src == ShortAddress::COORDINATOR.0, |short| short.0 == src)
409    }
410
411    // process an inbound APS command frame at its arrival point (4.4);
412    // a TC link key is installed as unverified (4.4.10) and a Confirm-Key
413    // marks it verified (4.4.9), each signaling BDB 10.2.5 commissioning.
414    // a network key transported by the Trust Center becomes the alternate
415    // key and its Switch-Key activates it (4.6.3.4.2)
416    fn handle_aps_command(&self, aib: &Aib, nib: &Nib, command: &Command, from_trust_center: bool) {
417        let exchange_active = self.tc_exchange_active.load(Ordering::Acquire);
418        match command {
419            // outside an armed exchange a TC link key must not be honored: a
420            // replayed frame would downgrade a verified key and reset its
421            // frame counters
422            Command::TransportKey(TransportKey::TrustCenterLinkKey(_)) if !exchange_active => {
423                log::warn!("[APS] rx unsolicited TC link key (ignored)");
424            }
425            Command::ConfirmKey(_) if !exchange_active => {
426                log::warn!("[APS] rx unsolicited confirm key (ignored)");
427            }
428            Command::TransportKey(TransportKey::TrustCenterLinkKey(descriptor)) => {
429                log::debug!("[APS] rx TC link key");
430                let installed = self.install_unverified_tc_link_key(aib, descriptor);
431                self.tc_key_received.signal(installed);
432            }
433            Command::ConfirmKey(confirm) => {
434                log::debug!("[APS] rx confirm key: status {:#04x}", confirm.status);
435                if confirm.status == 0x00 {
436                    self.mark_tc_link_key_verified(aib);
437                }
438                self.tc_key_verified.signal(confirm.status);
439            }
440            // key transport (4.4.3): only the Trust Center may rotate the
441            // network key (4.6.3.4.2)
442            Command::TransportKey(TransportKey::StandardNetworkKey(descriptor)) => {
443                if descriptor.source_address != *aib.trust_center_address() {
444                    log::warn!("[APS] rx network key from a foreign device (ignored)");
445                    return;
446                }
447                log::info!(
448                    "[APS] rx network key seq {} as alternate key",
449                    descriptor.sequence_number
450                );
451                install_alternate_network_key(nib, descriptor);
452            }
453            Command::SwitchKey(switch) if !from_trust_center => {
454                log::warn!(
455                    "[APS] rx switch key seq {} from a foreign device (ignored)",
456                    switch.sequence_number
457                );
458            }
459            Command::SwitchKey(switch) => switch_network_key(nib, switch.sequence_number),
460            Command::TransportKey(_) => log::trace!("[APS] rx transport key (ignored)"),
461            // TODO: a Request-Key addressed to us (e.g. app link key) would be
462            // answered here
463            Command::RequestKey(_) => log::trace!("[APS] rx request key (ignored)"),
464            Command::VerifyKey(_) => log::trace!("[APS] rx verify key (ignored)"),
465            Command::Reserved(id) => log::trace!("[APS] rx reserved command {id:#04x} (ignored)"),
466        }
467    }
468
469    // install a freshly transported TC link key as unverified (BDB 10.2.5
470    // step 9), reporting whether it was accepted: a key identical to the one
471    // already held means the exchange failed
472    fn install_unverified_tc_link_key(
473        &self,
474        aib: &Aib,
475        descriptor: &TrustCenterLinkKeyDescriptor,
476    ) -> bool {
477        let tc_ieee = *aib.trust_center_address();
478        if aib
479            .device_key_pair_set()
480            .iter()
481            .any(|k| k.device_address == tc_ieee && k.link_key == descriptor.key)
482        {
483            log::warn!("[APS] transported TC link key is the one already held");
484            return false;
485        }
486
487        aib.update_device_key_pair_set(|key_set| {
488            if let Some(entry) = key_set.iter_mut().find(|k| k.device_address == tc_ieee) {
489                entry.link_key = descriptor.key;
490                entry.key_attributes = KeyAttribute::UnverifiedKey;
491                entry.outgoing_frame_counter = 0;
492                entry.incoming_frame_counter = 0;
493                entry.link_key_type = LinkKeyType::UniqueLinkKey;
494            } else {
495                let _ = key_set.push(DeviceKeyPairDescriptor {
496                    device_address: tc_ieee,
497                    key_attributes: KeyAttribute::UnverifiedKey,
498                    link_key: descriptor.key,
499                    outgoing_frame_counter: 0,
500                    incoming_frame_counter: 0,
501                    link_key_type: LinkKeyType::UniqueLinkKey,
502                });
503            }
504        });
505        true
506    }
507
508    // mark the TC link key as verified after a successful Confirm-Key (4.4.9)
509    fn mark_tc_link_key_verified(&self, aib: &Aib) {
510        let tc_ieee = *aib.trust_center_address();
511        aib.update_device_key_pair_set(|key_set| {
512            if let Some(entry) = key_set.iter_mut().find(|k| k.device_address == tc_ieee) {
513                entry.key_attributes = KeyAttribute::VerifiedKey;
514            }
515        });
516    }
517
518    // encode an APS data frame into `buf`, returning its length and the APS
519    // counter it was stamped with (2.2.5.1)
520    fn build_data_frame(
521        &self,
522        delivery_mode: DeliveryMode,
523        ack_request: bool,
524        dst_endpoint: u8,
525        cluster_id: u16,
526        profile_id: u16,
527        src_endpoint: u8,
528        payload: &[u8],
529        buf: &mut [u8],
530    ) -> Result<(usize, u8), NetworkError> {
531        let frame_control = FrameControl::default()
532            .set_frame_type(FrameType::Data)
533            .set_delivery_mode(delivery_mode)
534            .set_ack_request(ack_request);
535
536        let counter = self.next_aps_counter();
537        let header = Header {
538            frame_control,
539            destination_endpoint: Some(dst_endpoint),
540            group_address: None,
541            cluster_id: Some(cluster_id),
542            profile_id: Some(profile_id),
543            source_endpoint: Some(src_endpoint),
544            counter,
545            extended_header: None,
546        };
547
548        let offset = &mut 0;
549        buf.write_with(offset, header, ())?;
550
551        let hdr_len = *offset;
552        if payload.len() > buf.len() - hdr_len {
553            return Err(NetworkError::FrameTooLong);
554        }
555        buf[hdr_len..hdr_len + payload.len()].copy_from_slice(payload);
556
557        Ok((hdr_len + payload.len(), counter))
558    }
559
560    // send a unicast APS data frame to a specific destination (2.2.5.1),
561    // without requesting an acknowledgement
562    pub(crate) async fn unicast_data<M: zigbee_mac::mlme::Mlme>(
563        &self,
564        nlme: &Nlme<M>,
565        destination: ShortAddress,
566        dst_endpoint: u8,
567        cluster_id: u16,
568        profile_id: u16,
569        src_endpoint: u8,
570        payload: &[u8],
571    ) -> Result<(), NetworkError> {
572        let mut buf = [0u8; 100];
573        let (len, _) = self.build_data_frame(
574            DeliveryMode::Unicast,
575            false,
576            dst_endpoint,
577            cluster_id,
578            profile_id,
579            src_endpoint,
580            payload,
581            &mut buf,
582        )?;
583
584        nlme.send_data(destination, true, &buf[..len]).await
585    }
586
587    /// Send a unicast APS data frame and wait for its acknowledgement
588    /// (2.2.8.4.4), retransmitting up to `apscMaxFrameRetries` times.
589    ///
590    /// The frame is encoded once, so every attempt carries the same APS
591    /// counter — which is what both the acknowledgement matching rule and the
592    /// receiver's duplicate rejection rely on.
593    pub(crate) async fn unicast_data_acked<M: zigbee_mac::mlme::Mlme>(
594        &self,
595        nlme: &Nlme<M>,
596        destination: ShortAddress,
597        dst_endpoint: u8,
598        cluster_id: u16,
599        profile_id: u16,
600        src_endpoint: u8,
601        payload: &[u8],
602        delay: &mut impl DelayNs,
603    ) -> Result<(), NetworkError> {
604        let mut buf = [0u8; 100];
605        let (len, counter) = self.build_data_frame(
606            DeliveryMode::Unicast,
607            true,
608            dst_endpoint,
609            cluster_id,
610            profile_id,
611            src_endpoint,
612            payload,
613            &mut buf,
614        )?;
615
616        let key = AckKey {
617            destination: destination.0,
618            dst_endpoint,
619            cluster_id,
620            counter,
621        };
622        let Some(slot) = self.claim_ack_slot(key) else {
623            log::warn!("[APS] no free pending-ack slot");
624            return Err(NetworkError::AckTimeout);
625        };
626
627        let mut result = Err(NetworkError::AckTimeout);
628        for attempt in 0..=APSC_MAX_FRAME_RETRIES {
629            if let Err(e) = nlme.send_data(destination, true, &buf[..len]).await {
630                result = Err(e);
631                break;
632            }
633            if with_timeout(
634                self.pending_acks[slot].acked.wait(),
635                delay.delay_ms(APSC_ACK_WAIT_DURATION_MS),
636            )
637            .await
638            .is_some()
639            {
640                result = Ok(());
641                break;
642            }
643            log::debug!("[APS] ack timeout for counter {counter} (attempt {attempt})");
644        }
645
646        self.release_ack_slot(slot);
647        result
648    }
649
650    /// Reserve a slot for an outstanding acknowledged transmission.
651    fn claim_ack_slot(&self, key: AckKey) -> Option<usize> {
652        self.pending_acks.iter().position(|pending| {
653            let mut slot = pending.key.lock();
654            if slot.is_some() {
655                return false;
656            }
657            pending.acked.reset();
658            *slot = Some(key);
659            true
660        })
661    }
662
663    fn release_ack_slot(&self, slot: usize) {
664        *self.pending_acks[slot].key.lock() = None;
665        self.pending_acks[slot].acked.reset();
666    }
667
668    /// Release the sender waiting for this acknowledgement, if any.
669    fn resolve_ack(&self, key: AckKey) {
670        for pending in &self.pending_acks {
671            if *pending.key.lock() == Some(key) {
672                pending.acked.signal();
673                return;
674            }
675        }
676        log::trace!("[APS] rx unexpected ack for counter {}", key.counter);
677    }
678
679    /// Acknowledge a received frame that requested it (2.2.5.2.3).
680    ///
681    /// The acknowledgement echoes the cluster, profile and APS counter of the
682    /// original frame and swaps its endpoints. It carries NWK security only —
683    /// TODO: mirror the APS security of the frame being acknowledged.
684    async fn send_ack<M: zigbee_mac::mlme::Mlme>(
685        &self,
686        nlme: &Nlme<M>,
687        destination: ShortAddress,
688        header: &Header,
689    ) -> Result<(), NetworkError> {
690        let ack = Header {
691            frame_control: FrameControl::default()
692                .set_frame_type(FrameType::Acknowledgement)
693                .set_delivery_mode(DeliveryMode::Unicast),
694            destination_endpoint: header.source_endpoint,
695            group_address: None,
696            cluster_id: header.cluster_id,
697            profile_id: header.profile_id,
698            source_endpoint: header.destination_endpoint,
699            counter: header.counter,
700            extended_header: None,
701        };
702
703        let mut buf = [0u8; 16];
704        let offset = &mut 0;
705        buf.write_with(offset, ack, ())?;
706        nlme.send_data(destination, true, &buf[..*offset]).await
707    }
708
709    // broadcast an APS data frame (2.2.5.1); nwk_broadcast is the NWK
710    // broadcast address (e.g. 0xFFFD for RxOnWhenIdle devices)
711    pub(crate) async fn broadcast_data<M: zigbee_mac::mlme::Mlme>(
712        &self,
713        nlme: &Nlme<M>,
714        nwk_broadcast: ShortAddress,
715        dst_endpoint: u8,
716        cluster_id: u16,
717        profile_id: u16,
718        src_endpoint: u8,
719        payload: &[u8],
720    ) -> Result<(), NetworkError> {
721        let mut buf = [0u8; 100];
722        // a broadcast is never acknowledged (2.2.8.4.3)
723        let (len, _) = self.build_data_frame(
724            DeliveryMode::Broadcast,
725            false,
726            dst_endpoint,
727            cluster_id,
728            profile_id,
729            src_endpoint,
730            payload,
731            &mut buf,
732        )?;
733
734        nlme.broadcast_data(nwk_broadcast, true, &buf[..len]).await
735    }
736}
737
738// store a network key transported by the Trust Center as the alternate key,
739// leaving the active one in place until a Switch-Key arrives (4.6.3.4.2); all
740// frame counters of the replaced key start over
741fn install_alternate_network_key(nib: &Nib, descriptor: &StandardNetworkKeyDescriptor) {
742    let active = *nib.active_key_seq_number();
743    let material = NetworkSecurityMaterialDescriptor {
744        key_seq_number: descriptor.sequence_number,
745        outgoing_frame_counter: 0,
746        incoming_frame_counter_set: StorageVec::new(),
747        key: descriptor.key,
748        network_key_type: STANDARD_NETWORK_KEY,
749    };
750
751    nib.update_security_material_set(|set| {
752        // a re-transported key replaces its own entry, a new one the alternate
753        let slot = set
754            .iter()
755            .position(|m| m.key_seq_number == descriptor.sequence_number)
756            .or_else(|| set.iter().position(|m| m.key_seq_number != active));
757        match slot {
758            Some(index) => set[index] = material,
759            None => {
760                if set.push(material).is_err() {
761                    log::warn!("[APS] no room for the alternate network key");
762                }
763            }
764        }
765    });
766
767    // a device without material for its active key (e.g. after a rejoin that
768    // followed a leave) could not encrypt at all — the transported key becomes
769    // the active one instead
770    if !nib
771        .security_material_set()
772        .iter()
773        .any(|m| m.key_seq_number == active)
774    {
775        switch_network_key(nib, descriptor.sequence_number);
776    }
777}
778
779// activate the network key with the given sequence number (4.6.3.4.2); an
780// unknown sequence number is kept as is so the device stays reachable
781fn switch_network_key(nib: &Nib, key_seq_number: u8) {
782    if !nib
783        .security_material_set()
784        .iter()
785        .any(|m| m.key_seq_number == key_seq_number)
786    {
787        log::warn!("[APS] rx switch key for unknown network key seq {key_seq_number}");
788        return;
789    }
790    log::info!("[APS] switching to network key seq {key_seq_number}");
791    nib.update_active_key_seq_number(|value| *value = key_seq_number);
792}
793
794impl ApsmeSap for Apsme {
795    // 2.2.4.3.1 - APSME-BIND.request
796    // request to bind two devices together, or to bind a device to a group
797    fn bind_request(&self, request: ApsmeBindRequest) -> ApsmeBindConfirm {
798        let status = if !self.is_joined() || !self.supports_binding_table {
799            ApsmeBindRequestStatus::IllegalRequest
800        } else if let Some(binding) = request.binding() {
801            let mut result = Ok(());
802            aib::get_ref()
803                .update_binding_table(|table| result = create_binding_link(table, binding));
804            match result {
805                Ok(()) => ApsmeBindRequestStatus::Success,
806                Err(BindingError::TableFull) => ApsmeBindRequestStatus::TableFull,
807                Err(_) => ApsmeBindRequestStatus::IllegalRequest,
808            }
809        } else {
810            ApsmeBindRequestStatus::IllegalRequest
811        };
812
813        ApsmeBindConfirm {
814            status,
815            src_address: request.src_address,
816            src_endpoint: request.src_endpoint,
817            cluster_id: request.cluster_id,
818            dst_addr_mode: request.dst_addr_mode,
819            dst_address: request.dst_address,
820            dst_endpoint: request.dst_endpoint,
821        }
822    }
823
824    // 2.2.4.3.3 - request to unbind two devices, or to unbind a device from a
825    // group
826    fn unbind_request(&self, request: ApsmeUnbindRequest) -> ApsmeUnbindConfirm {
827        let status = if self.is_joined().not() {
828            ApsmeUnbindRequestStatus::IllegalRequest
829        } else if let Some(binding) = request.binding() {
830            let mut result = Ok(());
831            aib::get_ref()
832                .update_binding_table(|table| result = remove_binding_link(table, &binding));
833            match result {
834                Ok(()) => ApsmeUnbindRequestStatus::Success,
835                Err(BindingError::InvalidBinding) => ApsmeUnbindRequestStatus::InvalidBinding,
836                Err(_) => ApsmeUnbindRequestStatus::IllegalRequest,
837            }
838        } else {
839            ApsmeUnbindRequestStatus::IllegalRequest
840        };
841
842        ApsmeUnbindConfirm {
843            status,
844            src_address: request.src_address,
845            src_endpoint: request.src_endpoint,
846            cluster_id: request.cluster_id,
847            dst_addr_mode: request.dst_addr_mode,
848            dst_address: request.dst_address,
849            dst_endpoint: request.dst_endpoint,
850        }
851    }
852
853    fn add_group(&self, _request: ApsmeAddGroupRequest) -> ApsmeAddGroupConfirm {
854        ApsmeAddGroupConfirm {}
855    }
856
857    fn remove_group(&self, _request: ApsmeRemoveGroupRequest) -> ApsmeRemoveGroupConfirm {
858        todo!()
859    }
860
861    fn remove_all_groups(
862        &self,
863        _request: ApsmeRemoveAllGroupsRequest,
864    ) -> ApsmeRemoveAllGroupsConfirm {
865        todo!()
866    }
867}
868
869#[cfg(test)]
870mod tests {
871    use basemgt::ApsmeBindRequestStatus;
872    use zigbee_types::ByteArray;
873
874    use super::*;
875    use crate::aps::aib::MAX_APS_BINDING_TABLE;
876    use crate::aps::binding::BindingAddrMode;
877    use crate::aps::frame::command::ConfirmKey;
878    use crate::aps::frame::command::SwitchKey;
879    use crate::aps::types::SrcEndpoint;
880
881    fn bind_request(cluster_id: u16) -> ApsmeBindRequest {
882        ApsmeBindRequest {
883            src_address: Address::Extended(0xaabb_ccdd_eeff_0011),
884            src_endpoint: SrcEndpoint::new(10).unwrap(),
885            cluster_id,
886            dst_addr_mode: BindingAddrMode::Device,
887            dst_address: Address::Extended(0x1122_3344_5566_7788),
888            dst_endpoint: 2,
889        }
890    }
891
892    fn unbind_request(cluster_id: u16) -> ApsmeUnbindRequest {
893        let request = bind_request(cluster_id);
894        ApsmeUnbindRequest {
895            src_address: request.src_address,
896            src_endpoint: request.src_endpoint,
897            cluster_id: request.cluster_id,
898            dst_addr_mode: request.dst_addr_mode,
899            dst_address: request.dst_address,
900            dst_endpoint: request.dst_endpoint,
901        }
902    }
903
904    // 2.2.4.3.1/2.2.4.3.3 — the binding table lives in the AIB singleton, so
905    // the whole lifecycle runs as one test rather than racing sibling tests
906    #[test]
907    fn bind_request_lifecycle() {
908        aib::try_init();
909        aib::get_ref().update_binding_table(|table| table.clear());
910
911        let mut apsme = Apsme::new(0xAB);
912
913        // a device without binding support rejects the request
914        apsme.supports_binding_table = false;
915        apsme.set_joined(true);
916        assert_eq!(
917            apsme.bind_request(bind_request(1)).status,
918            ApsmeBindRequestStatus::IllegalRequest
919        );
920
921        // so does a device that has not joined a network
922        apsme.supports_binding_table = true;
923        apsme.set_joined(false);
924        assert_eq!(
925            apsme.bind_request(bind_request(1)).status,
926            ApsmeBindRequestStatus::IllegalRequest
927        );
928
929        apsme.set_joined(true);
930        assert_eq!(
931            apsme.bind_request(bind_request(1)).status,
932            ApsmeBindRequestStatus::Success
933        );
934        // an identical binding is not stored twice
935        assert_eq!(
936            apsme.bind_request(bind_request(1)).status,
937            ApsmeBindRequestStatus::Success
938        );
939        assert_eq!(aib::get_ref().binding_table().len(), 1);
940
941        for cluster in 2..=MAX_APS_BINDING_TABLE as u16 {
942            assert_eq!(
943                apsme.bind_request(bind_request(cluster)).status,
944                ApsmeBindRequestStatus::Success
945            );
946        }
947        assert_eq!(
948            apsme
949                .bind_request(bind_request(MAX_APS_BINDING_TABLE as u16 + 1))
950                .status,
951            ApsmeBindRequestStatus::TableFull
952        );
953
954        assert_eq!(
955            apsme.unbind_request(unbind_request(1)).status,
956            ApsmeUnbindRequestStatus::Success
957        );
958        assert_eq!(
959            apsme.unbind_request(unbind_request(1)).status,
960            ApsmeUnbindRequestStatus::InvalidBinding
961        );
962    }
963
964    // 2.2.8.4.4: an ack matches on cluster, APS counter and a source endpoint
965    // equal to the destination endpoint the frame was sent to
966    #[test]
967    fn ack_matching_releases_only_the_waiting_sender() {
968        let apsme = Apsme::new(0xAB);
969        let key = AckKey {
970            destination: 0x0000,
971            dst_endpoint: 1,
972            cluster_id: 0x0402,
973            counter: 42,
974        };
975        let slot = apsme.claim_ack_slot(key).unwrap();
976
977        // wrong counter, wrong endpoint and wrong cluster all miss
978        apsme.resolve_ack(AckKey { counter: 41, ..key });
979        apsme.resolve_ack(AckKey {
980            dst_endpoint: 2,
981            ..key
982        });
983        apsme.resolve_ack(AckKey {
984            cluster_id: 0x0006,
985            ..key
986        });
987        assert!(!apsme.pending_acks[slot].acked.is_set());
988
989        apsme.resolve_ack(key);
990        assert!(apsme.pending_acks[slot].acked.is_set());
991
992        // a released slot no longer matches and can be claimed again
993        apsme.release_ack_slot(slot);
994        apsme.resolve_ack(key);
995        assert!(!apsme.pending_acks[slot].acked.is_set());
996        assert!(apsme.claim_ack_slot(key).is_some());
997    }
998
999    #[test]
1000    fn duplicate_table_rejects_repeats_until_evicted() {
1001        let mut table = DuplicateTable::default();
1002
1003        assert!(!table.seen(0x1234, 7));
1004        assert!(table.seen(0x1234, 7));
1005        // same counter from another device is a different frame
1006        assert!(!table.seen(0x4321, 7));
1007
1008        // the ring forgets the oldest entry once it wraps
1009        for counter in 0..APS_DUPLICATE_REJECTION_TABLE_SIZE as u8 {
1010            assert!(!table.seen(0x1234, 100 + counter));
1011        }
1012        assert!(!table.seen(0x1234, 7));
1013    }
1014
1015    const TC_IEEE: IeeeAddress = IeeeAddress(0xaaaa_bbbb_cccc_dddd);
1016    const NEW_KEY: [u8; 16] = [
1017        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
1018        0x10,
1019    ];
1020
1021    fn setup_aib() -> Aib {
1022        let aib = Aib::new();
1023        aib.update_trust_center_address(|value| *value = TC_IEEE);
1024        aib
1025    }
1026
1027    fn tc_link_key() -> Command {
1028        Command::TransportKey(TransportKey::TrustCenterLinkKey(
1029            TrustCenterLinkKeyDescriptor {
1030                key: ByteArray(NEW_KEY),
1031                destination_address: IeeeAddress(1),
1032                source_address: TC_IEEE,
1033            },
1034        ))
1035    }
1036
1037    fn confirm_key(status: u8) -> Command {
1038        Command::ConfirmKey(ConfirmKey {
1039            status,
1040            key_type: 0x04,
1041            destination_address: IeeeAddress(1),
1042        })
1043    }
1044
1045    // the NIB is only touched by the network-key commands, so the link-key
1046    // cases hand in a throwaway one
1047    fn handle(apsme: &Apsme, aib: &Aib, command: &Command) {
1048        apsme.handle_aps_command(aib, &Nib::new(), command, true);
1049    }
1050
1051    #[test]
1052    fn tc_link_key_is_installed_unverified_and_signaled() {
1053        use core::future::Future;
1054        use core::pin::pin;
1055        use core::task::Context;
1056        use core::task::Waker;
1057
1058        let apsme = Apsme::new(0xAB);
1059        let aib = setup_aib();
1060        let mut cx = Context::from_waker(Waker::noop());
1061        apsme.begin_tc_key_exchange();
1062
1063        let mut received = pin!(apsme.tc_key_received.wait());
1064        assert!(received.as_mut().poll(&mut cx).is_pending());
1065
1066        handle(&apsme, &aib, &tc_link_key());
1067
1068        let entry = aib.device_key_pair_set()[0].clone();
1069        assert_eq!(entry.device_address, TC_IEEE);
1070        assert_eq!(entry.link_key, ByteArray(NEW_KEY));
1071        assert_eq!(entry.key_attributes, KeyAttribute::UnverifiedKey);
1072        assert_eq!(
1073            received.as_mut().poll(&mut cx),
1074            core::task::Poll::Ready(true)
1075        );
1076    }
1077
1078    // BDB 10.2.5 step 9: a transported key identical to the one already held
1079    // fails the exchange instead of resetting the frame counters
1080    #[test]
1081    fn transported_tc_link_key_identical_to_the_held_one_is_rejected() {
1082        use core::future::Future;
1083        use core::pin::pin;
1084        use core::task::Context;
1085        use core::task::Poll;
1086        use core::task::Waker;
1087
1088        let apsme = Apsme::new(0xAB);
1089        let aib = setup_aib();
1090        let mut cx = Context::from_waker(Waker::noop());
1091        apsme.begin_tc_key_exchange();
1092
1093        handle(&apsme, &aib, &tc_link_key());
1094        aib.update_device_key_pair_set(|key_set| key_set[0].outgoing_frame_counter = 42);
1095
1096        handle(&apsme, &aib, &tc_link_key());
1097        assert_eq!(
1098            pin!(apsme.tc_key_received.wait()).poll(&mut cx),
1099            Poll::Ready(false)
1100        );
1101        assert_eq!(aib.device_key_pair_set()[0].outgoing_frame_counter, 42);
1102    }
1103
1104    #[test]
1105    fn confirm_key_marks_verified_and_signals_status() {
1106        use core::future::Future;
1107        use core::pin::pin;
1108        use core::task::Context;
1109        use core::task::Poll;
1110        use core::task::Waker;
1111
1112        let apsme = Apsme::new(0xAB);
1113        let aib = setup_aib();
1114        let mut cx = Context::from_waker(Waker::noop());
1115        apsme.begin_tc_key_exchange();
1116        handle(&apsme, &aib, &tc_link_key());
1117
1118        // failed verification signals the status but leaves the key unverified
1119        handle(&apsme, &aib, &confirm_key(0x01));
1120        assert_eq!(
1121            aib.device_key_pair_set()[0].key_attributes,
1122            KeyAttribute::UnverifiedKey
1123        );
1124        assert_eq!(
1125            pin!(apsme.tc_key_verified.wait()).poll(&mut cx),
1126            Poll::Ready(0x01)
1127        );
1128
1129        handle(&apsme, &aib, &confirm_key(0x00));
1130        assert_eq!(
1131            aib.device_key_pair_set()[0].key_attributes,
1132            KeyAttribute::VerifiedKey
1133        );
1134        assert_eq!(
1135            pin!(apsme.tc_key_verified.wait()).poll(&mut cx),
1136            Poll::Ready(0x00)
1137        );
1138    }
1139
1140    #[test]
1141    fn key_transport_ignored_outside_exchange() {
1142        use core::future::Future;
1143        use core::pin::pin;
1144        use core::task::Context;
1145        use core::task::Waker;
1146
1147        let apsme = Apsme::new(0xAB);
1148        let aib = setup_aib();
1149        let mut cx = Context::from_waker(Waker::noop());
1150
1151        // not armed: a (replayed) TC link key must not touch the AIB
1152        handle(&apsme, &aib, &tc_link_key());
1153        assert!(aib.device_key_pair_set().is_empty());
1154        assert!(
1155            pin!(apsme.tc_key_received.wait())
1156                .poll(&mut cx)
1157                .is_pending()
1158        );
1159
1160        handle(&apsme, &aib, &confirm_key(0x00));
1161        assert!(
1162            pin!(apsme.tc_key_verified.wait())
1163                .poll(&mut cx)
1164                .is_pending()
1165        );
1166
1167        // disarmed after a completed exchange: a replay must not downgrade
1168        // the verified key or reset its frame counters
1169        apsme.begin_tc_key_exchange();
1170        handle(&apsme, &aib, &tc_link_key());
1171        handle(&apsme, &aib, &confirm_key(0x00));
1172        apsme.end_tc_key_exchange();
1173        aib.update_device_key_pair_set(|key_set| key_set[0].outgoing_frame_counter = 42);
1174
1175        handle(&apsme, &aib, &tc_link_key());
1176        let entry = aib.device_key_pair_set()[0].clone();
1177        assert_eq!(entry.key_attributes, KeyAttribute::VerifiedKey);
1178        assert_eq!(entry.outgoing_frame_counter, 42);
1179    }
1180
1181    fn network_key(sequence_number: u8, key: [u8; 16], source: IeeeAddress) -> Command {
1182        Command::TransportKey(TransportKey::StandardNetworkKey(
1183            StandardNetworkKeyDescriptor {
1184                key: ByteArray(key),
1185                sequence_number,
1186                destination_address: IeeeAddress(1),
1187                source_address: source,
1188            },
1189        ))
1190    }
1191
1192    // 4.6.3.4.2: a transported network key becomes the alternate key and only
1193    // the Switch-Key from the Trust Center makes it active
1194    // seeds the material set with an active network key of sequence number 3
1195    fn nib_with_active_key() -> Nib {
1196        let nib = Nib::new();
1197        nib.update_security_material_set(|set| {
1198            let _ = set.push(NetworkSecurityMaterialDescriptor {
1199                key_seq_number: 3,
1200                outgoing_frame_counter: 7,
1201                incoming_frame_counter_set: StorageVec::new(),
1202                key: ByteArray([0xaa; 16]),
1203                network_key_type: STANDARD_NETWORK_KEY,
1204            });
1205        });
1206        nib.update_active_key_seq_number(|value| *value = 3);
1207        nib
1208    }
1209
1210    #[test]
1211    fn network_key_update_replaces_the_alternate_key_and_switches_on_command() {
1212        let apsme = Apsme::new(0xAB);
1213        let aib = setup_aib();
1214        let nib = nib_with_active_key();
1215
1216        apsme.handle_aps_command(&aib, &nib, &network_key(4, NEW_KEY, TC_IEEE), true);
1217
1218        // the active key is untouched, the new one is stored alongside it
1219        assert_eq!(*nib.active_key_seq_number(), 3);
1220        let set = nib.security_material_set();
1221        assert_eq!(set.len(), 2);
1222        assert_eq!(set[1].key_seq_number, 4);
1223        assert_eq!(set[1].outgoing_frame_counter, 0);
1224        assert_eq!(set[0].outgoing_frame_counter, 7);
1225        drop(set);
1226
1227        apsme.handle_aps_command(
1228            &aib,
1229            &nib,
1230            &Command::SwitchKey(SwitchKey { sequence_number: 4 }),
1231            true,
1232        );
1233        assert_eq!(*nib.active_key_seq_number(), 4);
1234
1235        // the next rotation overwrites the now-alternate key, not the active
1236        // one
1237        apsme.handle_aps_command(&aib, &nib, &network_key(5, [0xbb; 16], TC_IEEE), true);
1238        let set = nib.security_material_set();
1239        assert_eq!(set.len(), 2);
1240        assert_eq!(set[0].key_seq_number, 5);
1241        assert_eq!(set[1].key_seq_number, 4);
1242    }
1243
1244    #[test]
1245    fn network_key_and_switch_key_from_a_foreign_device_are_ignored() {
1246        let apsme = Apsme::new(0xAB);
1247        let aib = setup_aib();
1248        let nib = nib_with_active_key();
1249
1250        // a key transported by anyone but the Trust Center
1251        apsme.handle_aps_command(
1252            &aib,
1253            &nib,
1254            &network_key(4, NEW_KEY, IeeeAddress(0x99)),
1255            true,
1256        );
1257        assert_eq!(nib.security_material_set().len(), 1);
1258
1259        apsme.handle_aps_command(&aib, &nib, &network_key(4, NEW_KEY, TC_IEEE), true);
1260        // a switch from a device that is not the Trust Center
1261        apsme.handle_aps_command(
1262            &aib,
1263            &nib,
1264            &Command::SwitchKey(SwitchKey { sequence_number: 4 }),
1265            false,
1266        );
1267        assert_eq!(*nib.active_key_seq_number(), 3);
1268
1269        // as is a switch to a key we never received
1270        apsme.handle_aps_command(
1271            &aib,
1272            &nib,
1273            &Command::SwitchKey(SwitchKey { sequence_number: 9 }),
1274            true,
1275        );
1276        assert_eq!(*nib.active_key_seq_number(), 3);
1277    }
1278}
1279
1280#[cfg(test)]
1281mod receive_path_tests {
1282    use core::future::Future;
1283
1284    use zigbee_mac::Address;
1285    use zigbee_mac::mlme::AssociationResponse;
1286    use zigbee_mac::mlme::MacConfig;
1287    use zigbee_mac::mlme::MacError;
1288    use zigbee_mac::mlme::Mlme;
1289    use zigbee_mac::mlme::ScanResult;
1290    use zigbee_mac::mlme::ScanType;
1291    use zigbee_types::ByteArray;
1292    use zigbee_types::IeeeAddress;
1293    use zigbee_types::ShortAddress;
1294
1295    use super::*;
1296    // NIB and AIB are process-wide singletons
1297    use crate::TEST_MUTEX;
1298    use crate::nwk::frame::DataFrame;
1299    use crate::nwk::frame::frame_control::DiscoverRoute;
1300    use crate::nwk::frame::frame_control::FrameControl as NwkFrameControl;
1301    use crate::nwk::frame::frame_control::FrameType as NwkFrameType;
1302    use crate::nwk::frame::header::Header as NwkHeader;
1303    use crate::nwk::nib;
1304
1305    const TC_IEEE: IeeeAddress = IeeeAddress(0x00_11_22_33_44_55_66_77);
1306    const TC_SHORT: u16 = 0x0000;
1307    const ACTIVE_KEY_SEQ: u8 = 3;
1308    const ACTIVE_KEY: [u8; 16] = [0xaa; 16];
1309    const ATTACKER_KEY: [u8; 16] = [0xbb; 16];
1310
1311    // never transmits, exists so an Nlme can be built
1312    mockall::mock! {
1313        Mlme {}
1314        impl Mlme for Mlme {
1315            fn ieee_address(&self) -> IeeeAddress;
1316            async fn configure(&self, config: MacConfig);
1317            async fn scan_network(
1318                &self,
1319                ty: ScanType,
1320                channels: core::ops::Range<u8>,
1321                duration: u8,
1322            ) -> Result<ScanResult, MacError>;
1323            async fn associate(
1324                &self,
1325                channel: u8,
1326                dest: Address,
1327                capabilities: zigbee_mac::CapabilityInformation,
1328            ) -> Result<AssociationResponse, MacError>;
1329            async fn poll_data(
1330                &self,
1331                coord_address: Address,
1332                buf: &mut [u8],
1333            ) -> Result<(usize, u8), MacError>;
1334            async fn receive(
1335                &self,
1336                buf: &mut [u8],
1337            ) -> Result<(usize, u8), MacError>;
1338            async fn transmit_data(
1339                &self,
1340                dest: Address,
1341                payload: &[u8],
1342            ) -> Result<(), MacError>;
1343            fn random_u32(&self) -> u32;
1344        }
1345    }
1346
1347    // the receive path never yields
1348    #[allow(clippy::panic)]
1349    fn block_on<F: Future>(f: F) -> F::Output {
1350        use core::pin::pin;
1351        use core::task::Context;
1352        use core::task::Poll;
1353        use core::task::Waker;
1354
1355        let waker = Waker::noop();
1356        let mut cx = Context::from_waker(waker);
1357        let mut f = pin!(f);
1358        match f.as_mut().poll(&mut cx) {
1359            Poll::Ready(val) => val,
1360            Poll::Pending => panic!("block_on: future returned Pending"),
1361        }
1362    }
1363
1364    fn setup() -> Nlme<MockMlme> {
1365        nib::try_init();
1366        nib::reset();
1367        aib::try_init();
1368        aib::get_ref().update_trust_center_address(|value| *value = TC_IEEE);
1369        // an empty neighbor table makes is_trust_center fall back to the
1370        // coordinator, which TC_SHORT satisfies
1371        nib::get_ref().update_neighbor_table(|value| *value = StorageVec::new());
1372        nib::get_ref().update_security_material_set(|set| {
1373            *set = StorageVec::new();
1374            let _ = set.push(NetworkSecurityMaterialDescriptor {
1375                key_seq_number: ACTIVE_KEY_SEQ,
1376                outgoing_frame_counter: 7,
1377                incoming_frame_counter_set: StorageVec::new(),
1378                key: ByteArray(ACTIVE_KEY),
1379                network_key_type: STANDARD_NETWORK_KEY,
1380            });
1381        });
1382        nib::get_ref().update_active_key_seq_number(|value| *value = ACTIVE_KEY_SEQ);
1383
1384        let mut mac = MockMlme::new();
1385        mac.expect_ieee_address()
1386            .return_const(IeeeAddress(0xa4c1_0000_0000_0001));
1387        mac.expect_random_u32().return_const(0u32);
1388        Nlme::new(mac)
1389    }
1390
1391    // an inbound NWK data frame as the NWK layer hands it to the APS. a shared
1392    // slice suffices while every frame here is APS-unsecured; only the secured
1393    // branch reaches for payload_as_mut, which casts the payload to &mut
1394    fn nwk_data_frame(aps: &[u8]) -> DataFrame<'_> {
1395        let header = NwkHeader {
1396            frame_control: NwkFrameControl(0)
1397                .set_frame_type(NwkFrameType::Data)
1398                .set_protocol_version(2)
1399                .set_discover_route(DiscoverRoute::Suppress),
1400            destination: ShortAddress(0x1234),
1401            source: ShortAddress(TC_SHORT),
1402            radius: 1,
1403            sequence_number: 0,
1404            destination_ieee: None,
1405            source_ieee: None,
1406            multicast_control: None,
1407            source_route_subframe: None,
1408        };
1409        DataFrame {
1410            header,
1411            payload: aps,
1412        }
1413    }
1414
1415    // frame control 0x01 (command, unicast, security clear), APS counter, then
1416    // the payload. command frames carry no endpoint/cluster/profile octets
1417    fn unsecured_aps_command(counter: u8, payload: &[u8]) -> std::vec::Vec<u8> {
1418        let mut frame = std::vec![0x01u8, counter];
1419        frame.extend_from_slice(payload);
1420        frame
1421    }
1422
1423    // 4.4.1.1: command id, key type, key, sequence number, destination IEEE,
1424    // source IEEE
1425    fn transport_network_key_payload(
1426        key: [u8; 16],
1427        seq: u8,
1428        source: IeeeAddress,
1429    ) -> std::vec::Vec<u8> {
1430        let mut payload = std::vec![0x05u8, 0x01u8];
1431        payload.extend_from_slice(&key);
1432        payload.push(seq);
1433        payload.extend_from_slice(&IeeeAddress(0x0102_0304_0506_0708).0.to_le_bytes());
1434        payload.extend_from_slice(&source.0.to_le_bytes());
1435        payload
1436    }
1437
1438    // 4.4.6.1.3 exempts only the broadcast Switch-Key from APS security, so an
1439    // unsecured network-key transport proves nothing: its source address is
1440    // plaintext the sender chose
1441    #[test]
1442    fn unsecured_network_key_transport_is_ignored() {
1443        let _guard = TEST_MUTEX
1444            .lock()
1445            .unwrap_or_else(std::sync::PoisonError::into_inner);
1446        let nlme = setup();
1447        let apsme = Apsme::new(0xAB);
1448
1449        // names the real Trust Center as the source
1450        let payload = transport_network_key_payload(ATTACKER_KEY, 4, TC_IEEE);
1451        let frame = unsecured_aps_command(0x42, &payload);
1452        let indication = block_on(apsme.process_nwk_data(&nlme, nwk_data_frame(&frame)))
1453            .expect("an APS command frame is consumed, not reported as an error");
1454        assert!(
1455            indication.is_none(),
1456            "a command frame yields no data indication"
1457        );
1458
1459        let set = nib::get_ref().security_material_set();
1460        assert_eq!(
1461            set.len(),
1462            1,
1463            "an APS-unsecured Transport-Key must not install a network key: only \
1464             the broadcast Switch-Key is exempt from APS security (4.4.6.1.3), and \
1465             the descriptor's source_address is attacker-controlled plaintext here"
1466        );
1467        assert_eq!(set[0].key_seq_number, ACTIVE_KEY_SEQ);
1468        assert_eq!(set[0].key, ByteArray(ACTIVE_KEY));
1469    }
1470
1471    // closing the hole above must not close the one command that legitimately
1472    // arrives unsecured (4.4.6.1.3)
1473    #[test]
1474    fn unsecured_switch_key_is_still_honoured() {
1475        let _guard = TEST_MUTEX
1476            .lock()
1477            .unwrap_or_else(std::sync::PoisonError::into_inner);
1478        let nlme = setup();
1479        let apsme = Apsme::new(0xAB);
1480
1481        // give the device an alternate key to switch to
1482        nib::get_ref().update_security_material_set(|set| {
1483            let _ = set.push(NetworkSecurityMaterialDescriptor {
1484                key_seq_number: 4,
1485                outgoing_frame_counter: 0,
1486                incoming_frame_counter_set: StorageVec::new(),
1487                key: ByteArray([0xcc; 16]),
1488                network_key_type: STANDARD_NETWORK_KEY,
1489            });
1490        });
1491
1492        let frame = unsecured_aps_command(0x43, &[0x09, 0x04]);
1493        let _ = block_on(apsme.process_nwk_data(&nlme, nwk_data_frame(&frame)))
1494            .expect("an APS command frame is consumed, not reported as an error");
1495
1496        assert_eq!(
1497            *nib::get_ref().active_key_seq_number(),
1498            4,
1499            "a broadcast Switch-Key carries no APS security by design (4.4.6.1.3)"
1500        );
1501    }
1502}