Skip to main content

capsules_extra/ieee802154/
framer.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Implements IEEE 802.15.4 MAC device abstraction over a 802.15.4 MAC interface.
6//!
7//! Allows its users to prepare and send frames in plaintext, handling 802.15.4
8//! encoding and security procedures (in the future) transparently.
9//!
10//! However, certain IEEE 802.15.4 MAC device concepts are not implemented in
11//! this layer of abstraction and instead handled in hardware for performance
12//! purposes. These include CSMA-CA backoff, FCS generation and authentication,
13//! and automatic acknowledgement. Radio power management and channel selection
14//! is also passed down to the MAC control layer.
15//!
16//! Usage
17//! -----
18//!
19//! To use this capsule, we need an implementation of a hardware
20//! `capsules_extra::ieee802154::mac::Mac`. Suppose we have such an implementation of type
21//! `XMacDevice`.
22//!
23//! ```rust,ignore
24//! let xmac: &XMacDevice = /* ... */;
25//! let mac_device = static_init!(
26//!     capsules_extra::ieee802154::mac::Framer<'static, XMacDevice>,
27//!     capsules_extra::ieee802154::mac::Framer::new(xmac));
28//! xmac.set_transmit_client(mac_device);
29//! xmac.set_receive_client(mac_device, &mut MAC_RX_BUF);
30//! xmac.set_config_client(mac_device);
31//! ```
32//!
33//! The `mac_device` device is now set up. Users of the MAC device can now
34//! configure the underlying radio, prepare and send frames:
35//!
36//! ```rust,ignore
37//! mac_device.set_pan(0xABCD);
38//! mac_device.set_address(0x1008);
39//! mac_device.config_commit();
40//!
41//! let frame = mac_device
42//!     .prepare_data_frame(&mut STATIC_BUFFER,
43//!                         0xABCD, MacAddress::Short(0x1008),
44//!                         0xABCD, MacAddress::Short(0x1009),
45//!                         None)
46//!     .ok()
47//!     .map(|frame| {
48//!         let rval = frame.append_payload(&mut SOME_DATA[..10]);
49//!         if rval == Ok(()) {
50//!             let (rval, _) = mac_device.transmit(frame);
51//!             rval
52//!         } else {
53//!             rval
54//!         }
55//!     });
56//! ```
57//!
58//! You should also be able to set up the userspace driver for receiving/sending
59//! 802.15.4 frames:
60//!
61//! ```rust,ignore
62//! use kernel::static_init;
63//!
64//! let radio_capsule = static_init!(
65//!     capsules_extra::ieee802154::RadioDriver<'static>,
66//!     capsules_extra::ieee802154::RadioDriver::new(mac_device, board_kernel.create_grant(&grant_cap), &mut RADIO_BUF));
67//! mac_device.set_key_procedure(radio_capsule);
68//! mac_device.set_device_procedure(radio_capsule);
69//! mac_device.set_transmit_client(radio_capsule);
70//! mac_device.set_receive_client(radio_capsule);
71//! ```
72
73//
74// TODO: Encryption/decryption
75// TODO: Sending beacon frames
76// TODO: Channel scanning
77//
78
79use crate::ieee802154::device::{MacDevice, RxClient, TxClient};
80use crate::ieee802154::mac::Mac;
81use crate::net::ieee802154::{
82    FrameType, FrameVersion, Header, KeyId, MacAddress, PanID, Security, SecurityLevel,
83};
84use crate::net::stream::SResult;
85use crate::net::stream::{encode_bytes, encode_u8, encode_u32};
86
87use core::cell::Cell;
88
89use kernel::ErrorCode;
90use kernel::hil::radio::{self, LQI_SIZE};
91use kernel::hil::symmetric_encryption::{AES128, AESCCM, CCMClient};
92use kernel::processbuffer::ReadableProcessSlice;
93use kernel::utilities::cells::{MapCell, OptionalCell};
94use kernel::utilities::leasable_buffer::SubSliceMut;
95
96/// Wraps a static mutable byte slice along with header information
97/// for a payload.
98///
99/// This enables the user to abdicate any concerns about
100/// where the payload should be placed in the buffer.
101#[derive(Eq, PartialEq, Debug)]
102pub struct Frame {
103    buf: &'static mut [u8],
104    info: FrameInfo,
105}
106
107/// This contains just enough information about a frame to determine
108///
109/// 1. How to encode it once its payload has been finalized
110/// 2. The sizes of the mac header, payload and MIC tag length to be added
111///
112/// These offsets are relative to the PSDU or `buf[radio::PSDU_OFFSET..]` so
113/// that the mac frame length is `data_offset + data_len`
114#[derive(Copy, Clone, Eq, PartialEq, Debug)]
115struct FrameInfo {
116    frame_type: FrameType,
117
118    // The MAC payload, including Payload IEs
119    mac_payload_offset: usize,
120    // The data payload, not including Payload IEs
121    data_offset: usize,
122    // The length of the data payload, not including MIC and FCS
123    data_len: usize,
124    // The length of the MIC
125    mic_len: usize,
126
127    // Security level, key, and nonce
128    security_params: Option<(SecurityLevel, [u8; 16], [u8; 13])>,
129}
130
131impl Frame {
132    /// Consumes the frame and retrieves the buffer it wraps
133    pub fn into_buf(self) -> &'static mut [u8] {
134        self.buf
135    }
136
137    /// Calculates how much more data this frame can hold
138    pub fn remaining_data_capacity(&self) -> usize {
139        self.buf.len() - self.info.secured_length()
140    }
141
142    /// Appends payload bytes into the frame if possible
143    pub fn append_payload(&mut self, payload: &[u8]) -> Result<(), ErrorCode> {
144        if payload.len() > self.remaining_data_capacity() {
145            return Err(ErrorCode::NOMEM);
146        }
147        let begin = self.info.unsecured_length();
148        self.buf[begin..begin + payload.len()].copy_from_slice(payload);
149        self.info.data_len += payload.len();
150
151        Ok(())
152    }
153
154    /// Appends payload bytes from a process slice into the frame if
155    /// possible
156    pub fn append_payload_process(
157        &mut self,
158        payload_buf: &ReadableProcessSlice,
159    ) -> Result<(), ErrorCode> {
160        if payload_buf.len() > self.remaining_data_capacity() {
161            return Err(ErrorCode::NOMEM);
162        }
163        let begin = self.info.unsecured_length();
164        payload_buf.copy_to_slice(&mut self.buf[begin..begin + payload_buf.len()]);
165        self.info.data_len += payload_buf.len();
166
167        Ok(())
168    }
169}
170
171impl FrameInfo {
172    /// Current size of the frame, not including the MAC footer or the MIC
173    fn unsecured_length(&self) -> usize {
174        self.data_offset + self.data_len
175    }
176
177    /// Current size of the frame, not including the MAC footer but including
178    /// the MIC
179    fn secured_length(&self) -> usize {
180        self.data_offset + self.data_len + self.mic_len
181    }
182
183    /// Compute the offsets in the buffer for the a data and m data fields in
184    /// the CCM* authentication and encryption procedures which depends on the
185    /// frame type and security levels. Returns the (offset, len) of the m data
186    /// fields, not including the MIC. The a data is always the remaining prefix
187    /// of the header, so it can be determined implicitly.
188    #[allow(dead_code)]
189    fn ccm_encrypt_ranges(&self) -> (usize, usize) {
190        // IEEE 802.15.4-2015: Table 9-1. Exceptions to Private Payload field
191        // The boundary between open and private payload fields depends
192        // on the type of frame.
193        let private_payload_offset = match self.frame_type {
194            FrameType::Beacon => {
195                // Beginning of beacon payload field
196                unimplemented!()
197            }
198            FrameType::MACCommand => {
199                // Beginning of MAC command content field
200                unimplemented!()
201            }
202            _ => {
203                // MAC payload field, which includes payload IEs
204                self.mac_payload_offset
205            }
206        };
207
208        // IEEE 802.15.4-2015: Table 9-3. a data and m data
209        let encryption_needed = self
210            .security_params
211            .is_some_and(|(level, _, _)| level.encryption_needed());
212        if !encryption_needed {
213            // If only integrity is need, a data is the whole frame
214            (self.unsecured_length(), 0)
215        } else {
216            // Otherwise, a data is the header and the open payload, and
217            // m data is the private payload field; unsecured length is the end of
218            // private payload, length of private payload is difference between
219            // the offset and unsecured length
220            (
221                private_payload_offset,                           // m_offset
222                self.unsecured_length() - private_payload_offset, // m_len
223            )
224        }
225    }
226}
227
228/// Generate a 15.4 CCM nonce from the device address, frame counter, and SecurityLevel
229pub fn get_ccm_nonce(device_addr: &[u8; 8], frame_counter: u32, level: SecurityLevel) -> [u8; 13] {
230    let mut nonce = [0u8; 13];
231    let encode_ccm_nonce = |buf: &mut [u8]| {
232        let off = enc_consume!(buf; encode_bytes, device_addr.as_ref());
233        let off = enc_consume!(buf, off; encode_u32, frame_counter);
234        let off = enc_consume!(buf, off; encode_u8, level as u8);
235        stream_done!(off);
236    };
237    match encode_ccm_nonce(&mut nonce).done() {
238        None => {
239            // This should not be possible
240            panic!("Failed to produce ccm nonce");
241        }
242        Some(_) => nonce,
243    }
244}
245
246/// The needed buffer size might be bigger than an MTU, because
247/// the CCM* authentication procedure
248///
249/// - adds an extra 16-byte block in front of the a and m data
250/// - prefixes the a data with a length encoding and pads the result
251/// - pads the m data to 16-byte blocks
252pub const CRYPT_BUF_SIZE: usize = radio::MAX_MTU + 3 * 16;
253
254/// IEEE 802.15.4-2015, 9.2.2, KeyDescriptor lookup procedure.
255///
256/// Trait to be implemented by an upper layer that manages the list of 802.15.4
257/// key descriptors. This trait interface enables the lookup procedure to be
258/// implemented either explicitly (managing a list of KeyDescriptors) or
259/// implicitly with some equivalent logic.
260pub trait KeyProcedure {
261    /// Lookup the KeyDescriptor matching the provided security level and key ID
262    /// mode and return the key associated with it.
263    fn lookup_key(&self, level: SecurityLevel, key_id: KeyId) -> Option<[u8; 16]>;
264}
265
266/// IEEE 802.15.4-2015, 9.2.5, DeviceDescriptor lookup procedure.
267///
268/// Trait to be implemented by an upper layer that manages the list of 802.15.4
269/// device descriptors. This trait interface enables the lookup procedure to be
270/// implemented either explicitly (managing a list of DeviceDescriptors) or
271/// implicitly with some equivalent logic.
272pub trait DeviceProcedure {
273    /// Look up the extended MAC address of a device given either its short or
274    /// long address. As defined in the IEEE 802.15.4 spec, even if the provided
275    /// address is already long, a long address should be returned only if the
276    /// given address matches a known DeviceDescriptor.
277    fn lookup_addr_long(&self, addr: MacAddress) -> Option<[u8; 8]>;
278}
279
280/// This state enum describes the state of the transmission pipeline.
281///
282/// Conditionally-present state is also included as fields in the enum variants.
283/// We can view the transmission process as a state machine driven by the
284/// following events:
285///
286/// - calls to `Mac#transmit`
287/// - `send_done` callbacks from the underlying radio
288/// - `config_done` callbacks from the underlying radio (if, for example,
289///   configuration was in progress when a transmission was requested)
290#[derive(Eq, PartialEq, Debug)]
291enum TxState {
292    /// There is no frame to be transmitted.
293    Idle,
294    /// There is a valid frame that needs to be secured before transmission.
295    ReadyToEncrypt(FrameInfo, &'static mut [u8]),
296    /// There is currently a frame being encrypted by the encryption facility.
297    #[allow(dead_code)]
298    Encrypting(FrameInfo),
299    /// There is a frame that is completely secured or does not require
300    /// security, and is waiting to be passed to the radio.
301    ReadyToTransmit(FrameInfo, &'static mut [u8]),
302}
303
304#[derive(Eq, PartialEq, Debug)]
305enum RxState {
306    /// There is no frame that has been received.
307    Idle,
308    /// There is a secured frame that needs to be decrypted.
309    /// ReadyToDecrypt(FrameInfo, buf, lqi)
310    ReadyToDecrypt(FrameInfo, &'static mut [u8], u8),
311    /// A secured frame is currently being decrypted by the decryption facility.
312    /// Decrypting(FrameInfo, lqi)
313    #[allow(dead_code)]
314    Decrypting(FrameInfo, u8),
315    /// There is an unsecured frame that needs to be re-parsed and exposed to
316    /// the client. ReadyToYield(FrameInfo, buf, lqi)
317    #[allow(dead_code)]
318    ReadyToYield(FrameInfo, &'static mut [u8], u8),
319}
320
321/// Wraps an IEEE 802.15.4 [kernel::hil::radio::Radio]
322/// and exposes [`capsules_extra::ieee802154::mac::Mac`](crate::ieee802154::mac::Mac) functionality.
323///
324/// It hides header preparation, transmission and processing logic
325/// from the user by essentially maintaining multiple state machines
326/// corresponding to the transmission, reception and
327/// encryption/decryption pipelines. See the documentation in
328/// `capsules/extra/src/ieee802154/mac.rs` for more details.
329pub struct Framer<'a, M: Mac<'a>, A: AESCCM<'a, AES128>> {
330    mac: &'a M,
331    aes_ccm: &'a A,
332    data_sequence: Cell<u8>,
333
334    /// KeyDescriptor lookup procedure
335    key_procedure: OptionalCell<&'a dyn KeyProcedure>,
336    /// DeviceDescriptor lookup procedure
337    device_procedure: OptionalCell<&'a dyn DeviceProcedure>,
338
339    /// Transmission pipeline state. This should never be `None`, except when
340    /// transitioning between states. That is, any method that consumes the
341    /// current state should always remember to replace it along with the
342    /// associated state information.
343    tx_state: MapCell<TxState>,
344    tx_client: OptionalCell<&'a dyn TxClient>,
345
346    /// Reception pipeline state. Similar to the above, this should never be
347    /// `None`, except when transitioning between states.
348    rx_state: MapCell<RxState>,
349    rx_client: OptionalCell<&'a dyn RxClient>,
350    crypt_buf: MapCell<SubSliceMut<'static, u8>>,
351}
352
353impl<'a, M: Mac<'a>, A: AESCCM<'a, AES128>> Framer<'a, M, A> {
354    pub fn new(
355        mac: &'a M,
356        aes_ccm: &'a A,
357        crypt_buf: SubSliceMut<'static, u8>,
358    ) -> Framer<'a, M, A> {
359        Framer {
360            mac,
361            aes_ccm,
362            data_sequence: Cell::new(0),
363            key_procedure: OptionalCell::empty(),
364            device_procedure: OptionalCell::empty(),
365            tx_state: MapCell::new(TxState::Idle),
366            tx_client: OptionalCell::empty(),
367            rx_state: MapCell::new(RxState::Idle),
368            rx_client: OptionalCell::empty(),
369            crypt_buf: MapCell::new(crypt_buf),
370        }
371    }
372
373    /// Sets the IEEE 802.15.4 key lookup procedure to be used.
374    pub fn set_key_procedure(&self, key_procedure: &'a dyn KeyProcedure) {
375        self.key_procedure.set(key_procedure);
376    }
377
378    /// Sets the IEEE 802.15.4 key lookup procedure to be used.
379    pub fn set_device_procedure(&self, device_procedure: &'a dyn DeviceProcedure) {
380        self.device_procedure.set(device_procedure);
381    }
382
383    /// Look up the key using the IEEE 802.15.4 KeyDescriptor lookup procedure
384    /// implemented elsewhere.
385    fn lookup_key(&self, level: SecurityLevel, key_id: KeyId) -> Option<[u8; 16]> {
386        self.key_procedure
387            .and_then(|key_procedure| key_procedure.lookup_key(level, key_id))
388    }
389
390    /// IEEE 802.15.4-2015, 9.2.1, outgoing frame security procedure
391    /// Performs the first checks in the security procedure. The rest of the
392    /// steps are performed as part of the transmission pipeline.
393    /// Returns the next `TxState` to enter.
394    fn outgoing_frame_security(&self, buf: &'static mut [u8], frame_info: FrameInfo) -> TxState {
395        // IEEE 802.15.4-2015: 9.2.1, outgoing frame security
396        // Steps a-e have already been performed in the frame preparation step,
397        // so we only need to dispatch on the security parameters in the frame info
398        match frame_info.security_params {
399            Some((level, _, _)) => {
400                if level == SecurityLevel::None {
401                    // This case should never occur if the FrameInfo was
402                    // prepared by prepare_data_frame
403                    TxState::ReadyToTransmit(frame_info, buf)
404                } else {
405                    TxState::ReadyToEncrypt(frame_info, buf)
406                }
407            }
408            None => TxState::ReadyToTransmit(frame_info, buf),
409        }
410    }
411
412    /// IEEE 802.15.4-2015, 9.2.3, incoming frame security procedure
413    fn incoming_frame_security(
414        &self,
415        buf: &'static mut [u8],
416        frame_len: usize,
417        lqi: u8,
418    ) -> RxState {
419        // Try to decode the MAC header. Three possible results can occur:
420        // 1) The frame should be dropped and the buffer returned to the radio
421        // 2) The frame is unsecured. We immediately expose the frame to the
422        //    user and queue the buffer for returning to the radio.
423        // 3) The frame needs to be unsecured.
424
425        // The buffer containing the 15.4 packet also contains the PSDU bytes and an LQI
426        // byte. We only pass the 15.4 packet up the stack and slice buf accordingly.
427        let frame_buffer = &buf[radio::PSDU_OFFSET..(buf.len() - LQI_SIZE)];
428
429        let result = Header::decode(frame_buffer, false)
430            .done()
431            .and_then(|(data_offset, (header, mac_payload_offset))| {
432                // Note: there is a complication here regarding the offsets.
433                // When the received frame has security enabled, the payload
434                // (including the payload IEs) is encrypted, and hence the data
435                // payload field includes the encrypted payload IEs too.
436                // However, when the frame is not encrypted, the data payload
437                // field does not include the payload IEs.
438                //
439                // This is fine because we re-parse the unsecured frame before
440                // exposing it to the user. At that time, the data payload field
441                // will not include the payload IEs.
442                let mic_len = header.security.map_or(0, |sec| sec.level.mic_len());
443                let data_len = frame_len - data_offset - mic_len;
444                if let Some(security) = header.security {
445                    // IEEE 802.15.4-2015: 9.2.3, incoming frame security procedure
446                    // for security-enabled headers
447                    if header.version == FrameVersion::V2003 {
448                        None
449                    } else {
450                        // Step e: Lookup the key.
451                        let key = match self.lookup_key(security.level, security.key_id) {
452                            Some(key) => key,
453                            None => {
454                                return None;
455                            }
456                        };
457
458                        // Step f: Obtain the extended source address
459                        // TODO: For Thread, when the frame's security header
460                        // specifies `KeyIdMode::Source4Index`, the source
461                        // address used for the nonce is actually a constant
462                        // defined in their spec
463                        let device_addr = match header.src_addr {
464                            Some(mac) => match mac {
465                                MacAddress::Long(val) => val,
466                                MacAddress::Short(_) => {
467                                    kernel::debug!("[15.4] DROPPED PACKET - error only short address provided on encrypted packet.");
468                                    return None
469                                },
470                            },
471                            None => {
472                                kernel::debug!("[15.4] DROPPED PACKET - Malformed, no src address provided.");
473                                return None
474                            },
475                        };
476
477                        // Step g, h: Check frame counter
478                        let frame_counter = match security.frame_counter {
479                            Some(frame_counter) => {
480                                if frame_counter == 0xffffffff {
481                                    // Counter error
482                                    return None;
483                                }
484                                // TODO: Check frame counter against source device
485                                frame_counter
486                            }
487                            // TSCH mode, where ASN is used instead, not supported
488                            None => {
489                                return None;
490                            }
491                        };
492
493                        // Compute ccm nonce
494                        let nonce = get_ccm_nonce(&device_addr, frame_counter, security.level);
495
496                        Some(FrameInfo {
497                            frame_type: header.frame_type,
498                            mac_payload_offset,
499                            data_offset,
500                            data_len,
501                            mic_len,
502                            security_params: Some((security.level, key, nonce)),
503                        })
504                    }
505                } else {
506                    // No security needed, can yield the frame immediately
507
508                    // The buffer containing the 15.4 packet also contains the PSDU bytes and an LQI
509                    // byte. We only pass the 15.4 packet up the stack and slice buf accordingly.
510                    let frame_buffer = &buf[radio::PSDU_OFFSET..(buf.len() - LQI_SIZE)];
511                    self.rx_client.map(|client| {
512                        client.receive(frame_buffer, header, lqi, data_offset, data_len);
513                    });
514                    None
515                }
516            });
517
518        match result {
519            None => {
520                // The packet was not encrypted, we completed the 15.4 framer procedure, and passed the packet to the
521                // client. We can now return the recv buffer to the radio driver and enter framer's idle state.
522                self.mac.set_receive_buffer(buf);
523                RxState::Idle
524            }
525            Some(frame_info) => RxState::ReadyToDecrypt(frame_info, buf, lqi),
526        }
527    }
528
529    /// Advances the transmission pipeline if it can be advanced.
530    fn step_transmit_state(&self) -> Result<(), (ErrorCode, &'static mut [u8])> {
531        self.tx_state.take().map_or_else(
532            || panic!("missing tx_state"),
533            |state| {
534                // This mechanism is a little more clunky, but makes it
535                // difficult to forget to replace `tx_state`.
536                let (next_state, result) = match state {
537                    TxState::Idle => (TxState::Idle, Ok(())),
538                    TxState::ReadyToEncrypt(info, buf) => {
539                        match info.security_params {
540                            None => {
541                                // `ReadyToEncrypt` should only be entered when
542                                // `security_params` is not `None`.
543                                (TxState::Idle, Err((ErrorCode::FAIL, buf)))
544                            }
545                            Some((level, key, nonce)) => {
546                                let (m_off, m_len) = info.ccm_encrypt_ranges();
547                                let (a_off, m_off) =
548                                    (radio::PSDU_OFFSET, radio::PSDU_OFFSET + m_off);
549
550                                // Crypto setup failed; fail sending packet and return to idle
551                                if self.aes_ccm.set_key(&key) != Ok(())
552                                    || self.aes_ccm.set_nonce(&nonce) != Ok(())
553                                {
554                                    (TxState::Idle, Err((ErrorCode::FAIL, buf)))
555                                } else {
556                                    let res = self.aes_ccm.crypt(
557                                        buf,
558                                        a_off,
559                                        m_off,
560                                        m_len,
561                                        info.mic_len,
562                                        level.encryption_needed(),
563                                        true,
564                                    );
565                                    match res {
566                                        Ok(()) => (TxState::Encrypting(info), Ok(())),
567                                        Err((ErrorCode::BUSY, buf)) => {
568                                            (TxState::ReadyToEncrypt(info, buf), Ok(()))
569                                        }
570                                        Err((ecode, buf)) => (TxState::Idle, Err((ecode, buf))),
571                                    }
572                                }
573                            }
574                        }
575                    }
576                    TxState::Encrypting(info) => {
577                        // This state should be advanced only by the hardware
578                        // encryption callback.
579                        (TxState::Encrypting(info), Ok(()))
580                    }
581                    TxState::ReadyToTransmit(info, buf) => {
582                        let res = self.mac.transmit(buf, info.secured_length());
583                        match res {
584                            // If the radio is busy, just wait for either a
585                            // transmit_done or config_done callback to trigger
586                            // this state transition again
587                            Err((ErrorCode::BUSY, buf)) => {
588                                (TxState::ReadyToTransmit(info, buf), Ok(()))
589                            }
590                            Ok(()) => (TxState::Idle, Ok(())),
591                            Err((ecode, buf)) => (TxState::Idle, Err((ecode, buf))),
592                        }
593                    }
594                };
595                self.tx_state.replace(next_state);
596                result
597            },
598        )
599    }
600
601    /// Advances the reception pipeline if it can be advanced.
602    fn step_receive_state(&self) {
603        self.rx_state.take().map(|state| {
604            let next_state = match state {
605                RxState::Idle => RxState::Idle,
606                RxState::ReadyToDecrypt(info, buf, lqi) => {
607                    match info.security_params {
608                        None => {
609                            // `ReadyToDecrypt` should only be entered when
610                            // `security_params` is not `None`.
611                            RxState::Idle
612                        }
613                        Some((level, key, nonce)) => {
614                            let (m_off, m_len) = info.ccm_encrypt_ranges();
615                            let (a_off, m_off) = (radio::PSDU_OFFSET, radio::PSDU_OFFSET + m_off);
616
617                            // Crypto setup failed; fail receiving packet and return to idle
618                            if self.aes_ccm.set_key(&key) != Ok(())
619                                || self.aes_ccm.set_nonce(&nonce) != Ok(())
620                            {
621                                // No error is returned for the receive function because recv occurs implicitly
622                                // Log debug statement here so that this error does not occur silently
623                                kernel::debug!(
624                                    "[15.4 RECV FAIL] - Failed setting crypto key/nonce."
625                                );
626                                self.mac.set_receive_buffer(buf);
627                                RxState::Idle
628                            } else {
629                                // The crypto operation requires multiple steps through the receiving pipeline and
630                                // an unknown quanitity of time to perform decryption. Holding the 15.4 radio's
631                                // receive buffer for this period of time is suboptimal as packets will be dropped.
632                                // The radio driver assumes the mac.set_receive_buffer(...) function is called prior
633                                // to returning from the framer. These constraints necessitate the creation of a seperate
634                                // crypto buffer for the radio framer so that the framer can return the radio driver's
635                                // receive buffer and then perform decryption using the copied packet in the crypto buffer.
636                                let res = self.crypt_buf.take().map(|mut crypt_buf| {
637                                    crypt_buf[0..buf.len()].copy_from_slice(buf);
638                                    crypt_buf.slice(0..buf.len());
639
640                                    self.aes_ccm.crypt(
641                                        crypt_buf.take(),
642                                        a_off,
643                                        m_off,
644                                        m_len,
645                                        info.mic_len,
646                                        level.encryption_needed(),
647                                        true,
648                                    )
649                                });
650
651                                // The potential scenarios include:
652                                // - (1) Successfully transfer packet to crypto buffer and succesfully begin crypto operation
653                                // - (2) Succesfully transfer packet to crypto buffer, but the crypto operation aes_ccm.crypt(...)
654                                //   is busy so we do not advance the reception pipeline and retry on the next iteration
655                                // - (3) Succesfully transfer packet to crypto buffer, but the crypto operation fails for some
656                                //   unknown reason (likely due to the crypto buffer's configuration or the offset/len parameters
657                                //   passed to the function. It is not possible to decrypt the packet so we drop the packet, return
658                                //   the radio drivers recv buffer and return the framer recv state machine to idle
659                                // - (4) The crypto buffer is empty (in use elsewhere) and we are unable to copy the received
660                                //   packet. This packet is dropped and we must return the buffer to the radio driver. This
661                                //   scenario is handled in the None case
662                                match res {
663                                    // Scenario 1
664                                    Some(Ok(())) => {
665                                        self.mac.set_receive_buffer(buf);
666                                        RxState::Decrypting(info, lqi)
667                                    }
668                                    // Scenario 2
669                                    Some(Err((ErrorCode::BUSY, buf))) => {
670                                        RxState::ReadyToDecrypt(info, buf, lqi)
671                                    }
672                                    // Scenario 3
673                                    Some(Err((_, fail_crypt_buf))) => {
674                                        self.mac.set_receive_buffer(buf);
675                                        self.crypt_buf.replace(SubSliceMut::new(fail_crypt_buf));
676                                        RxState::Idle
677                                    }
678                                    // Scenario 4
679                                    None => {
680                                        self.mac.set_receive_buffer(buf);
681                                        RxState::Idle
682                                    }
683                                }
684                            }
685                        }
686                    }
687                }
688                RxState::Decrypting(info, lqi) => {
689                    // This state should be advanced only by the hardware
690                    // encryption callback.
691                    RxState::Decrypting(info, lqi)
692                }
693                RxState::ReadyToYield(info, buf, lqi) => {
694                    // Between the secured and unsecured frames, the
695                    // unsecured frame length remains constant but the data
696                    // offsets may change due to the presence of PayloadIEs.
697                    // Hence, we can only use the unsecured length from the
698                    // frame info, but not the offsets.
699                    let frame_len = info.unsecured_length();
700                    if let Some((data_offset, (header, _))) = Header::decode(
701                        &buf[radio::PSDU_OFFSET..(radio::PSDU_OFFSET + radio::MAX_FRAME_SIZE)],
702                        true,
703                    )
704                    .done()
705                    {
706                        // IEEE 802.15.4-2015 specifies that unsecured
707                        // frames do not have auxiliary security headers,
708                        // but we do not remove the auxiliary security
709                        // header before returning the frame to the client.
710                        // This is so that it is possible to tell if the
711                        // frame was secured or unsecured, while still
712                        // always receiving the frame payload in plaintext.
713                        //
714                        // The buffer containing the 15.4 packet also contains
715                        // the PSDU bytes and an LQI byte. We only pass the
716                        // 15.4 packet up the stack and slice buf accordingly.
717                        let frame_buffer = &buf[radio::PSDU_OFFSET..(buf.len() - LQI_SIZE)];
718                        self.rx_client.map(|client| {
719                            client.receive(
720                                frame_buffer,
721                                header,
722                                lqi,
723                                data_offset,
724                                frame_len - data_offset,
725                            );
726                        });
727                        self.crypt_buf.replace(SubSliceMut::new(buf));
728                    }
729                    RxState::Idle
730                }
731            };
732            self.rx_state.replace(next_state);
733        });
734    }
735}
736
737impl<'a, M: Mac<'a>, A: AESCCM<'a, AES128>> MacDevice<'a> for Framer<'a, M, A> {
738    fn set_transmit_client(&self, client: &'a dyn TxClient) {
739        self.tx_client.set(client);
740    }
741
742    fn set_receive_client(&self, client: &'a dyn RxClient) {
743        self.rx_client.set(client);
744    }
745
746    fn get_address(&self) -> u16 {
747        self.mac.get_address()
748    }
749
750    fn get_address_long(&self) -> [u8; 8] {
751        self.mac.get_address_long()
752    }
753
754    fn get_pan(&self) -> u16 {
755        self.mac.get_pan()
756    }
757
758    fn set_address(&self, addr: u16) {
759        self.mac.set_address(addr)
760    }
761
762    fn set_address_long(&self, addr: [u8; 8]) {
763        self.mac.set_address_long(addr)
764    }
765
766    fn set_pan(&self, id: u16) {
767        self.mac.set_pan(id)
768    }
769
770    fn config_commit(&self) {
771        self.mac.config_commit()
772    }
773
774    fn is_on(&self) -> bool {
775        self.mac.is_on()
776    }
777
778    fn start(&self) -> Result<(), ErrorCode> {
779        self.mac.start()
780    }
781
782    fn prepare_data_frame(
783        &self,
784        buf: &'static mut [u8],
785        dst_pan: PanID,
786        dst_addr: MacAddress,
787        src_pan: PanID,
788        src_addr: MacAddress,
789        security_needed: Option<(SecurityLevel, KeyId)>,
790    ) -> Result<Frame, &'static mut [u8]> {
791        // IEEE 802.15.4-2015: 9.2.1, outgoing frame security
792        // Steps a-e of the security procedure are implemented here.
793
794        // TODO: For Thread, in the case of `KeyIdMode::Source4Index`, the source
795        // address should instead be some constant defined in their
796        // specification.
797
798        let security_desc = security_needed.and_then(|(level, key_id)| {
799            // To decrypt the packet, we need the long addr.
800            // Without the long addr, we are unable to proceed
801            // and return None
802            let src_addr_long = match src_addr {
803                MacAddress::Long(addr) => addr,
804                MacAddress::Short(_) => return None,
805            };
806
807            self.lookup_key(level, key_id).map(|key| {
808                // TODO: lookup frame counter for device
809                let frame_counter = 0;
810                let nonce = get_ccm_nonce(&src_addr_long, frame_counter, level);
811                (
812                    Security {
813                        level,
814                        asn_in_nonce: false,
815                        frame_counter: Some(frame_counter),
816                        key_id,
817                    },
818                    key,
819                    nonce,
820                )
821            })
822        });
823        if security_needed.is_some() && security_desc.is_none() {
824            // If security was requested, fail when desired key was not found.
825            return Err(buf);
826        }
827
828        // Construct MAC header
829        let security = security_desc.map(|(sec, _, _)| sec);
830        let mic_len = security.map_or(0, |sec| sec.level.mic_len());
831        let header = Header {
832            frame_type: FrameType::Data,
833            /* TODO: determine this by looking at queue, and also set it in
834             * hardware so that ACKs set this flag to the right value. */
835            frame_pending: false,
836            // Unicast data frames request acknowledgement
837            ack_requested: true,
838            version: FrameVersion::V2006,
839            seq: Some(self.data_sequence.get()),
840            dst_pan: Some(dst_pan),
841            dst_addr: Some(dst_addr),
842            src_pan: Some(src_pan),
843            src_addr: Some(src_addr),
844            security,
845            header_ies: Default::default(),
846            header_ies_len: 0,
847            payload_ies: Default::default(),
848            payload_ies_len: 0,
849        };
850
851        match header.encode(buf, true).done() {
852            Some((data_offset, mac_payload_offset)) => Ok(Frame {
853                buf,
854                info: FrameInfo {
855                    frame_type: FrameType::Data,
856                    mac_payload_offset,
857                    data_offset,
858                    data_len: 0,
859                    mic_len,
860                    security_params: security_desc.map(|(sec, key, nonce)| (sec.level, key, nonce)),
861                },
862            }),
863            None => Err(buf),
864        }
865    }
866
867    fn transmit(&self, frame: Frame) -> Result<(), (ErrorCode, &'static mut [u8])> {
868        let Frame { buf, info } = frame;
869        let state = match self.tx_state.take() {
870            None => {
871                return Err((ErrorCode::FAIL, buf));
872            }
873            Some(state) => state,
874        };
875        match state {
876            TxState::Idle => {
877                let next_state = self.outgoing_frame_security(buf, info);
878                self.tx_state.replace(next_state);
879                self.step_transmit_state()
880            }
881            other_state => {
882                self.tx_state.replace(other_state);
883                Err((ErrorCode::BUSY, buf))
884            }
885        }
886    }
887}
888
889impl<'a, M: Mac<'a>, A: AESCCM<'a, AES128>> radio::TxClient for Framer<'a, M, A> {
890    fn send_done(&self, buf: &'static mut [u8], acked: bool, result: Result<(), ErrorCode>) {
891        self.data_sequence.set(self.data_sequence.get() + 1);
892        self.tx_client.map(move |client| {
893            client.send_done(buf, acked, result);
894        });
895    }
896}
897
898impl<'a, M: Mac<'a>, A: AESCCM<'a, AES128>> radio::RxClient for Framer<'a, M, A> {
899    fn receive(
900        &self,
901        buf: &'static mut [u8],
902        frame_len: usize,
903        lqi: u8,
904        crc_valid: bool,
905        _: Result<(), ErrorCode>,
906    ) {
907        // Drop all frames with invalid CRC
908        if !crc_valid {
909            self.mac.set_receive_buffer(buf);
910            return;
911        }
912
913        self.rx_state.take().map(move |state| {
914            let next_state = match state {
915                RxState::Idle => {
916                    // We can start processing a new received frame only if
917                    // the reception pipeline is free
918                    self.incoming_frame_security(buf, frame_len, lqi)
919                }
920                other_state => {
921                    // This should never occur unless something other than
922                    // this MAC layer provided a receive buffer to the
923                    // radio, but if this occurs then we have no choice but
924                    // to drop the frame.
925                    self.mac.set_receive_buffer(buf);
926                    other_state
927                }
928            };
929            self.rx_state.replace(next_state);
930            self.step_receive_state()
931        });
932    }
933}
934
935impl<'a, M: Mac<'a>, A: AESCCM<'a, AES128>> radio::ConfigClient for Framer<'a, M, A> {
936    fn config_done(&self, _: Result<(), ErrorCode>) {
937        // The transmission pipeline is the only state machine that
938        // waits for the configuration procedure to complete before
939        // advancing.
940        let _ = self.step_transmit_state().map_err(|(ecode, buf)| {
941            // Return the buffer to the transmit client
942            self.tx_client.map(move |client| {
943                client.send_done(buf, false, Err(ecode));
944            });
945        });
946    }
947}
948
949impl<'a, M: Mac<'a>, A: AESCCM<'a, AES128>> CCMClient for Framer<'a, M, A> {
950    fn crypt_done(&self, buf: &'static mut [u8], res: Result<(), ErrorCode>, tag_is_valid: bool) {
951        let mut tx_waiting = false;
952        let mut rx_waiting = false;
953
954        // The crypto operation was from the transmission pipeline.
955        let opt_buf = if let Some(state) = self.tx_state.take() {
956            match state {
957                TxState::Encrypting(info) => {
958                    let res2 = match res {
959                        Err(ecode) => {
960                            self.tx_state.replace(TxState::Idle);
961                            Err((ecode, buf))
962                        }
963                        Ok(()) => {
964                            self.tx_state.replace(TxState::ReadyToTransmit(info, buf));
965                            self.step_transmit_state()
966                        }
967                    };
968
969                    if let Err((ecode, buf)) = res2 {
970                        // Abort the transmission process. Return the buffer to the client.
971                        self.tx_client.map(move |client| {
972                            client.send_done(buf, false, Err(ecode));
973                        });
974                    }
975                    None
976                }
977                other_state => {
978                    tx_waiting = match other_state {
979                        TxState::ReadyToEncrypt(_, _) => true,
980                        _ => false,
981                    };
982                    self.tx_state.replace(other_state);
983                    Some(buf)
984                }
985            }
986        } else {
987            Some(buf)
988        };
989
990        // The crypto operation was from the reception pipeline.
991        if let Some(buf) = opt_buf {
992            self.rx_state.take().map(|state| {
993                match state {
994                    RxState::Decrypting(info, lqi) => {
995                        let next_state = if tag_is_valid {
996                            RxState::ReadyToYield(info, buf, lqi)
997                        } else {
998                            // The CRC tag is invalid, meaning the packet was corrupted. Drop this packet
999                            // and reset reception pipeline
1000                            self.crypt_buf.replace(SubSliceMut::new(buf));
1001                            RxState::Idle
1002                        };
1003                        self.rx_state.replace(next_state);
1004                        self.step_receive_state()
1005                    }
1006                    other_state => {
1007                        rx_waiting = match other_state {
1008                            RxState::ReadyToDecrypt(_, _, _) => true,
1009                            _ => false,
1010                        };
1011                        self.rx_state.replace(other_state);
1012                    }
1013                }
1014            });
1015        }
1016
1017        // Now trigger the next crypto operation if one exists.
1018        if tx_waiting {
1019            let _ = self.step_transmit_state().map_err(|(ecode, buf)| {
1020                // Return the buffer to the client.
1021                self.tx_client.map(move |client| {
1022                    client.send_done(buf, false, Err(ecode));
1023                });
1024            });
1025        } else if rx_waiting {
1026            self.step_receive_state()
1027        }
1028    }
1029}