Skip to main content

capsules_core/virtualizers/
virtual_aes_ccm.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 and virtualizes AES-CCM* encryption/decryption/authentication using an underlying
6//! AES-CBC and AES-CTR implementation.
7//!
8//! IEEE 802.15.4-2015: Appendix B.4.1, CCM* transformations. CCM* is
9//! defined so that both encryption and decryption can be done by preparing two
10//! fields: the AuthData and either the PlaintextData or the CiphertextData.
11//! Then, two passes of AES are performed with one block of overlap.
12//!
13//! ```text
14//! crypt_buf: [ -------- AuthData -------- | -------- PData/CData -------- ]
15//! aes_cbc:    \__________________________/
16//! aes_ctr:                        \ 1 blk | _____________________________/
17//! ```
18//!
19//! The overlapping block is then the encrypted authentication tag U. For
20//! encryption, we append U to the data as a message integrity code (MIC).
21//! For decryption, we compare U with the provided MIC.
22//
23//! This is true only if data confidentiality is not needed. If it is, then
24//! the AuthData includes the PlaintextData. At encryption, we perform CBC over
25//! both fields, then copy the last block to just before the PData. Then,
26//! CTR mode is performed over the same overlapping region, forming the encrypted
27//! authentication tag U.
28//!
29//! ```text
30//! crypt_buf: [ -------- AuthData -------- | -------- PData/CData -------- ]
31//! aes_cbc:    \__________________________________________________________/
32//! aes_ctr:                        \ 1 blk | _____________________________/
33//! ```
34//!
35//! At decryption, there is no choice but the reverse the order of operations.
36//! First, we zero out the overlapping block and perform ctr over it and the
37//! PlaintextData. This produces Enc(Key, A_i), which we save in saved_tag.
38//! Then, we restore the previous value of the last block of AuthData and re-pad
39//! PlaintextData before running CBC over both fields. The last step is to
40//! combine saved_tag and the unencrypted tag to form the encrypted tag and
41//! verify its correctness.
42//!
43//! Usage
44//! -----
45//!
46//! ```rust,ignore
47//! # use capsules_core::test::aes_ccm::Test;
48//! # use capsules_core::virtual_aes_ccm;
49//! # use kernel::common::deferred_call::DeferredCallClient;
50//! # use kernel::hil::symmetric_encryption::{AES, AES128, AESCCM, AES_BLOCK_SIZE};
51//! # use kernel::static_init;
52//! # use sam4l::aes::{Aes, AES};
53//! type AESCCMMUX = virtual_aes_ccm::MuxAES128CCM<'static, Aes<'static>>;
54//! type AESCCMCLIENT = virtual_aes_ccm::VirtualAES128CCM<'static, AESCCMMUX>;
55//! // mux
56//! let ccm_mux = static_init!(AESCCMMUX, virtual_aes_ccm::MuxAES128CCM::new(&AES));
57//! ccm_mux.register();
58//! AES.set_client(ccm_mux);
59//! const CRYPT_SIZE: usize = 7 * AES_BLOCK_SIZE;
60//! let crypt_buf1 = static_init!([u8; CRYPT_SIZE], [0x00; CRYPT_SIZE]);
61//! let ccm_client1 = static_init!(
62//!     AESCCMCLIENT,
63//!     virtual_aes_ccm::VirtualAES128CCM::new(ccm_mux, crypt_buf1)
64//! );
65//! ccm_client1.setup();
66//! let data1 = static_init!([u8; 4 * AES_BLOCK_SIZE], [0x00; 4 * AES_BLOCK_SIZE]);
67//! let t1 = static_init!(Test<'static, AESCCMCLIENT>, Test::new(ccm_client1, data1));
68//! ccm_client1.set_client(t1);
69//! let crypt_buf2 = static_init!([u8; CRYPT_SIZE], [0x00; CRYPT_SIZE]);
70//! let ccm_client2 = static_init!(
71//!     AESCCMCLIENT,
72//!     virtual_aes_ccm::VirtualAES128CCM::new(ccm_mux, crypt_buf2)
73//! );
74//! ccm_client2.setup();
75//! let data2 = static_init!([u8; 4 * AES_BLOCK_SIZE], [0x00; 4 * AES_BLOCK_SIZE]);
76//! let t2 = static_init!(Test<'static, AESCCMCLIENT>, Test::new(ccm_client2, data2));
77//! ccm_client2.set_client(t2);
78//! t1.run();
79//! t2.run();
80//!
81//! ```
82
83use core::cell::Cell;
84
85use kernel::ErrorCode;
86use kernel::collections::list::{List, ListLink, ListNode};
87use kernel::debug;
88use kernel::deferred_call::{DeferredCall, DeferredCallClient};
89use kernel::hil::symmetric_encryption;
90use kernel::hil::symmetric_encryption::{
91    AES, AES_BLOCK_SIZE, AES128, AES128_KEY_SIZE, AESCBC, AESCtr, AESECB, CCM_NONCE_LENGTH,
92};
93use kernel::utilities::cells::{OptionalCell, TakeCell};
94
95use crate::stream::SResult;
96use crate::stream::{encode_bytes, encode_u16};
97
98#[derive(Copy, Clone, Eq, PartialEq, Debug)]
99enum CCMState {
100    Idle,
101    Auth,
102    Encrypt,
103}
104
105// to cache up the function parameters of the crypt() function
106struct CryptFunctionParameters {
107    buf: &'static mut [u8],
108    a_off: usize,
109    m_off: usize,
110    m_len: usize,
111    mic_len: usize,
112    confidential: bool,
113    encrypting: bool,
114}
115
116impl CryptFunctionParameters {
117    pub fn new(
118        buf: &'static mut [u8],
119        a_off: usize,
120        m_off: usize,
121        m_len: usize,
122        mic_len: usize,
123        confidential: bool,
124        encrypting: bool,
125    ) -> CryptFunctionParameters {
126        CryptFunctionParameters {
127            buf,
128            a_off,
129            m_off,
130            m_len,
131            mic_len,
132            confidential,
133            encrypting,
134        }
135    }
136}
137
138pub struct MuxAES128CCM<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> {
139    aes: &'a A,
140    client: OptionalCell<&'a dyn symmetric_encryption::Client<'a>>,
141    ccm_clients: List<'a, VirtualAES128CCM<'a, A>>,
142    inflight: OptionalCell<&'a VirtualAES128CCM<'a, A>>,
143    deferred_call: DeferredCall,
144}
145
146impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> MuxAES128CCM<'a, A> {
147    pub fn new(aes: &'a A) -> Self {
148        aes.enable(); // enable the hardware, in case it's forgotten elsewhere
149        Self {
150            aes,
151            client: OptionalCell::empty(),
152            ccm_clients: List::new(),
153            inflight: OptionalCell::empty(),
154            deferred_call: DeferredCall::new(),
155        }
156    }
157
158    /// Asynchronously executes the next operation, if any. Used by calls
159    /// to trigger do_next_op such that it will execute after the call
160    /// returns.
161    /// See virtual_uart::MuxUart<'a>::do_next_op_async
162    fn do_next_op_async(&self) {
163        self.deferred_call.set();
164    }
165
166    fn do_next_op(&self) {
167        if self.inflight.is_none() {
168            let mnode = self
169                .ccm_clients
170                .iter()
171                .find(|node| node.queued_up.is_some());
172            mnode.map(|node| {
173                self.inflight.set(node);
174                let parameters: CryptFunctionParameters = node.queued_up.take().unwrap();
175                // now, eat the parameters
176                let _ = node.crypt_r(parameters).map_err(|(ecode, _)| {
177                    // notice that we didn't put the parameters back...
178                    // because it's already eaten
179                    if node.ccm_client.is_none() {
180                        debug!("virtual_aes_ccm: no ccm_client is registered in VirtualAES128CCM");
181                    }
182                    if node.buf.is_none() {
183                        debug!("virtual_aes_ccm: no buffer is binded with VirtualAES128CCM");
184                    }
185                    // notify the client that there's a failure
186                    node.buf.take().map(|buf| {
187                        node.ccm_client.map(move |client| {
188                            client.crypt_done(buf, Err(ecode), false);
189                        });
190                    });
191                    // if it fails to trigger encryption, remove it and perform the next
192                    node.remove_from_queue();
193                    self.do_next_op();
194                });
195                // otherwise, wait for crypt_done
196            });
197        }
198    }
199}
200
201impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> DeferredCallClient for MuxAES128CCM<'a, A> {
202    fn handle_deferred_call(&self) {
203        self.do_next_op();
204    }
205
206    fn register(&'static self) {
207        self.deferred_call.register(self);
208    }
209}
210
211impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> symmetric_encryption::Client<'a>
212    for MuxAES128CCM<'a, A>
213{
214    fn crypt_done(&'a self, source: Option<&'static mut [u8]>, dest: &'static mut [u8]) {
215        if self.inflight.is_none() {
216            self.client.map(move |client| {
217                client.crypt_done(source, dest);
218            });
219            return;
220        }
221        self.inflight.map(move |vaes_ccm| {
222            // vaes_ccm.crypt_done might call additional start_ccm_crypt / start_ccm_auth
223            // when the encryption is *really* done, inflight will be cleared by remove_from_queue
224            // and it will call do_next_op to perform the next operation
225            // self.do_next_op() will be called when the encryption is failed or is really done
226            // search for self.ccm_client
227            vaes_ccm.crypt_done(source, dest);
228        });
229    }
230}
231
232pub struct VirtualAES128CCM<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> {
233    mux: &'a MuxAES128CCM<'a, A>,
234    aes: &'a A,
235    next: ListLink<'a, VirtualAES128CCM<'a, A>>,
236
237    crypt_buf: TakeCell<'static, [u8]>,
238    crypt_auth_len: Cell<usize>,
239    crypt_enc_len: Cell<usize>,
240    ccm_client: OptionalCell<&'a dyn symmetric_encryption::CCMClient>,
241
242    state: Cell<CCMState>,
243    confidential: Cell<bool>,
244    encrypting: Cell<bool>,
245
246    buf: TakeCell<'static, [u8]>,
247    pos: Cell<(usize, usize, usize, usize)>,
248    key: Cell<[u8; AES128_KEY_SIZE]>,
249    nonce: Cell<[u8; CCM_NONCE_LENGTH]>,
250    saved_tag: Cell<[u8; AES_BLOCK_SIZE]>,
251    queued_up: OptionalCell<CryptFunctionParameters>,
252}
253
254impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> VirtualAES128CCM<'a, A> {
255    pub fn new(
256        mux: &'a MuxAES128CCM<'a, A>,
257        crypt_buf: &'static mut [u8],
258    ) -> VirtualAES128CCM<'a, A> {
259        VirtualAES128CCM {
260            mux,
261            aes: mux.aes,
262            next: ListLink::empty(),
263            crypt_buf: TakeCell::new(crypt_buf),
264            crypt_auth_len: Cell::new(0),
265            crypt_enc_len: Cell::new(0),
266            ccm_client: OptionalCell::empty(),
267            state: Cell::new(CCMState::Idle),
268            confidential: Cell::new(false),
269            encrypting: Cell::new(false),
270            buf: TakeCell::empty(),
271            pos: Cell::new((0, 0, 0, 0)),
272            key: Cell::new(Default::default()),
273            nonce: Cell::new(Default::default()),
274            saved_tag: Cell::new(Default::default()),
275            queued_up: OptionalCell::empty(),
276        }
277    }
278
279    /// bind itself to self.mux, should be called after static_init!
280    pub fn setup(&'a self) {
281        self.mux.ccm_clients.push_head(self);
282    }
283
284    /// Prepares crypt_buf with the input for the CCM* authentication and
285    /// encryption/decryption transformations. Returns NOMEM if crypt_buf is
286    /// not present or if it is not long enough.
287    fn prepare_ccm_buffer(
288        &self,
289        nonce: &[u8; CCM_NONCE_LENGTH],
290        mic_len: usize,
291        a_data: &[u8],
292        m_data: &[u8],
293    ) -> Result<(), ErrorCode> {
294        self.crypt_buf.map_or(Err(ErrorCode::NOMEM), |cbuf| {
295            let (auth_len, enc_len) =
296                match Self::encode_ccm_buffer(cbuf, nonce, mic_len, a_data, m_data) {
297                    SResult::Done(_, out) => out,
298                    SResult::Needed(_) => {
299                        return Err(ErrorCode::NOMEM);
300                    }
301                    SResult::Error(()) => {
302                        return Err(ErrorCode::FAIL);
303                    }
304                };
305            // debug!("auth: ({})", auth_len);
306            // for i in 0..auth_len {
307            //     debug!("{:02x}", cbuf[i]);
308            // }
309            // debug!("enc: ({})", enc_len);
310            // for i in auth_len..enc_len {
311            //     debug!("{:02x}", cbuf[i]);
312            // }
313
314            self.crypt_auth_len.set(auth_len);
315            self.crypt_enc_len.set(enc_len);
316            Ok(())
317        })
318    }
319
320    /// This function encodes AuthData (a_data) and PData/CData (m_data) into a
321    /// buffer, along with the prerequisite metadata/padding bytes. On success,
322    /// `auth_len` (the length of the AuthData field) and `enc_len` (the
323    /// combined length of AuthData and PData/CData) are returned. `auth_len` is
324    /// guaranteed to be >= AES_BLOCK_SIZE
325    fn encode_ccm_buffer(
326        buf: &mut [u8],
327        nonce: &[u8; CCM_NONCE_LENGTH],
328        mic_len: usize,
329        a_data: &[u8],
330        m_data: &[u8],
331    ) -> SResult<(usize, usize)> {
332        // IEEE 802.15.4-2015: Appendix B.4.1.2, CCM* authentication
333        // The authentication tag T is computed with AES128-CBC-MAC on
334        // B_0 | AuthData, where
335        //   B_0 = Flags (1 byte) | nonce (13 bytes) | m length (2 bytes)
336        //   Flags = 0 | A data present? (1 bit) | M (3 bits) | L (3 bits)
337        //   AuthData = AddAuthData | PlaintextData
338        //   AddAuthData = L(a) (encoding of a_data.len()) | a_data
339        //   PlaintextData = m_data
340        //   Both AddAuthData and PlaintextData are 0-padded to 16-byte blocks.
341        // The following code places B_0 | AuthData into crypt_buf.
342
343        // flags = reserved | Adata | (M - 2) / 2 | (L - 1)
344        let mut flags: u8 = 0;
345        if a_data.len() != 0 {
346            flags |= 1 << 6;
347        }
348        if mic_len != 0 {
349            flags |= (((mic_len - 2) / 2) as u8) << 3;
350        }
351        flags |= 1;
352
353        stream_len_cond!(buf, AES_BLOCK_SIZE);
354        // The first block is flags | nonce | m length
355        buf[0] = flags;
356        buf[1..14].copy_from_slice(nonce.as_ref());
357        let mut off = enc_consume!(buf, 14; encode_u16,
358                                            (m_data.len() as u16).to_le());
359
360        // After that comes L(a) | a, where L(a) is the following
361        // encoding of a_len:
362        if a_data.len() == 0 {
363            // L(a) is empty, and the Adata flag is zero
364        } else if a_data.len() < 0xff00_usize {
365            // L(a) is l(a) in 2 bytes of little-endian
366            off = enc_consume!(buf, off; encode_u16,
367                                         (a_data.len() as u16).to_le());
368        } else {
369            // These length encoding branches are defined in the specification
370            // but should never be reached because our MTU is 127.
371            stream_err!(());
372        }
373
374        // Append the auth data and 0-pad to a multiple of 16 bytes
375        off = enc_consume!(buf, off; encode_bytes, a_data);
376        let auth_len = off.div_ceil(AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
377        stream_len_cond!(buf, auth_len);
378        buf[off..auth_len].iter_mut().for_each(|b| *b = 0);
379        off = auth_len;
380
381        // Append plaintext data and 0-pad to a multiple of 16 bytes
382        off = enc_consume!(buf, off; encode_bytes, m_data);
383        let enc_len = off.div_ceil(AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
384        stream_len_cond!(buf, enc_len);
385        buf[off..enc_len].iter_mut().for_each(|b| *b = 0);
386        off = enc_len;
387
388        stream_done!(off, (auth_len, enc_len));
389    }
390
391    fn reversed(&self) -> bool {
392        self.confidential.get() && !self.encrypting.get()
393    }
394
395    // Assumes that the state is Idle, which means that crypt_buf must be
396    // present. Panics if this is not the case.
397    fn start_ccm_auth(&self) -> Result<(), ErrorCode> {
398        if !(self.state.get() == CCMState::Idle)
399            && !(self.state.get() == CCMState::Encrypt && self.reversed())
400        {
401            panic!("Called start_ccm_auth when not idle");
402        }
403
404        // We are performing CBC-MAC, so always encrypting.
405        self.aes.set_mode_aescbc(true)?;
406
407        let iv = [0u8; AES_BLOCK_SIZE];
408        let res = self.aes.set_iv(&iv);
409        if res != Ok(()) {
410            return res;
411        }
412        let res = self.aes.set_key(&self.key.get());
413        if res != Ok(()) {
414            return res;
415        }
416
417        let crypt_buf = match self.crypt_buf.take() {
418            None => panic!("Cannot perform CCM* auth because crypt_buf is not present."),
419            Some(buf) => buf,
420        };
421
422        // If confidentiality is needed, authenticate over message data.
423        let auth_end = if self.confidential.get() {
424            self.crypt_enc_len.get()
425        } else {
426            self.crypt_auth_len.get()
427        };
428
429        self.aes.start_message();
430        match self.aes.crypt(None, crypt_buf, 0, auth_end) {
431            None => {
432                self.state.set(CCMState::Auth);
433                Ok(())
434            }
435            Some((res, _, crypt_buf)) => {
436                // Request failed
437                self.crypt_buf.replace(crypt_buf);
438                res
439            }
440        }
441    }
442
443    fn start_ccm_encrypt(&self) -> Result<(), ErrorCode> {
444        if !(self.state.get() == CCMState::Auth)
445            && !(self.state.get() == CCMState::Idle && self.reversed())
446        {
447            return Err(ErrorCode::FAIL);
448        }
449        self.state.set(CCMState::Idle); // default to fail
450
451        // debug!("after auth:");
452        // self.crypt_buf.map(|buf| {
453        //     for i in 0..self.crypt_auth_len.get() {
454        //         debug!("{:02x}", buf[i]);
455        //     }
456        // });
457
458        self.aes.set_mode_aesctr(self.encrypting.get())?;
459
460        let res = self.aes.set_key(&self.key.get());
461        if res != Ok(()) {
462            return res;
463        }
464
465        let mut iv = [0u8; AES_BLOCK_SIZE];
466        // flags = reserved | reserved | 0 | (L - 1)
467        // Since L = 2, flags = 1.
468        iv[0] = 1;
469        iv[1..1 + CCM_NONCE_LENGTH].copy_from_slice(&self.nonce.get());
470        let res = self.aes.set_iv(&iv);
471        if res != Ok(()) {
472            return res;
473        }
474
475        self.aes.start_message();
476        let crypt_buf = match self.crypt_buf.take() {
477            None => panic!("Cannot perform CCM* encrypt because crypt_buf is not present."),
478            Some(buf) => buf,
479        };
480
481        match self.aes.crypt(
482            None,
483            crypt_buf,
484            self.crypt_auth_len.get() - AES_BLOCK_SIZE,
485            self.crypt_enc_len.get(),
486        ) {
487            None => {
488                self.state.set(CCMState::Encrypt);
489                Ok(())
490            }
491            Some((res, _, crypt_buf)) => {
492                self.crypt_buf.replace(crypt_buf);
493                res
494            }
495        }
496    }
497
498    fn end_ccm(&self) {
499        let tag_valid = self.buf.map_or(false, |buf| {
500            self.crypt_buf.map_or_else(
501                || {
502                    panic!("We lost track of crypt_buf!");
503                },
504                |cbuf| {
505                    // Copy the encrypted/decrypted message data
506                    let (_, m_off, m_len, mic_len) = self.pos.get();
507                    let auth_len = self.crypt_auth_len.get();
508                    buf[m_off..m_off + m_len].copy_from_slice(&cbuf[auth_len..auth_len + m_len]);
509
510                    let m_end = m_off + m_len;
511                    let tag_off = auth_len - AES_BLOCK_SIZE;
512                    if self.encrypting.get() {
513                        // Copy the encrypted tag to the end of the message
514                        buf[m_end..m_end + mic_len]
515                            .copy_from_slice(&cbuf[tag_off..tag_off + mic_len]);
516                        true
517                    } else {
518                        // Compare the computed encrypted tag to the received
519                        // encrypted tag
520                        buf[m_end..m_end + mic_len]
521                            .iter()
522                            .zip(cbuf[tag_off..tag_off + mic_len].iter())
523                            .all(|(a, b)| *a == *b)
524                    }
525                },
526            )
527        });
528        // encryption is successful
529        self.state.set(CCMState::Idle);
530        self.remove_from_queue();
531        self.mux.do_next_op();
532        self.ccm_client.map(|client| {
533            self.buf.take().map(|buf| {
534                client.crypt_done(buf, Ok(()), tag_valid);
535            });
536        });
537    }
538
539    fn reverse_end_ccm(&self) {
540        // Finalize CCM process only in the case where we did CTR before CBC
541        let tag_valid = self.buf.map_or(false, |buf| {
542            self.crypt_buf.map_or_else(
543                || {
544                    panic!("We lost track of crypt_buf!");
545                },
546                |cbuf| {
547                    let (_, m_off, m_len, mic_len) = self.pos.get();
548
549                    // Combine unencrypted tag at end of crypt_buf with saved
550                    // CTR-encrypted block to obtain encrypted tag
551                    let tag_off = self.crypt_enc_len.get() - AES_BLOCK_SIZE;
552                    self.saved_tag.get()[..mic_len]
553                        .iter()
554                        .zip(cbuf[tag_off..tag_off + mic_len].iter_mut())
555                        .for_each(|(a, b)| *b ^= *a);
556
557                    // Compare the computed encrypted tag to the received
558                    // encrypted tag
559                    buf[m_off + m_len..m_off + m_len + mic_len]
560                        .iter()
561                        .zip(cbuf[tag_off..tag_off + mic_len].iter())
562                        .all(|(a, b)| *a == *b)
563                },
564            )
565        });
566        // encryption is successful
567        self.state.set(CCMState::Idle);
568        self.remove_from_queue();
569        self.mux.do_next_op();
570        self.ccm_client.map(|client| {
571            self.buf.take().map(|buf| {
572                client.crypt_done(buf, Ok(()), tag_valid);
573            });
574        });
575    }
576
577    fn save_tag_block(&self) {
578        // Copies [auth_len - AES_BLOCK_SIZE..auth_len] to saved_tag
579        // and zeroes it out
580        let auth_len = self.crypt_auth_len.get();
581        self.crypt_buf.map(|cbuf| {
582            let mut cbuf_block = [0u8; AES_BLOCK_SIZE];
583            cbuf_block.copy_from_slice(&cbuf[auth_len - AES_BLOCK_SIZE..auth_len]);
584            self.saved_tag.set(cbuf_block);
585            cbuf[auth_len - AES_BLOCK_SIZE..auth_len]
586                .iter_mut()
587                .for_each(|b| *b = 0);
588        });
589    }
590
591    fn swap_tag_block(&self) {
592        // Swaps [auth_len - AES_BLOCK_SIZE..auth_len] with
593        // the value in saved_tag
594        let auth_len = self.crypt_auth_len.get();
595        self.crypt_buf.map(|cbuf| {
596            let mut cbuf_block = [0u8; AES_BLOCK_SIZE];
597            cbuf_block.copy_from_slice(&cbuf[auth_len - AES_BLOCK_SIZE..auth_len]);
598            cbuf[auth_len - AES_BLOCK_SIZE..auth_len].copy_from_slice(&self.saved_tag.get());
599            self.saved_tag.set(cbuf_block);
600        });
601    }
602
603    fn crypt_r(
604        &self,
605        parameter: CryptFunctionParameters,
606    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
607        // just expanding the parameters......
608        let buf: &'static mut [u8] = parameter.buf;
609        let a_off: usize = parameter.a_off;
610        let m_off: usize = parameter.m_off;
611        let m_len: usize = parameter.m_len;
612        let mic_len: usize = parameter.mic_len;
613        let confidential: bool = parameter.confidential;
614        let encrypting: bool = parameter.encrypting;
615        //
616        if self.state.get() != CCMState::Idle {
617            return Err((ErrorCode::BUSY, buf));
618        }
619        if !(a_off <= m_off && m_off + m_len + mic_len <= buf.len()) {
620            return Err((ErrorCode::INVAL, buf));
621        }
622
623        self.confidential.set(confidential);
624        self.encrypting.set(encrypting);
625
626        let res = self.prepare_ccm_buffer(
627            &self.nonce.get(),
628            mic_len,
629            &buf[a_off..m_off],
630            &buf[m_off..m_off + m_len],
631        );
632        if res != Ok(()) {
633            return Err((res.unwrap_err(), buf));
634        }
635
636        let res = if !confidential || encrypting {
637            // Perform CBC before CTR
638            self.start_ccm_auth()
639        } else {
640            // Perform CTR before CBC
641            self.save_tag_block();
642            self.start_ccm_encrypt()
643        };
644
645        if res != Ok(()) {
646            Err((res.unwrap_err(), buf))
647        } else {
648            self.buf.replace(buf);
649            self.pos.set((a_off, m_off, m_len, mic_len));
650            Ok(())
651        }
652    }
653
654    fn remove_from_queue(&self) {
655        self.queued_up.clear();
656        self.mux.inflight.clear();
657    }
658}
659
660impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> symmetric_encryption::AESCCM<'a, AES128>
661    for VirtualAES128CCM<'a, A>
662{
663    fn set_client(&self, client: &'a dyn symmetric_encryption::CCMClient) {
664        self.ccm_client.set(client);
665    }
666
667    fn set_key(&self, key: &[u8]) -> Result<(), ErrorCode> {
668        if key.len() != AES128_KEY_SIZE {
669            Err(ErrorCode::INVAL)
670        } else {
671            let mut new_key = [0u8; AES128_KEY_SIZE];
672            new_key.copy_from_slice(key);
673            self.key.set(new_key);
674            Ok(())
675        }
676    }
677
678    fn set_nonce(&self, nonce: &[u8]) -> Result<(), ErrorCode> {
679        if nonce.len() != CCM_NONCE_LENGTH {
680            Err(ErrorCode::INVAL)
681        } else {
682            let mut new_nonce = [0u8; CCM_NONCE_LENGTH];
683            new_nonce.copy_from_slice(nonce);
684            self.nonce.set(new_nonce);
685            Ok(())
686        }
687    }
688    /// Try to begin the encryption/decryption process
689    fn crypt(
690        &self,
691        buf: &'static mut [u8],
692        a_off: usize,
693        m_off: usize,
694        m_len: usize,
695        mic_len: usize,
696        confidential: bool,
697        encrypting: bool,
698    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
699        if self.queued_up.is_some() {
700            return Err((ErrorCode::BUSY, buf));
701        }
702        if self.state.get() != CCMState::Idle {
703            return Err((ErrorCode::BUSY, buf));
704        }
705        if !(a_off <= m_off && m_off + m_len + mic_len <= buf.len()) {
706            return Err((ErrorCode::INVAL, buf));
707        }
708
709        self.queued_up.set(CryptFunctionParameters::new(
710            buf,
711            a_off,
712            m_off,
713            m_len,
714            mic_len,
715            confidential,
716            encrypting,
717        ));
718        self.mux.do_next_op_async();
719        Ok(())
720    }
721}
722
723impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> symmetric_encryption::AES<'a, AES128>
724    for VirtualAES128CCM<'a, A>
725{
726    fn enable(&self) {
727        self.aes.enable();
728    }
729
730    fn disable(&self) {
731        self.aes.disable();
732    }
733
734    fn set_client(&'a self, client: &'a dyn symmetric_encryption::Client<'a>) {
735        self.mux.client.set(client);
736    }
737
738    fn set_key(&self, key: &[u8]) -> Result<(), ErrorCode> {
739        if self.mux.inflight.is_none() {
740            self.mux.aes.set_key(key)
741        } else {
742            Err(ErrorCode::BUSY)
743        }
744    }
745
746    fn set_iv(&self, iv: &[u8]) -> Result<(), ErrorCode> {
747        if self.mux.inflight.is_none() {
748            self.mux.aes.set_iv(iv)
749        } else {
750            Err(ErrorCode::BUSY)
751        }
752    }
753
754    fn start_message(&self) {
755        if self.mux.inflight.is_none() {
756            self.mux.aes.start_message()
757        }
758    }
759
760    fn crypt(
761        &self,
762        source: Option<&'static mut [u8]>,
763        dest: &'static mut [u8],
764        start_index: usize,
765        stop_index: usize,
766    ) -> Option<(
767        Result<(), ErrorCode>,
768        Option<&'static mut [u8]>,
769        &'static mut [u8],
770    )> {
771        if self.mux.inflight.is_none() {
772            self.mux.aes.crypt(source, dest, start_index, stop_index)
773        } else {
774            Some((Err(ErrorCode::BUSY), source, dest))
775        }
776    }
777}
778
779impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> AESCtr for VirtualAES128CCM<'a, A> {
780    fn set_mode_aesctr(&self, encrypting: bool) -> Result<(), ErrorCode> {
781        if self.mux.inflight.is_none() {
782            self.mux.aes.set_mode_aesctr(encrypting)
783        } else {
784            Err(ErrorCode::BUSY)
785        }
786    }
787}
788
789impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> AESECB for VirtualAES128CCM<'a, A> {
790    fn set_mode_aesecb(&self, encrypting: bool) -> Result<(), ErrorCode> {
791        if self.mux.inflight.is_none() {
792            self.mux.aes.set_mode_aesecb(encrypting)
793        } else {
794            Err(ErrorCode::BUSY)
795        }
796    }
797}
798
799impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> AESCBC for VirtualAES128CCM<'a, A> {
800    fn set_mode_aescbc(&self, encrypting: bool) -> Result<(), ErrorCode> {
801        if self.mux.inflight.is_none() {
802            self.mux.aes.set_mode_aescbc(encrypting)
803        } else {
804            Err(ErrorCode::BUSY)
805        }
806    }
807}
808
809impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> symmetric_encryption::Client<'a>
810    for VirtualAES128CCM<'a, A>
811{
812    fn crypt_done(&self, _: Option<&'static mut [u8]>, crypt_buf: &'static mut [u8]) {
813        self.crypt_buf.replace(crypt_buf);
814        match self.state.get() {
815            CCMState::Idle => {}
816            CCMState::Auth => {
817                if !self.reversed() {
818                    if self.confidential.get() {
819                        let (_, m_off, m_len, _) = self.pos.get();
820                        let auth_len = self.crypt_auth_len.get();
821                        let enc_len = self.crypt_enc_len.get();
822                        self.crypt_buf.map(|cbuf| {
823                            // If we authenticated over the plaintext, copy the last
824                            // block over to the beginning again so that it becomes
825                            // the encrypted tag after ctr mode
826                            let auth_last = auth_len - AES_BLOCK_SIZE;
827                            let enc_last = enc_len - AES_BLOCK_SIZE;
828                            for i in 0..AES_BLOCK_SIZE {
829                                cbuf[auth_last + i] = cbuf[enc_last + i];
830                            }
831
832                            // Then repopulate the plaintext data field
833                            self.buf.map(|buf| {
834                                cbuf[auth_len..auth_len + m_len]
835                                    .copy_from_slice(&buf[m_off..m_off + m_len]);
836                            });
837                            cbuf[auth_len + m_len..enc_len]
838                                .iter_mut()
839                                .for_each(|b| *b = 0);
840                        });
841                    }
842
843                    let res = self.start_ccm_encrypt();
844                    if res != Ok(()) {
845                        // The operation fails, immediately remove the request and perform the next operation
846                        self.state.set(CCMState::Idle);
847                        self.remove_from_queue();
848                        self.mux.do_next_op();
849
850                        // Return client buffer to client
851                        self.buf.take().map(|buf| {
852                            self.ccm_client.map(move |client| {
853                                client.crypt_done(buf, res, false);
854                            });
855                        });
856                    }
857                } else {
858                    self.reverse_end_ccm();
859                }
860            }
861            CCMState::Encrypt => {
862                if !self.reversed() {
863                    self.end_ccm();
864                } else {
865                    self.swap_tag_block();
866                    self.crypt_buf.map(|cbuf| {
867                        // Copy the encrypted/decrypted message data
868                        let (_, m_off, m_len, _) = self.pos.get();
869                        let auth_len = self.crypt_auth_len.get();
870                        self.buf.map(|buf| {
871                            buf[m_off..m_off + m_len]
872                                .copy_from_slice(&cbuf[auth_len..auth_len + m_len]);
873                        });
874
875                        // Reset the rest of the padding
876                        cbuf[self.crypt_auth_len.get() + m_len..self.crypt_enc_len.get()]
877                            .iter_mut()
878                            .for_each(|b| *b = 0);
879                    });
880                    let res = self.start_ccm_auth();
881                    if res != Ok(()) {
882                        // Return client buffer to ccm_clients
883                        self.buf.take().map(|buf| {
884                            self.ccm_client.map(move |client| {
885                                client.crypt_done(buf, res, false);
886                            });
887                        });
888                        // The operation fails, immediately remove the request and perform the next operation
889                        self.state.set(CCMState::Idle);
890                        self.remove_from_queue();
891                        self.mux.do_next_op();
892                    }
893                }
894            }
895        }
896    }
897}
898
899// Fit in the linked list
900impl<'a, A: AES<'a, AES128> + AESCtr + AESCBC + AESECB> ListNode<'a, VirtualAES128CCM<'a, A>>
901    for VirtualAES128CCM<'a, A>
902{
903    fn next(&'a self) -> &'a ListLink<'a, VirtualAES128CCM<'a, A>> {
904        &self.next
905    }
906}