Skip to main content

capsules_extra/symmetric_encryption/
aes.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//! AES.
6
7use capsules_core::driver;
8/// Syscall driver number.
9pub const DRIVER_NUM: usize = driver::NUM::Aes as usize;
10
11use core::cell::Cell;
12use core::marker::PhantomData;
13
14use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
15use kernel::hil::symmetric_encryption::{
16    AES, AESCBC, AESCCM, AESCtr, AESECB, AESGCM, AESKeySize, CCMClient, Client, GCMClient,
17};
18use kernel::processbuffer::{ReadableProcessBuffer, WriteableProcessBuffer};
19use kernel::syscall::{CommandReturn, SyscallDriver};
20use kernel::utilities::cells::{OptionalCell, TakeCell};
21use kernel::{ErrorCode, ProcessId};
22
23/// Ids for read-only allow buffers
24mod ro_allow {
25    pub const KEY: usize = 0;
26    pub const IV: usize = 1;
27    pub const SOURCE: usize = 2;
28    /// The number of allow buffers the kernel stores for this grant
29    pub const COUNT: u8 = 3;
30}
31
32/// Ids for read-write allow buffers
33mod rw_allow {
34    pub const DEST: usize = 0;
35    /// The number of allow buffers the kernel stores for this grant
36    pub const COUNT: u8 = 1;
37}
38
39pub struct AesDriver<'a, A, K>
40where
41    K: AESKeySize,
42    A: AES<'a, K> + AESCCM<'static, K> + AESGCM<'static, K>,
43{
44    aes: &'a A,
45
46    active: Cell<bool>,
47
48    apps: Grant<
49        App,
50        UpcallCount<1>,
51        AllowRoCount<{ ro_allow::COUNT }>,
52        AllowRwCount<{ rw_allow::COUNT }>,
53    >,
54    processid: OptionalCell<ProcessId>,
55
56    source_buffer: TakeCell<'static, [u8]>,
57    data_copied: Cell<usize>,
58    dest_buffer: TakeCell<'static, [u8]>,
59    _phantom: PhantomData<K>,
60}
61
62impl<
63    K: AESKeySize,
64    A: AES<'static, K> + AESCtr + AESCBC + AESECB + AESCCM<'static, K> + AESGCM<'static, K>,
65> AesDriver<'static, A, K>
66{
67    pub fn new(
68        aes: &'static A,
69        source_buffer: &'static mut [u8],
70        dest_buffer: &'static mut [u8],
71        grant: Grant<
72            App,
73            UpcallCount<1>,
74            AllowRoCount<{ ro_allow::COUNT }>,
75            AllowRwCount<{ rw_allow::COUNT }>,
76        >,
77    ) -> AesDriver<'static, A, K> {
78        AesDriver {
79            aes,
80            active: Cell::new(false),
81            apps: grant,
82            processid: OptionalCell::empty(),
83            source_buffer: TakeCell::new(source_buffer),
84            data_copied: Cell::new(0),
85            dest_buffer: TakeCell::new(dest_buffer),
86
87            _phantom: PhantomData::<K>,
88        }
89    }
90
91    fn run(&self) -> Result<(), ErrorCode> {
92        self.processid.map_or(Err(ErrorCode::RESERVE), |processid| {
93            self.apps
94                .enter(processid, |app, kernel_data| {
95                    self.aes.enable();
96                    match app.aes_operation {
97                        Some(AesOperation::AESCtr(encrypt)) => self.aes.set_mode_aesctr(encrypt)?,
98                        Some(AesOperation::AESCBC(encrypt)) => self.aes.set_mode_aescbc(encrypt)?,
99                        Some(AesOperation::AESECB(encrypt)) => self.aes.set_mode_aesecb(encrypt)?,
100                        Some(AesOperation::AESCCM(_encrypt)) => {}
101                        Some(AesOperation::AESGCM(_encrypt)) => {}
102                        _ => return Err(ErrorCode::INVAL),
103                    }
104
105                    kernel_data
106                        .get_readonly_processbuffer(ro_allow::KEY)
107                        .and_then(|key| {
108                            key.enter(|key| {
109                                let mut static_buffer_len = 0;
110                                self.source_buffer.map_or(Err(ErrorCode::NOMEM), |buf| {
111                                    // Determine the size of the static buffer we have
112                                    static_buffer_len = buf.len();
113
114                                    if static_buffer_len > key.len() {
115                                        static_buffer_len = key.len()
116                                    }
117
118                                    // Copy the data into the static buffer
119                                    key[..static_buffer_len]
120                                        .copy_to_slice(&mut buf[..static_buffer_len]);
121
122                                    if let Some(op) = app.aes_operation.as_ref() {
123                                        match op {
124                                            AesOperation::AESCtr(_)
125                                            | AesOperation::AESCBC(_)
126                                            | AesOperation::AESECB(_) => {
127                                                AES::set_key(self.aes, &buf[..static_buffer_len])?;
128                                                Ok(())
129                                            }
130                                            AesOperation::AESCCM(_) => {
131                                                AESCCM::set_key(
132                                                    self.aes,
133                                                    &buf[..static_buffer_len],
134                                                )?;
135                                                Ok(())
136                                            }
137                                            AesOperation::AESGCM(_) => {
138                                                AESGCM::set_key(
139                                                    self.aes,
140                                                    &buf[..static_buffer_len],
141                                                )?;
142                                                Ok(())
143                                            }
144                                        }
145                                    } else {
146                                        Err(ErrorCode::FAIL)
147                                    }
148                                })
149                            })
150                        })
151                        .unwrap_or(Err(ErrorCode::RESERVE))?;
152
153                    kernel_data
154                        .get_readonly_processbuffer(ro_allow::IV)
155                        .and_then(|iv| {
156                            iv.enter(|iv| {
157                                let mut static_buffer_len = 0;
158                                self.source_buffer.map_or(Err(ErrorCode::NOMEM), |buf| {
159                                    // Determine the size of the static buffer we have
160                                    static_buffer_len = buf.len();
161
162                                    if static_buffer_len > iv.len() {
163                                        static_buffer_len = iv.len()
164                                    }
165
166                                    // Copy the data into the static buffer
167                                    iv[..static_buffer_len]
168                                        .copy_to_slice(&mut buf[..static_buffer_len]);
169
170                                    if let Some(op) = app.aes_operation.as_ref() {
171                                        match op {
172                                            AesOperation::AESCtr(_)
173                                            | AesOperation::AESCBC(_)
174                                            | AesOperation::AESECB(_) => {
175                                                AES::set_iv(self.aes, &buf[..static_buffer_len])?;
176                                                Ok(())
177                                            }
178                                            AesOperation::AESCCM(_) => {
179                                                AESCCM::set_nonce(self.aes, &buf[0..13])?;
180                                                Ok(())
181                                            }
182                                            AesOperation::AESGCM(_) => {
183                                                AESGCM::set_iv(self.aes, &buf[0..12])?;
184                                                Ok(())
185                                            }
186                                        }
187                                    } else {
188                                        Err(ErrorCode::FAIL)
189                                    }
190                                })
191                            })
192                        })
193                        .unwrap_or(Err(ErrorCode::RESERVE))?;
194
195                    kernel_data
196                        .get_readonly_processbuffer(ro_allow::SOURCE)
197                        .and_then(|source| {
198                            source.enter(|source| {
199                                let mut static_buffer_len = 0;
200
201                                if let Some(op) = app.aes_operation.as_ref() {
202                                    match op {
203                                        AesOperation::AESCtr(_)
204                                        | AesOperation::AESCBC(_)
205                                        | AesOperation::AESECB(_) => {
206                                            self.source_buffer.map_or(
207                                                Err(ErrorCode::NOMEM),
208                                                |buf| {
209                                                    // Determine the size of the static buffer we have
210                                                    static_buffer_len = buf.len();
211
212                                                    if static_buffer_len > source.len() {
213                                                        static_buffer_len = source.len()
214                                                    }
215
216                                                    // Copy the data into the static buffer
217                                                    source[..static_buffer_len].copy_to_slice(
218                                                        &mut buf[..static_buffer_len],
219                                                    );
220
221                                                    self.data_copied.set(static_buffer_len);
222
223                                                    Ok(())
224                                                },
225                                            )?;
226                                        }
227                                        AesOperation::AESCCM(_) => {
228                                            self.dest_buffer.map_or(
229                                                Err(ErrorCode::NOMEM),
230                                                |buf| {
231                                                    // Determine the size of the static buffer we have
232                                                    static_buffer_len = buf.len();
233
234                                                    if static_buffer_len > source.len() {
235                                                        static_buffer_len = source.len()
236                                                    }
237
238                                                    // Copy the data into the static buffer
239                                                    source[..static_buffer_len].copy_to_slice(
240                                                        &mut buf[..static_buffer_len],
241                                                    );
242
243                                                    self.data_copied.set(static_buffer_len);
244
245                                                    Ok(())
246                                                },
247                                            )?;
248                                        }
249                                        AesOperation::AESGCM(_) => {
250                                            self.dest_buffer.map_or(
251                                                Err(ErrorCode::NOMEM),
252                                                |buf| {
253                                                    // Determine the size of the static buffer we have
254                                                    static_buffer_len = buf.len();
255
256                                                    if static_buffer_len > source.len() {
257                                                        static_buffer_len = source.len()
258                                                    }
259
260                                                    // Copy the data into the static buffer
261                                                    source[..static_buffer_len].copy_to_slice(
262                                                        &mut buf[..static_buffer_len],
263                                                    );
264
265                                                    self.data_copied.set(static_buffer_len);
266
267                                                    Ok(())
268                                                },
269                                            )?;
270                                        }
271                                    }
272
273                                    self.calculate_output(
274                                        op,
275                                        app.aoff.get(),
276                                        app.moff.get(),
277                                        app.mlen.get(),
278                                        app.mic_len.get(),
279                                        app.confidential.get(),
280                                    )?;
281                                    Ok(())
282                                } else {
283                                    Err(ErrorCode::FAIL)
284                                }
285                            })
286                        })
287                        .unwrap_or(Err(ErrorCode::RESERVE))?;
288
289                    Ok(())
290                })
291                .unwrap_or_else(|err| Err(err.into()))
292        })
293    }
294
295    fn calculate_output(
296        &self,
297        op: &AesOperation,
298        aoff: usize,
299        moff: usize,
300        mlen: usize,
301        mic_len: usize,
302        confidential: bool,
303    ) -> Result<(), ErrorCode> {
304        match op {
305            AesOperation::AESCtr(_) | AesOperation::AESCBC(_) | AesOperation::AESECB(_) => {
306                if let Some(dest_buf) = self.dest_buffer.take() {
307                    // The HIL requires the source to span exactly start..stop.
308                    let len = self.source_buffer.map_or(0, |buf| buf.len());
309                    if let Some((e, source, dest)) =
310                        AES::crypt(self.aes, self.source_buffer.take(), dest_buf, 0, len)
311                    {
312                        // Error, clear the processid and data
313                        self.aes.disable();
314                        self.processid.clear();
315                        if let Some(source_buf) = source {
316                            self.source_buffer.replace(source_buf);
317                        }
318                        self.dest_buffer.replace(dest);
319
320                        return e;
321                    }
322                } else {
323                    return Err(ErrorCode::FAIL);
324                }
325            }
326            AesOperation::AESCCM(encrypting) => {
327                if let Some(buf) = self.dest_buffer.take() {
328                    if let Err((e, dest)) = AESCCM::crypt(
329                        self.aes,
330                        buf,
331                        aoff,
332                        moff,
333                        mlen,
334                        mic_len,
335                        confidential,
336                        *encrypting,
337                    ) {
338                        // Error, clear the processid and data
339                        self.aes.disable();
340                        self.processid.clear();
341                        self.dest_buffer.replace(dest);
342
343                        return Err(e);
344                    }
345                } else {
346                    return Err(ErrorCode::FAIL);
347                }
348            }
349            AesOperation::AESGCM(encrypting) => {
350                if let Some(buf) = self.dest_buffer.take() {
351                    if let Err((e, dest)) =
352                        AESGCM::crypt(self.aes, buf, aoff, moff, mlen, mic_len, *encrypting)
353                    {
354                        // Error, clear the appid and data
355                        self.aes.disable();
356                        self.processid.clear();
357                        self.dest_buffer.replace(dest);
358
359                        return Err(e);
360                    }
361                } else {
362                    return Err(ErrorCode::FAIL);
363                }
364            }
365        }
366
367        Ok(())
368    }
369
370    fn check_queue(&self) {
371        for appiter in self.apps.iter() {
372            // If an app is already running let it complete
373            if self.processid.is_some() {
374                break;
375            }
376
377            // If this app has a pending command let's use it.
378            if let Some(processid) = appiter.enter(|app, _| app.pending_run_app.take()) {
379                // Mark this driver as being in use.
380                self.processid.set(processid);
381                // Actually make the buzz happen.
382                if let Err(e) = self.run() {
383                    self.aes.disable();
384                    self.processid.clear();
385                    let _ = self.apps.enter(processid, |_, kernel_data| {
386                        kernel_data.schedule_upcall(0, (e as usize, 0, 0))
387                    });
388                }
389            }
390        }
391    }
392}
393
394impl<
395    K: AESKeySize,
396    A: AES<'static, K> + AESCtr + AESCBC + AESECB + AESCCM<'static, K> + AESGCM<'static, K>,
397> Client<'static> for AesDriver<'static, A, K>
398{
399    fn crypt_done(&self, source: Option<&'static mut [u8]>, destination: &'static mut [u8]) {
400        if let Some(source_buf) = source {
401            self.source_buffer.replace(source_buf);
402        }
403        self.dest_buffer.replace(destination);
404
405        self.processid.map(|id| {
406            self.apps
407                .enter(id, |app, kernel_data| {
408                    let mut data_len = 0;
409                    let mut exit = false;
410                    let mut static_buffer_len = 0;
411
412                    let source_len = kernel_data
413                        .get_readonly_processbuffer(ro_allow::SOURCE)
414                        .map_or(0, |source| source.len());
415
416                    let subtract = self
417                        .source_buffer
418                        .map_or(0, |buf| core::cmp::min(buf.len(), source_len));
419
420                    self.dest_buffer.map(|buf| {
421                        let ret = kernel_data
422                            .get_readwrite_processbuffer(rw_allow::DEST)
423                            .and_then(|dest| {
424                                dest.mut_enter(|dest| {
425                                    let offset = self.data_copied.get() - subtract;
426                                    let app_len = dest.len();
427                                    let static_len = self.source_buffer.map_or(0, |source_buf| {
428                                        core::cmp::min(source_buf.len(), buf.len())
429                                    });
430
431                                    if app_len < static_len {
432                                        if app_len - offset > 0 {
433                                            dest[offset..app_len]
434                                                .copy_from_slice(&buf[0..(app_len - offset)]);
435                                        }
436                                    } else {
437                                        if offset + static_len <= app_len {
438                                            dest[offset..(offset + static_len)]
439                                                .copy_from_slice(&buf[0..static_len]);
440                                        }
441                                    }
442                                })
443                            });
444
445                        if let Err(e) = ret {
446                            // No data buffer, clear the processid and data
447                            self.aes.disable();
448                            self.processid.clear();
449                            let _ = kernel_data.schedule_upcall(0, (e as usize, 0, 0));
450                            exit = true;
451                        }
452                    });
453
454                    if exit {
455                        return;
456                    }
457
458                    self.source_buffer.map(|buf| {
459                        let ret = kernel_data
460                            .get_readonly_processbuffer(ro_allow::SOURCE)
461                            .and_then(|source| {
462                                source.enter(|source| {
463                                    // Determine the size of the static buffer we have
464                                    static_buffer_len = buf.len();
465                                    // Determine how much data we have already copied
466                                    let copied_data = self.data_copied.get();
467
468                                    data_len = source.len();
469
470                                    if data_len > copied_data {
471                                        let remaining_data = &source[copied_data..];
472                                        let remaining_len = data_len - copied_data;
473
474                                        if remaining_len < static_buffer_len {
475                                            remaining_data.copy_to_slice(&mut buf[..remaining_len]);
476                                        } else {
477                                            remaining_data[..static_buffer_len].copy_to_slice(buf);
478                                        }
479                                    }
480                                    Ok(())
481                                })
482                            })
483                            .unwrap_or(Err(ErrorCode::RESERVE));
484
485                        if let Err(e) = ret {
486                            // No data buffer, clear the processid and data
487                            self.aes.disable();
488                            self.processid.clear();
489                            let _ = kernel_data.schedule_upcall(0, (e as usize, 0, 0));
490                            exit = true;
491                        }
492                    });
493
494                    if exit {
495                        return;
496                    }
497
498                    if static_buffer_len > 0 {
499                        let copied_data = self.data_copied.get();
500
501                        if data_len > copied_data {
502                            // Update the amount of data copied
503                            self.data_copied.set(copied_data + static_buffer_len);
504
505                            if let Some(op) = app.aes_operation.as_ref() {
506                                if let Err(e) = self.calculate_output(
507                                    op,
508                                    app.aoff.get(),
509                                    app.moff.get(),
510                                    app.mlen.get(),
511                                    app.mic_len.get(),
512                                    app.confidential.get(),
513                                ) {
514                                    // Error, clear the processid and data
515                                    self.aes.disable();
516                                    self.processid.clear();
517                                    let _ = kernel_data.schedule_upcall(0, (e as usize, 0, 0));
518                                    return;
519                                }
520                            }
521
522                            // Return as we don't want to run the digest yet
523                            return;
524                        }
525                    }
526
527                    // If we get here we have finished all the crypto operations
528                    let _ = kernel_data.schedule_upcall(0, (0, self.data_copied.get(), 0));
529                    self.data_copied.set(0);
530                })
531                .map_err(|err| {
532                    if err == kernel::process::Error::NoSuchApp
533                        || err == kernel::process::Error::InactiveApp
534                    {
535                        self.processid.clear();
536                    }
537                })
538        });
539    }
540}
541
542impl<
543    K: AESKeySize,
544    A: AES<'static, K> + AESCtr + AESCBC + AESECB + AESCCM<'static, K> + AESGCM<'static, K>,
545> CCMClient for AesDriver<'static, A, K>
546{
547    fn crypt_done(&self, buf: &'static mut [u8], res: Result<(), ErrorCode>, tag_is_valid: bool) {
548        self.dest_buffer.replace(buf);
549
550        self.processid.map(|id| {
551            self.apps
552                .enter(id, |_, kernel_data| {
553                    let mut exit = false;
554
555                    if let Err(e) = res {
556                        let _ = kernel_data.schedule_upcall(0, (e as usize, 0, 0));
557                        return;
558                    }
559
560                    self.dest_buffer.map(|buf| {
561                        let ret = kernel_data
562                            .get_readwrite_processbuffer(rw_allow::DEST)
563                            .and_then(|dest| {
564                                dest.mut_enter(|dest| {
565                                    // One-shot operation: the result starts at offset 0.
566                                    let len = core::cmp::min(buf.len(), dest.len());
567                                    dest[..len].copy_from_slice(&buf[..len]);
568                                })
569                            });
570
571                        if let Err(e) = ret {
572                            // No data buffer, clear the processid and data
573                            self.aes.disable();
574                            self.processid.clear();
575                            let _ = kernel_data.schedule_upcall(0, (e as usize, 0, 0));
576                            exit = true;
577                        }
578                    });
579
580                    if exit {
581                        return;
582                    }
583
584                    // AES CCM is online only we can't send any more data in, so
585                    // just report what we did to the app.
586                    let _ = kernel_data
587                        .schedule_upcall(0, (0, self.data_copied.get(), tag_is_valid as usize));
588                    self.data_copied.set(0);
589                })
590                .map_err(|err| {
591                    if err == kernel::process::Error::NoSuchApp
592                        || err == kernel::process::Error::InactiveApp
593                    {
594                        self.processid.clear();
595                    }
596                })
597        });
598    }
599}
600
601impl<
602    K: AESKeySize,
603    A: AES<'static, K> + AESCtr + AESCBC + AESECB + AESCCM<'static, K> + AESGCM<'static, K>,
604> GCMClient for AesDriver<'static, A, K>
605{
606    fn crypt_done(&self, buf: &'static mut [u8], res: Result<(), ErrorCode>, tag_is_valid: bool) {
607        self.dest_buffer.replace(buf);
608
609        self.processid.map(|id| {
610            self.apps
611                .enter(id, |_, kernel_data| {
612                    let mut exit = false;
613
614                    if let Err(e) = res {
615                        let _ = kernel_data.schedule_upcall(0, (e as usize, 0, 0));
616                        return;
617                    }
618
619                    self.dest_buffer.map(|buf| {
620                        let ret = kernel_data
621                            .get_readwrite_processbuffer(rw_allow::DEST)
622                            .and_then(|dest| {
623                                dest.mut_enter(|dest| {
624                                    // One-shot operation: the result starts at offset 0.
625                                    let len = core::cmp::min(buf.len(), dest.len());
626                                    dest[..len].copy_from_slice(&buf[..len]);
627                                })
628                            });
629
630                        if let Err(e) = ret {
631                            // No data buffer, clear the appid and data
632                            self.aes.disable();
633                            self.processid.clear();
634                            let _ = kernel_data.schedule_upcall(0, (e as usize, 0, 0));
635                            exit = true;
636                        }
637                    });
638
639                    if exit {
640                        return;
641                    }
642
643                    // AES GCM is online only we can't send any more data in, so
644                    // just report what we did to the app.
645                    let _ = kernel_data
646                        .schedule_upcall(0, (0, self.data_copied.get(), tag_is_valid as usize));
647                    self.data_copied.set(0);
648                })
649                .map_err(|err| {
650                    if err == kernel::process::Error::NoSuchApp
651                        || err == kernel::process::Error::InactiveApp
652                    {
653                        self.processid.clear();
654                    }
655                })
656        });
657    }
658}
659
660impl<
661    K: AESKeySize,
662    A: AES<'static, K> + AESCtr + AESCBC + AESECB + AESCCM<'static, K> + AESGCM<'static, K>,
663> SyscallDriver for AesDriver<'static, A, K>
664{
665    fn command(
666        &self,
667        command_num: usize,
668        data1: usize,
669        data2: usize,
670        processid: ProcessId,
671    ) -> CommandReturn {
672        let match_or_empty_or_nonexistant = self.processid.map_or(true, |owning_app| {
673            // We have recorded that an app has ownership of the HMAC.
674
675            // If the HMAC is still active, then we need to wait for the operation
676            // to finish and the app, whether it exists or not (it may have crashed),
677            // still owns this capsule. If the HMAC is not active, then
678            // we need to verify that that application still exists, and remove
679            // it as owner if not.
680            if self.active.get() {
681                owning_app == processid
682            } else {
683                // Check the app still exists.
684                //
685                // If the `.enter()` succeeds, then the app is still valid, and
686                // we can check if the owning app matches the one that called
687                // the command. If the `.enter()` fails, then the owning app no
688                // longer exists and we return `true` to signify the
689                // "or_nonexistant" case.
690                self.apps
691                    .enter(owning_app, |_, _| owning_app == processid)
692                    .unwrap_or(true)
693            }
694        });
695
696        let app_match = self.processid.map_or(false, |owning_app| {
697            // We have recorded that an app has ownership of the HMAC.
698
699            // If the HMAC is still active, then we need to wait for the operation
700            // to finish and the app, whether it exists or not (it may have crashed),
701            // still owns this capsule. If the HMAC is not active, then
702            // we need to verify that that application still exists, and remove
703            // it as owner if not.
704            if self.active.get() {
705                owning_app == processid
706            } else {
707                // Check the app still exists.
708                //
709                // If the `.enter()` succeeds, then the app is still valid, and
710                // we can check if the owning app matches the one that called
711                // the command. If the `.enter()` fails, then the owning app no
712                // longer exists and we return `true` to signify the
713                // "or_nonexistant" case.
714                self.apps
715                    .enter(owning_app, |_, _| owning_app == processid)
716                    .unwrap_or(true)
717            }
718        });
719
720        // Try the commands where we want to start an operation *not* entered in
721        // an app grant first.
722        if match_or_empty_or_nonexistant && command_num == 2 {
723            self.processid.set(processid);
724            let ret = self.run();
725
726            return if let Err(e) = ret {
727                self.aes.disable();
728                self.processid.clear();
729                self.check_queue();
730                CommandReturn::failure(e)
731            } else {
732                CommandReturn::success()
733            };
734        }
735
736        let ret = self
737            .apps
738            .enter(processid, |app, kernel_data| {
739                match command_num {
740                    // check if present
741                    0 => CommandReturn::success(),
742
743                    // set_algorithm
744                    1 => match data1 {
745                        0 => {
746                            app.aes_operation = Some(AesOperation::AESCtr(data2 != 0));
747                            CommandReturn::success()
748                        }
749                        1 => {
750                            app.aes_operation = Some(AesOperation::AESCBC(data2 != 0));
751                            CommandReturn::success()
752                        }
753                        2 => {
754                            app.aes_operation = Some(AesOperation::AESECB(data2 != 0));
755                            CommandReturn::success()
756                        }
757                        3 => {
758                            app.aes_operation = Some(AesOperation::AESCCM(data2 != 0));
759                            CommandReturn::success()
760                        }
761                        4 => {
762                            app.aes_operation = Some(AesOperation::AESGCM(data2 != 0));
763                            CommandReturn::success()
764                        }
765                        _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
766                    },
767
768                    // setup
769                    // Copy in the key and IV and run the first encryption operation
770                    // This will trigger a callback
771                    2 => {
772                        // Some app is using the storage, we must wait.
773                        if app.pending_run_app.is_some() {
774                            // No more room in the queue, nowhere to store this
775                            // request.
776                            CommandReturn::failure(ErrorCode::NOMEM)
777                        } else {
778                            // We can store this, so lets do it.
779                            app.pending_run_app = Some(processid);
780                            CommandReturn::success()
781                        }
782                    }
783
784                    // crypt
785                    // Generate the encrypted output
786                    // Multiple calls to crypt will re-use the existing state
787                    // This will trigger a callback
788                    3 => {
789                        if app_match {
790                            if let Err(e) = kernel_data
791                                .get_readonly_processbuffer(ro_allow::SOURCE)
792                                .and_then(|source| {
793                                    source.enter(|source| {
794                                        let mut static_buffer_len = 0;
795                                        self.source_buffer.map_or(
796                                            Err(ErrorCode::NOMEM),
797                                            |buf| {
798                                                // Determine the size of the static buffer we have
799                                                static_buffer_len = buf.len();
800
801                                                if static_buffer_len > source.len() {
802                                                    static_buffer_len = source.len()
803                                                }
804
805                                                // Copy the data into the static buffer
806                                                source[..static_buffer_len]
807                                                    .copy_to_slice(&mut buf[..static_buffer_len]);
808
809                                                self.data_copied.set(static_buffer_len);
810
811                                                Ok(())
812                                            },
813                                        )?;
814
815                                        if let Some(op) = app.aes_operation.as_ref() {
816                                            self.calculate_output(
817                                                op,
818                                                app.aoff.get(),
819                                                app.moff.get(),
820                                                app.mlen.get(),
821                                                app.mic_len.get(),
822                                                app.confidential.get(),
823                                            )?;
824                                            Ok(())
825                                        } else {
826                                            Err(ErrorCode::FAIL)
827                                        }
828                                    })
829                                })
830                                .unwrap_or(Err(ErrorCode::RESERVE))
831                            {
832                                let _ = kernel_data.schedule_upcall(
833                                    0,
834                                    (kernel::errorcode::into_statuscode(e.into()), 0, 0),
835                                );
836                            }
837                            CommandReturn::success()
838                        } else {
839                            // We don't queue this request, the user has to call
840                            // `setup` first.
841                            CommandReturn::failure(ErrorCode::OFF)
842                        }
843                    }
844
845                    // Finish
846                    // Complete the operation and reset the AES
847                    // This will not trigger a callback and will not process any data from userspace
848                    4 => {
849                        if app_match {
850                            self.aes.disable();
851                            self.processid.clear();
852
853                            CommandReturn::success()
854                        } else {
855                            // We don't queue this request, the user has to call
856                            // `setup` first.
857                            CommandReturn::failure(ErrorCode::OFF)
858                        }
859                    }
860
861                    // Set aoff for CCM
862                    // This will not trigger a callback and will not process any data from userspace
863                    5 => {
864                        app.aoff.set(data1);
865                        CommandReturn::success()
866                    }
867
868                    // Set moff for CCM
869                    // This will not trigger a callback and will not process any data from userspace
870                    6 => {
871                        app.moff.set(data1);
872                        CommandReturn::success()
873                    }
874
875                    // Set mic_len for CCM
876                    // This will not trigger a callback and will not process any data from userspace
877                    7 => {
878                        app.mic_len.set(data1);
879                        CommandReturn::success()
880                    }
881
882                    // Set confidential boolean for CCM
883                    // This will not trigger a callback and will not process any data from userspace
884                    8 => {
885                        app.confidential.set(data1 > 0);
886                        CommandReturn::success()
887                    }
888
889                    // Set mlen for CCM and GCM
890                    // This will not trigger a callback and will not process any data from userspace
891                    9 => {
892                        app.mlen.set(data1);
893                        CommandReturn::success()
894                    }
895
896                    // default
897                    _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
898                }
899            })
900            .unwrap_or_else(|err| err.into());
901
902        if command_num == 4
903            || command_num == 5
904            || command_num == 6
905            || command_num == 7
906            || command_num == 8
907            || command_num == 9
908        {
909            self.check_queue();
910        }
911
912        ret
913    }
914
915    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
916        self.apps.enter(processid, |_, _| {})
917    }
918}
919
920enum AesOperation {
921    AESCtr(bool),
922    AESCBC(bool),
923    AESECB(bool),
924    AESCCM(bool),
925    AESGCM(bool),
926}
927
928#[derive(Default)]
929pub struct App {
930    pending_run_app: Option<ProcessId>,
931    aes_operation: Option<AesOperation>,
932
933    aoff: Cell<usize>,
934    moff: Cell<usize>,
935    mlen: Cell<usize>,
936    mic_len: Cell<usize>,
937    confidential: Cell<bool>,
938}