Skip to main content

zigbee_base_device_behavior/
lib.rs

1//! Implements the Zigbee Base Device Behavior (BDB) in `no-std` based on the
2//! [Zigbee Base Device Behavior Specification Rev. 13].
3//!
4//! [Zigbee Base Device Behavior Specification Rev. 13]: https://csa-iot.org/wp-content/uploads/2022/12/16-02828-012-PRO-BDB-v3.0.1-Specification.pdf
5//!
6//! This crate defines the standard commissioning procedures all devices must
7//! support. It is a thin commissioning orchestrator: it does not own the
8//! [`ZigbeeDevice`] or the [`Nlme`] — instead, callers pass the device to a
9//! commissioning procedure. Everything takes `&self`, like the layers below,
10//! so one instance can be shared; post-commissioning the application interacts
11//! with the stack through the APSDE-SAP exposed on [`ZigbeeDevice`].
12#![no_std]
13#![allow(unused)]
14
15#[cfg(test)]
16extern crate std;
17
18use core::future::Future;
19use core::future::poll_fn;
20use core::pin::pin;
21use core::sync::atomic::AtomicBool;
22use core::sync::atomic::Ordering;
23use core::task::Poll;
24
25use embedded_hal_async::delay::DelayNs;
26use spin::Mutex;
27use thiserror::Error;
28
29pub mod types;
30
31// BDB 5.1, table 1
32const BDBC_MAX_SAME_NETWORK_RETRY_ATTEMPTS: u8 = 10;
33const BDBC_MIN_COMMISSIONING_TIME: u8 = 0xb4;
34const BDBC_REC_SAME_NETWORK_RETRY_ATTEMPTS: u8 = 3;
35const BDBC_TC_LINK_KEY_EXCHANGE_TIMEOUT: u8 = 5;
36
37// bdbTCLinkKeyExchangeAttemptsMax (BDB 5.3.12)
38const TC_LINK_KEY_EXCHANGE_ATTEMPTS_MAX: u8 = 3;
39// a trust center reporting this stack revision or an earlier one predates the
40// TC link key exchange (BDB 10.2.5 step 5)
41const LEGACY_STACK_REVISION: u8 = 20;
42
43// bdbcTcLinkKeyExchangeTimeout in milliseconds
44const TC_LINK_KEY_EXCHANGE_TIMEOUT_MS: u32 = BDBC_TC_LINK_KEY_EXCHANGE_TIMEOUT as u32 * 1_000;
45
46use types::BdbCommissioningStatus;
47use types::CommissioningMode;
48use zigbee_core::Config;
49use zigbee_core::LogicalType;
50use zigbee_core::aps::aib;
51use zigbee_core::aps::frame::command::Command;
52use zigbee_core::aps::frame::command::RequestKey;
53use zigbee_core::aps::frame::command::VerifyKey;
54use zigbee_core::nwk::nib;
55use zigbee_core::nwk::nib::CapabilityInformation;
56use zigbee_core::nwk::nib::Nib;
57use zigbee_core::nwk::nlme::NetworkError;
58use zigbee_core::nwk::nlme::Nlme;
59use zigbee_core::nwk::nlme::management::NlmeJoinConfirm;
60use zigbee_core::nwk::nlme::management::NlmeJoinRequest;
61use zigbee_core::nwk::nlme::management::NlmeJoinStatus;
62use zigbee_core::nwk::nlme::management::NlmeNetworkFormationRequest;
63use zigbee_core::nwk::nlme::management::NlmePermitJoiningRequest;
64use zigbee_core::nwk::nlme::management::RejoinNetwork;
65use zigbee_core::security::primitives::HmacAes128Mmo;
66use zigbee_core::zdo::ZigbeeDevice;
67use zigbee_core::zdo::descriptor::NodeDescRsp;
68use zigbee_mac::mlme::MacConfig;
69use zigbee_mac::mlme::Mlme;
70use zigbee_types::ByteArray;
71use zigbee_types::IeeeAddress;
72use zigbee_types::ShortAddress;
73use zigbee_types::sync::with_timeout;
74
75/// Base Device Behavior (BDB) commissioning manager.
76///
77/// Orchestrates the standard commissioning procedures defined in the BDB
78/// specification: initialization, network steering, network formation,
79/// finding & binding, and touchlink. The application owns the
80/// [`ZigbeeDevice`] and the [`Nlme`]; commissioning methods borrow the device
81/// for the duration of the procedure.
82///
83/// Like the layers below, procedures take `&self` and keep their few
84/// attributes (BDB 5.3) behind interior mutability, so one instance can be
85/// shared. They are not meant to overlap, though: run one commissioning
86/// procedure at a time.
87pub struct BaseDeviceBehavior {
88    config: Config,
89    // bdbNodeIsOnANetwork (BDB 5.3.9)
90    bdb_node_is_on_a_network: AtomicBool,
91    // bdbCommissioningMode (BDB 5.3.5)
92    bdb_commissioning_mode: Mutex<CommissioningMode>,
93    // bdbCommissioningStatus (BDB 5.3.1)
94    bdb_commissioning_status: Mutex<BdbCommissioningStatus>,
95    // whether network steering exchanges the TC link key (BDB 8.2 step 12)
96    tc_link_key_exchange_enabled: AtomicBool,
97}
98
99impl BaseDeviceBehavior {
100    pub fn new(config: Config) -> Self {
101        Self {
102            config,
103            bdb_node_is_on_a_network: AtomicBool::new(false),
104            bdb_commissioning_mode: Mutex::new(CommissioningMode::NetworkSteering),
105            bdb_commissioning_status: Mutex::new(BdbCommissioningStatus::Success),
106            tc_link_key_exchange_enabled: AtomicBool::new(true),
107        }
108    }
109
110    /// Returns a reference to the global NIB singleton.
111    pub fn nib(&self) -> &'static Nib {
112        nib::get_ref()
113    }
114
115    /// bdbCommissioningStatus (BDB 5.3.1): how the last commissioning
116    /// procedure ended, or `InProgress` while one runs.
117    pub fn commissioning_status(&self) -> BdbCommissioningStatus {
118        *self.bdb_commissioning_status.lock()
119    }
120
121    /// bdbCommissioningMode (BDB 5.3.5): the procedure commissioning runs.
122    pub fn commissioning_mode(&self) -> CommissioningMode {
123        *self.bdb_commissioning_mode.lock()
124    }
125
126    /// bdbNodeIsOnANetwork (BDB 5.3.9): whether the node is on a network.
127    pub fn node_is_on_a_network(&self) -> bool {
128        self.bdb_node_is_on_a_network.load(Ordering::Relaxed)
129    }
130
131    /// Whether network steering exchanges the initial Trust Center link key
132    /// for a unique one (BDB 8.2 step 12); a failed exchange takes the node
133    /// off the network again.
134    ///
135    /// Disable to stay on the default global TC link key with a trust center
136    /// that answers neither Node_Desc_req nor REQUEST-KEY, at the cost of
137    /// leaving the join unauthenticated.
138    pub fn set_tc_link_key_exchange(&self, enabled: bool) {
139        self.tc_link_key_exchange_enabled
140            .store(enabled, Ordering::Relaxed);
141    }
142
143    fn set_commissioning_status(&self, status: BdbCommissioningStatus) {
144        *self.bdb_commissioning_status.lock() = status;
145    }
146
147    /// Initialization procedure (BDB 7.1).
148    ///
149    /// Persistent state (NIB/AIB) must already be restored by the caller
150    /// before constructing the [`Nlme`]/[`ZigbeeDevice`] — that is step 1.
151    /// If the node is not on a network, or is not an end device, this
152    /// returns `Ok(None)` and the caller should invoke
153    /// [`Self::network_steering`].
154    ///
155    /// Step 4 delegates to [`ZigbeeDevice::rejoin`], so a Trust Center rejoin
156    /// backs up the secure one. If both fail the caller is responsible for
157    /// falling back to [`Self::network_steering`] after
158    /// [`ZigbeeDevice::forget_network`]; keeping the parent link alive
159    /// afterwards is [`ZigbeeDevice::link_maintenance`].
160    pub async fn start_initialization_procedure<M: Mlme>(
161        &self,
162        device: &ZigbeeDevice<M>,
163        delay: &mut impl DelayNs,
164    ) -> Result<Option<NlmeJoinConfirm>, NetworkError> {
165        let nib = self.nib();
166
167        // BDB 7.1 step 2
168        let on_a_network = *nib.network_address() != 0xffff;
169        self.bdb_node_is_on_a_network
170            .store(on_a_network, Ordering::Relaxed);
171        if !on_a_network {
172            return Ok(None);
173        }
174
175        // BDB 7.1 step 3: only an end device attempts an automatic rejoin
176        // here; a router's channel-verification step (7.1 steps 6-7) is not
177        // yet implemented
178        if !self.is_end_device() {
179            return Ok(None);
180        }
181
182        // BDB 7.1 step 4: rejoin on the current channel, so no scan channels.
183        // Read the guard's value out before the `.await` — held across it,
184        // it'd deadlock against rejoin_confirm's write of the same NIB field.
185        log::debug!("[BDB] step 4: attempt NWK rejoin");
186        let extended_panid = *nib.extended_panid();
187        let confirm = device.rejoin(IeeeAddress(extended_panid), 0..0, 0).await?;
188
189        // BDB 7.1 step 5
190        if confirm.status == NlmeJoinStatus::Success {
191            log::debug!("[BDB] step 5: rejoin succeeded");
192            self.set_commissioning_status(BdbCommissioningStatus::Success);
193        } else {
194            log::warn!("[BDB] step 5: rejoin failed ({:?})", confirm.status);
195            self.set_commissioning_status(BdbCommissioningStatus::NoNetwork);
196        }
197
198        Ok(Some(confirm))
199    }
200
201    /// Network steering procedure for a node not on a network (BDB 8.2).
202    ///
203    /// Discovers and joins the network at `extended_pan_id`, then exchanges
204    /// keys with the Trust Center.
205    ///
206    /// The receive loop task must be spawned before calling this: it idles
207    /// until the join completes (`ZigbeeDevice::rx_loop`), then delivers the
208    /// Trust Center's replies for the link key exchange.
209    pub async fn network_steering<M: Mlme>(
210        &self,
211        device: &ZigbeeDevice<M>,
212        delay: &mut impl DelayNs,
213        extended_pan_id: IeeeAddress,
214        channels: core::ops::Range<u8>,
215        scan_duration: u8,
216        capability_information: CapabilityInformation,
217    ) -> Result<NlmeJoinConfirm, NetworkError> {
218        log::debug!(
219            "[BDB] start network steering, EPID={extended_pan_id:?}, channels={channels:?}"
220        );
221        self.set_commissioning_status(BdbCommissioningStatus::InProgress);
222
223        // a node steering onto a network holds no valid link keys for it: any
224        // left over from an earlier network would reject the Trust Center's
225        // Transport-Key (4.4.10)
226        device.reset_trust_center_link_keys();
227
228        // BDB 8.2 step 1
229        device
230            .nlme()
231            .network_discovery(channels, scan_duration)
232            .await?;
233
234        // BDB 8.2 step 5
235        let request = NlmeJoinRequest {
236            extended_pan_id,
237            rejoin_network: RejoinNetwork::Association,
238            capability_information,
239            security_enabled: false,
240            // an association join selects its parent from the neighbor table
241            // filled by the discovery above
242            scan_channels: 0..0,
243            scan_duration: 0,
244        };
245        let confirm = device.nlme().join(request).await;
246        if confirm.status != NlmeJoinStatus::Success {
247            self.set_commissioning_status(BdbCommissioningStatus::NoNetwork);
248            return Ok(confirm);
249        }
250
251        // BDB 8.2 step 9
252        log::debug!("[BDB] step 9: poll for network key (transport-key)");
253        device.poll_transport_key().await?;
254        log::debug!("[BDB] step 9: network key installed");
255
256        // 3.6.10.2: negotiate the end-device timeout with the parent
257        let _ = device.nlme().negotiate_end_device_timeout().await;
258
259        // BDB 8.2 step 11
260        log::debug!("[BDB] step 11: broadcast Device_annce");
261        device.announce_self().await?;
262
263        // BDB 8.2 step 12, BDB 10.2.5
264        if self.tc_link_key_exchange_enabled.load(Ordering::Relaxed) {
265            log::debug!("[BDB] step 12: TC link key exchange");
266            // BDB 8.2 step 12: staying on the network with an unexchanged key
267            // is not permitted — the node leaves and resets its network state
268            if let Err(e) = self.tc_link_key_exchange(device, delay).await {
269                log::warn!("[BDB] step 12: TC link key exchange failed ({e:?}), leaving network");
270                self.set_commissioning_status(BdbCommissioningStatus::TclkExFailure);
271                self.bdb_node_is_on_a_network
272                    .store(false, Ordering::Relaxed);
273                let status = device.leave_network(false).await;
274                log::info!("[BDB] left the network after TCLK failure: {status:?}");
275                return Err(e);
276            }
277            log::debug!("[BDB] step 12: TC link key exchange complete");
278        } else {
279            log::debug!("[BDB] step 12: TC link key exchange disabled, skipping");
280        }
281
282        self.bdb_node_is_on_a_network.store(true, Ordering::Relaxed);
283        self.set_commissioning_status(BdbCommissioningStatus::Success);
284        Ok(confirm)
285    }
286
287    // TC link key exchange procedure (BDB 10.2.5): REQUEST-KEY ->
288    // TRANSPORT-KEY -> VERIFY-KEY -> CONFIRM-KEY; the receive loop consumes
289    // the Trust Center's replies, this only drives the timing
290    async fn tc_link_key_exchange<M: Mlme>(
291        &self,
292        device: &ZigbeeDevice<M>,
293        delay: &mut impl DelayNs,
294    ) -> Result<(), NetworkError> {
295        // arm the stack: only now are Transport-Key/Confirm-Key honored, so
296        // replayed frames outside the exchange cannot downgrade the key
297        device.begin_tc_link_key_exchange();
298        let result = self.run_tc_link_key_exchange(device, delay).await;
299        device.end_tc_link_key_exchange();
300        result
301    }
302
303    async fn run_tc_link_key_exchange<M: Mlme>(
304        &self,
305        device: &ZigbeeDevice<M>,
306        delay: &mut impl DelayNs,
307    ) -> Result<(), NetworkError> {
308        let tc_short = ShortAddress(0x0000);
309        let aib = aib::get_ref();
310        let tc_ieee = *aib.trust_center_address();
311
312        log::debug!("[BDB] start TC link key exchange, TC={tc_ieee:?}");
313
314        // BDB 10.2.5 steps 2-5: a trust center on r20 or earlier knows no key
315        // exchange, and asking it for a key would stall the commissioning
316        let Some(node_desc) = self
317            .request_trust_center_node_desc(device, delay, tc_short)
318            .await
319        else {
320            log::warn!("[BDB] TC link key exchange failed: no Node_Desc_rsp");
321            self.set_commissioning_status(BdbCommissioningStatus::TclkExFailure);
322            return Err(NetworkError::NoTransportKey);
323        };
324        if node_desc
325            .stack_revision()
326            .is_some_and(|revision| revision <= LEGACY_STACK_REVISION)
327        {
328            log::info!(
329                "[BDB] trust center reports stack revision {:?}, keeping the default TC link key",
330                node_desc.stack_revision()
331            );
332            return Ok(());
333        }
334
335        // BDB 10.2.5 steps 6-9: the receive loop installs the transported
336        // key as unverified and signals reception
337        let mut attempts = 0u8;
338        loop {
339            device
340                .send_aps_command(
341                    tc_short,
342                    tc_ieee,
343                    Command::RequestKey(RequestKey::TrustCenterLinkKey),
344                    true,
345                )
346                .await?;
347            attempts += 1;
348
349            match with_timeout(
350                device.wait_tc_link_key_received(),
351                delay.delay_ms(TC_LINK_KEY_EXCHANGE_TIMEOUT_MS),
352            )
353            .await
354            {
355                Some(true) => {
356                    log::debug!("[BDB] received new TC link key");
357                    break;
358                }
359                // step 9: the transported key was rejected — it is the one we
360                // already hold, which ends the procedure rather than retrying
361                Some(false) => {
362                    log::warn!("[BDB] TC link key exchange failed: unusable TRANSPORT-KEY");
363                    self.set_commissioning_status(BdbCommissioningStatus::TclkExFailure);
364                    return Err(NetworkError::NoTransportKey);
365                }
366                None if attempts >= TC_LINK_KEY_EXCHANGE_ATTEMPTS_MAX => {
367                    log::warn!("[BDB] TC link key exchange failed: no TRANSPORT-KEY");
368                    self.set_commissioning_status(BdbCommissioningStatus::TclkExFailure);
369                    return Err(NetworkError::NoTransportKey);
370                }
371                None => continue,
372            }
373        }
374
375        // BDB 10.2.5 step 9: the unverified key is now in the AIB
376        let new_key = aib
377            .device_key_pair_set()
378            .iter()
379            .find(|k| k.device_address == tc_ieee)
380            .map(|k| k.link_key)
381            .ok_or(NetworkError::NoTransportKey)?;
382
383        // BDB 10.2.5 steps 10-13, 4.4.10.7.4
384        let hash = HmacAes128Mmo::hmac(new_key.as_slice(), &[0x03]).map_err(|_| {
385            NetworkError::SecurityError(zigbee_core::security::SecurityError::Unspecified)
386        })?;
387        // 4.4.10.7.3
388        let device_addr = *nib::get_ref().ieee_address();
389
390        let mut attempts = 0u8;
391        loop {
392            device
393                .send_aps_command(
394                    tc_short,
395                    tc_ieee,
396                    Command::VerifyKey(VerifyKey {
397                        key_type: 0x04,
398                        source_address: device_addr,
399                        hash: ByteArray(hash),
400                    }),
401                    false,
402                )
403                .await?;
404            attempts += 1;
405
406            match with_timeout(
407                device.wait_tc_link_key_verified(),
408                delay.delay_ms(TC_LINK_KEY_EXCHANGE_TIMEOUT_MS),
409            )
410            .await
411            {
412                Some(0x00) => {
413                    log::debug!("[BDB] TC link key verified successfully");
414                    return Ok(());
415                }
416                // rejected verification: retry immediately instead of
417                // burning the full timeout
418                Some(status) if attempts < BDBC_MAX_SAME_NETWORK_RETRY_ATTEMPTS => {
419                    log::warn!("[BDB] CONFIRM-KEY status {status:#04x}, retrying");
420                }
421                None if attempts < BDBC_MAX_SAME_NETWORK_RETRY_ATTEMPTS => continue,
422                _ => {
423                    log::warn!("[BDB] TC link key exchange failed: no CONFIRM-KEY");
424                    self.set_commissioning_status(BdbCommissioningStatus::TclkExFailure);
425                    return Err(NetworkError::NoTransportKey);
426                }
427            }
428        }
429    }
430
431    // BDB 10.2.5 steps 3-4: read the trust center's node descriptor, retrying
432    // until bdbTCLinkKeyExchangeAttemptsMax attempts are spent
433    async fn request_trust_center_node_desc<M: Mlme>(
434        &self,
435        device: &ZigbeeDevice<M>,
436        delay: &mut impl DelayNs,
437        tc_short: ShortAddress,
438    ) -> Option<NodeDescRsp> {
439        for _ in 0..TC_LINK_KEY_EXCHANGE_ATTEMPTS_MAX {
440            if let Err(e) = device.node_desc_req(tc_short).await {
441                log::warn!("[BDB] Node_Desc_req to the trust center failed ({e:?})");
442                delay.delay_ms(TC_LINK_KEY_EXCHANGE_TIMEOUT_MS).await;
443                continue;
444            }
445            if let Some(response) = with_timeout(
446                device.wait_node_desc_rsp(),
447                delay.delay_ms(TC_LINK_KEY_EXCHANGE_TIMEOUT_MS),
448            )
449            .await
450            {
451                return Some(response);
452            }
453        }
454        None
455    }
456
457    fn is_end_device(&self) -> bool {
458        self.config.device_type == LogicalType::EndDevice
459    }
460
461    fn is_router(&self) -> bool {
462        self.config.device_type == LogicalType::Router
463    }
464}
465
466#[derive(Debug, Error)]
467pub enum BdbError {
468    #[error("network error")]
469    NetworkError(#[from] NetworkError),
470
471    #[error("no open network discovered to join")]
472    NoNetwork,
473}
474
475#[cfg(test)]
476mod tests {
477    use core::future::Future;
478    use core::sync::atomic::AtomicBool;
479    use core::sync::atomic::Ordering;
480
481    use zigbee_core::nwk::nib;
482    use zigbee_mac::Address;
483    use zigbee_mac::mlme::AssociationResponse;
484    use zigbee_mac::mlme::MacError;
485    use zigbee_mac::mlme::ScanResult;
486    use zigbee_mac::mlme::ScanType;
487
488    use super::*;
489
490    #[allow(clippy::panic)]
491    fn block_on<F: Future>(f: F) -> F::Output {
492        use core::pin::pin;
493        use core::task::Context;
494        use core::task::Poll;
495        use core::task::RawWaker;
496        use core::task::RawWakerVTable;
497        use core::task::Waker;
498
499        fn noop(_: *const ()) {}
500        fn clone(p: *const ()) -> RawWaker {
501            RawWaker::new(p, &VTABLE)
502        }
503        static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
504
505        let waker = unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &VTABLE)) };
506        let mut cx = Context::from_waker(&waker);
507        let mut f = pin!(f);
508
509        match f.as_mut().poll(&mut cx) {
510            Poll::Ready(val) => val,
511            Poll::Pending => panic!("block_on: future returned Pending"),
512        }
513    }
514
515    mockall::mock! {
516        Mlme {}
517        impl Mlme for Mlme {
518            fn ieee_address(&self) -> IeeeAddress;
519            async fn configure(&self, config: MacConfig);
520            async fn scan_network(
521                &self,
522                ty: ScanType,
523                channels: core::ops::Range<u8>,
524                duration: u8,
525            ) -> Result<ScanResult, MacError>;
526            async fn associate(
527                &self,
528                channel: u8,
529                dest: Address,
530                capabilities: zigbee_mac::CapabilityInformation,
531            ) -> Result<AssociationResponse, MacError>;
532            async fn poll_data(
533                &self,
534                coord_address: Address,
535                buf: &mut [u8],
536            ) -> Result<(usize, u8), MacError>;
537            async fn receive(
538                &self,
539                buf: &mut [u8],
540            ) -> Result<(usize, u8), MacError>;
541            async fn transmit_data(
542                &self,
543                dest: Address,
544                payload: &[u8],
545            ) -> Result<(), MacError>;
546            fn random_u32(&self) -> u32;
547        }
548    }
549
550    // returns immediately, so block_on never sees Pending
551    struct NoopDelay;
552
553    impl DelayNs for NoopDelay {
554        async fn delay_ns(&mut self, _ns: u32) {}
555    }
556
557    fn make_device(device_type: LogicalType) -> ZigbeeDevice<MockMlme> {
558        let mut mac = MockMlme::new();
559        mac.expect_ieee_address()
560            .return_const(IeeeAddress(0xa4c1_0000_0000_0001));
561        mac.expect_random_u32().return_const(0u32);
562        let nlme = Nlme::new(mac);
563        let config = Config {
564            device_type,
565            ..Config::default()
566        };
567        ZigbeeDevice::new(config, nlme)
568    }
569
570    // NIB is a process-wide singleton with a non-cfg(test) `init()` (no
571    // `try_init`/`reset` outside the `zigbee-core` crate itself), so every case
572    // that needs it lives in one #[test] to keep initialization order
573    // deterministic across the crate's test binary.
574    #[test]
575    fn start_initialization_procedure_early_returns() {
576        nib::init();
577        zigbee_core::aps::aib::init();
578
579        let device = make_device(LogicalType::EndDevice);
580        let bdb = BaseDeviceBehavior::new(Config {
581            device_type: LogicalType::EndDevice,
582            ..Config::default()
583        });
584        let result = block_on(bdb.start_initialization_procedure(&device, &mut NoopDelay));
585        assert!(matches!(result, Ok(None)));
586        assert!(!bdb.node_is_on_a_network());
587
588        nib::get_ref().update_network_address(|value| *value = 0x1234);
589        let router_device = make_device(LogicalType::Router);
590        let router_bdb = BaseDeviceBehavior::new(Config {
591            device_type: LogicalType::Router,
592            ..Config::default()
593        });
594        let result =
595            block_on(router_bdb.start_initialization_procedure(&router_device, &mut NoopDelay));
596        assert!(matches!(result, Ok(None)));
597        assert!(router_bdb.node_is_on_a_network());
598    }
599}