Skip to main content

capsules_extra/
hmac.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//! HMAC (Hash-based Message Authentication Code).
6//!
7//! Usage
8//! -----
9//!
10//! ```rust,ignore
11//! let hmac = &earlgrey::hmac::HMAC;
12//!
13//! let mux_hmac = static_init!(MuxHmac<'static, lowrisc::hmac::Hmac>, MuxHmac::new(hmac));
14//! digest::Digest::set_client(&earlgrey::hmac::HMAC, mux_hmac);
15//!
16//! let virtual_hmac_user = static_init!(
17//!     VirtualMuxHmac<'static, lowrisc::hmac::Hmac>,
18//!     VirtualMuxHmac::new(mux_hmac)
19//! );
20//! let hmac = static_init!(
21//!     capsules::hmac::HmacDriver<'static, VirtualMuxHmac<'static, lowrisc::hmac::Hmac>>,
22//!     capsules::hmac::HmacDriver::new(
23//!         virtual_hmac_user,
24//!         board_kernel.create_grant(&memory_allocation_cap),
25//!     )
26//! );
27//! digest::Digest::set_client(virtual_hmac_user, hmac);
28//! ```
29
30use capsules_core::driver;
31use kernel::errorcode::into_statuscode;
32/// Syscall driver number.
33pub const DRIVER_NUM: usize = driver::NUM::Hmac as usize;
34
35/// Ids for read-only allow buffers
36mod ro_allow {
37    pub const KEY: usize = 0;
38    pub const DATA: usize = 1;
39    pub const COMPARE: usize = 2;
40    /// The number of allow buffers the kernel stores for this grant
41    pub const COUNT: u8 = 3;
42}
43
44/// Ids for read-write allow buffers
45mod rw_allow {
46    pub const DEST: usize = 2;
47    /// The number of allow buffers the kernel stores for this grant
48    pub const COUNT: u8 = 3;
49}
50
51use core::cell::Cell;
52
53use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
54use kernel::hil::digest;
55use kernel::processbuffer::{ReadableProcessBuffer, WriteableProcessBuffer};
56use kernel::syscall::{CommandReturn, SyscallDriver};
57use kernel::utilities::cells::{OptionalCell, TakeCell};
58use kernel::utilities::leasable_buffer::SubSlice;
59use kernel::utilities::leasable_buffer::SubSliceMut;
60use kernel::{ErrorCode, ProcessId};
61
62enum ShaOperation {
63    Md5,
64    Sha1,
65    Sha224,
66    Sha256,
67    Sha384,
68    Sha512,
69}
70
71// Temporary buffer to copy the keys from userspace into
72//
73// Needs to be able to accommodate the largest key sizes, e.g. 512
74const TMP_KEY_BUFFER_SIZE: usize = 512 / 8;
75
76pub struct HmacDriver<'a, H: digest::Digest<'a, DIGEST_LEN>, const DIGEST_LEN: usize> {
77    hmac: &'a H,
78
79    active: Cell<bool>,
80
81    apps: Grant<
82        App,
83        UpcallCount<1>,
84        AllowRoCount<{ ro_allow::COUNT }>,
85        AllowRwCount<{ rw_allow::COUNT }>,
86    >,
87    processid: OptionalCell<ProcessId>,
88
89    data_buffer: TakeCell<'static, [u8]>,
90    data_copied: Cell<usize>,
91    dest_buffer: TakeCell<'static, [u8; DIGEST_LEN]>,
92}
93
94impl<
95    'a,
96    H: digest::Digest<'a, DIGEST_LEN>
97        + digest::HmacMd5
98        + digest::HmacSha1
99        + digest::HmacSha224
100        + digest::HmacSha256
101        + digest::HmacSha384
102        + digest::HmacSha512,
103    const DIGEST_LEN: usize,
104> HmacDriver<'a, H, DIGEST_LEN>
105{
106    pub fn new(
107        hmac: &'a H,
108        data_buffer: &'static mut [u8],
109        dest_buffer: &'static mut [u8; DIGEST_LEN],
110        grant: Grant<
111            App,
112            UpcallCount<1>,
113            AllowRoCount<{ ro_allow::COUNT }>,
114            AllowRwCount<{ rw_allow::COUNT }>,
115        >,
116    ) -> HmacDriver<'a, H, DIGEST_LEN> {
117        HmacDriver {
118            hmac,
119            active: Cell::new(false),
120            apps: grant,
121            processid: OptionalCell::empty(),
122            data_buffer: TakeCell::new(data_buffer),
123            data_copied: Cell::new(0),
124            dest_buffer: TakeCell::new(dest_buffer),
125        }
126    }
127
128    fn run(&self) -> Result<(), ErrorCode> {
129        self.processid.map_or(Err(ErrorCode::RESERVE), |processid| {
130            self.apps
131                .enter(processid, |app, kernel_data| {
132                    kernel_data
133                        .get_readonly_processbuffer(ro_allow::KEY)
134                        .and_then(|key| {
135                            key.enter(|k| {
136                                if let Some(op) = &app.sha_operation {
137                                    let mut tmp_key_buffer: [u8; TMP_KEY_BUFFER_SIZE] =
138                                        [0; TMP_KEY_BUFFER_SIZE];
139                                    let key_len = core::cmp::min(k.len(), TMP_KEY_BUFFER_SIZE);
140
141                                    k[..key_len].copy_to_slice(&mut tmp_key_buffer[..key_len]);
142
143                                    match op {
144                                        ShaOperation::Md5 => {
145                                            self.hmac.set_mode_hmacmd5(&tmp_key_buffer[..key_len])
146                                        }
147                                        ShaOperation::Sha1 => {
148                                            self.hmac.set_mode_hmacsha1(&tmp_key_buffer[..key_len])
149                                        }
150                                        ShaOperation::Sha224 => self
151                                            .hmac
152                                            .set_mode_hmacsha224(&tmp_key_buffer[..key_len]),
153                                        ShaOperation::Sha256 => self
154                                            .hmac
155                                            .set_mode_hmacsha256(&tmp_key_buffer[..key_len]),
156                                        ShaOperation::Sha384 => self
157                                            .hmac
158                                            .set_mode_hmacsha384(&tmp_key_buffer[..key_len]),
159                                        ShaOperation::Sha512 => self
160                                            .hmac
161                                            .set_mode_hmacsha512(&tmp_key_buffer[..key_len]),
162                                    }
163                                } else {
164                                    Err(ErrorCode::INVAL)
165                                }
166                            })
167                        })
168                        .unwrap_or(Err(ErrorCode::RESERVE))?;
169
170                    kernel_data
171                        .get_readonly_processbuffer(ro_allow::DATA)
172                        .and_then(|data| {
173                            data.enter(|data| {
174                                let mut static_buffer_len = 0;
175                                self.data_buffer.map(|buf| {
176                                    // Determine the size of the static buffer we have
177                                    static_buffer_len = buf.len();
178
179                                    if static_buffer_len > data.len() {
180                                        static_buffer_len = data.len()
181                                    }
182
183                                    self.data_copied.set(static_buffer_len);
184
185                                    // Copy the data into the static buffer
186                                    data[..static_buffer_len]
187                                        .copy_to_slice(&mut buf[..static_buffer_len]);
188                                });
189
190                                // Add the data from the static buffer to the HMAC
191                                let mut lease_buf = SubSliceMut::new(
192                                    self.data_buffer.take().ok_or(ErrorCode::RESERVE)?,
193                                );
194                                lease_buf.slice(0..static_buffer_len);
195                                if let Err(e) = self.hmac.add_mut_data(lease_buf) {
196                                    self.data_buffer.replace(e.1.take());
197                                    return Err(e.0);
198                                }
199                                Ok(())
200                            })
201                        })
202                        .unwrap_or(Err(ErrorCode::RESERVE))
203                })
204                .unwrap_or_else(|err| Err(err.into()))
205        })
206    }
207
208    fn calculate_digest(&self) -> Result<(), ErrorCode> {
209        self.data_copied.set(0);
210
211        if let Err(e) = self
212            .hmac
213            .run(self.dest_buffer.take().ok_or(ErrorCode::RESERVE)?)
214        {
215            // Error, clear the processid and data
216            self.hmac.clear_data();
217            self.processid.clear();
218            self.dest_buffer.replace(e.1);
219
220            return Err(e.0);
221        }
222
223        Ok(())
224    }
225
226    fn verify_digest(&self) -> Result<(), ErrorCode> {
227        self.data_copied.set(0);
228
229        if let Err(e) = self
230            .hmac
231            .verify(self.dest_buffer.take().ok_or(ErrorCode::RESERVE)?)
232        {
233            // Error, clear the processid and data
234            self.hmac.clear_data();
235            self.processid.clear();
236            self.dest_buffer.replace(e.1);
237
238            return Err(e.0);
239        }
240
241        Ok(())
242    }
243
244    fn check_queue(&self) {
245        for appiter in self.apps.iter() {
246            // If an app is already running let it complete
247            if self.processid.is_some() {
248                break;
249            }
250
251            // If this app has a pending command let's use it.
252            if let Some(processid) = appiter.enter(|app, _| app.pending_run_app.take()) {
253                // Mark this driver as being in use.
254                self.processid.set(processid);
255                // Actually make the buzz happen.
256                if let Err(e) = self.run() {
257                    self.hmac.clear_data();
258                    self.processid.clear();
259                    let _ = self.apps.enter(processid, |_, kernel_data| {
260                        kernel_data.schedule_upcall(0, (into_statuscode(e.into()), 0, 0))
261                    });
262                }
263            }
264        }
265    }
266}
267
268impl<
269    'a,
270    H: digest::Digest<'a, DIGEST_LEN>
271        + digest::HmacMd5
272        + digest::HmacSha1
273        + digest::HmacSha224
274        + digest::HmacSha256
275        + digest::HmacSha384
276        + digest::HmacSha512,
277    const DIGEST_LEN: usize,
278> digest::ClientData<DIGEST_LEN> for HmacDriver<'a, H, DIGEST_LEN>
279{
280    // Because data needs to be copied from a userspace buffer into a kernel (RAM) one,
281    // we always pass mut data; this callback should never be invoked.
282    fn add_data_done(&self, _result: Result<(), ErrorCode>, _data: SubSlice<'static, u8>) {}
283
284    fn add_mut_data_done(&self, _result: Result<(), ErrorCode>, data: SubSliceMut<'static, u8>) {
285        self.processid.map(move |id| {
286            self.apps
287                .enter(id, move |app, kernel_data| {
288                    let mut data_len = 0;
289                    let mut exit = false;
290                    let mut static_buffer_len = 0;
291
292                    self.data_buffer.replace(data.take());
293
294                    self.data_buffer.map(|buf| {
295                        let ret = kernel_data
296                            .get_readonly_processbuffer(ro_allow::DATA)
297                            .and_then(|data| {
298                                data.enter(|data| {
299                                    // Determine the size of the static buffer we have
300                                    static_buffer_len = buf.len();
301                                    // Determine how much data we have already copied
302                                    let copied_data = self.data_copied.get();
303
304                                    data_len = data.len();
305
306                                    if data_len > copied_data {
307                                        let remaining_data = &data[copied_data..];
308                                        let remaining_len = data_len - copied_data;
309
310                                        if remaining_len < static_buffer_len {
311                                            remaining_data.copy_to_slice(&mut buf[..remaining_len]);
312                                        } else {
313                                            remaining_data[..static_buffer_len].copy_to_slice(buf);
314                                        }
315                                    }
316                                    Ok(())
317                                })
318                            })
319                            .unwrap_or(Err(ErrorCode::RESERVE));
320
321                        if ret == Err(ErrorCode::RESERVE) {
322                            // No data buffer, clear the processid and data
323                            self.hmac.clear_data();
324                            self.processid.clear();
325                            exit = true;
326                        }
327                    });
328
329                    if exit {
330                        return;
331                    }
332
333                    if static_buffer_len > 0 {
334                        let copied_data = self.data_copied.get();
335
336                        if data_len > copied_data {
337                            // Update the amount of data copied
338                            self.data_copied.set(copied_data + static_buffer_len);
339
340                            let mut lease_buf = SubSliceMut::new(self.data_buffer.take().unwrap());
341
342                            // Add the data from the static buffer to the HMAC
343                            if data_len < (copied_data + static_buffer_len) {
344                                lease_buf.slice(..(data_len - copied_data))
345                            }
346
347                            if self.hmac.add_mut_data(lease_buf).is_err() {
348                                // Error, clear the processid and data
349                                self.hmac.clear_data();
350                                self.processid.clear();
351                                return;
352                            }
353
354                            // Return as we don't want to run the digest yet
355                            return;
356                        }
357                    }
358
359                    // If we get here we are ready to run the digest, reset the copied data
360                    if app.op.get().unwrap() == UserSpaceOp::Run {
361                        if let Err(e) = self.calculate_digest() {
362                            let _ =
363                                kernel_data.schedule_upcall(0, (into_statuscode(e.into()), 0, 0));
364                        }
365                    } else if app.op.get().unwrap() == UserSpaceOp::Verify {
366                        let _ = kernel_data
367                            .get_readonly_processbuffer(ro_allow::COMPARE)
368                            .and_then(|compare| {
369                                compare.enter(|compare| {
370                                    let mut static_buffer_len = 0;
371                                    self.dest_buffer.map(|buf| {
372                                        // Determine the size of the static buffer we have
373                                        static_buffer_len = buf.len();
374
375                                        if static_buffer_len > compare.len() {
376                                            static_buffer_len = compare.len()
377                                        }
378
379                                        self.data_copied.set(static_buffer_len);
380
381                                        // Copy the data into the static buffer
382                                        compare[..static_buffer_len]
383                                            .copy_to_slice(&mut buf[..static_buffer_len]);
384                                    });
385                                })
386                            });
387
388                        if let Err(e) = self.verify_digest() {
389                            let _ =
390                                kernel_data.schedule_upcall(1, (into_statuscode(e.into()), 0, 0));
391                        }
392                    } else {
393                        let _ = kernel_data.schedule_upcall(0, (0, 0, 0));
394                    }
395                })
396                .map_err(|err| {
397                    if err == kernel::process::Error::NoSuchApp
398                        || err == kernel::process::Error::InactiveApp
399                    {
400                        self.processid.clear();
401                    }
402                })
403        });
404
405        self.check_queue();
406    }
407}
408
409impl<
410    'a,
411    H: digest::Digest<'a, DIGEST_LEN>
412        + digest::HmacMd5
413        + digest::HmacSha1
414        + digest::HmacSha224
415        + digest::HmacSha256
416        + digest::HmacSha384
417        + digest::HmacSha512,
418    const DIGEST_LEN: usize,
419> digest::ClientHash<DIGEST_LEN> for HmacDriver<'a, H, DIGEST_LEN>
420{
421    fn hash_done(&self, result: Result<(), ErrorCode>, digest: &'static mut [u8; DIGEST_LEN]) {
422        self.processid.map(|id| {
423            self.apps
424                .enter(id, |_, kernel_data| {
425                    self.hmac.clear_data();
426
427                    let pointer = digest[0] as *mut u8;
428
429                    let _ = kernel_data
430                        .get_readwrite_processbuffer(rw_allow::DEST)
431                        .and_then(|dest| {
432                            dest.mut_enter(|dest| {
433                                let len = dest.len();
434
435                                if len < DIGEST_LEN {
436                                    dest.copy_from_slice(&digest[0..len]);
437                                } else {
438                                    dest[0..DIGEST_LEN].copy_from_slice(digest);
439                                }
440                            })
441                        });
442
443                    let _ = match result {
444                        Ok(()) => kernel_data.schedule_upcall(0, (0, pointer as usize, 0)),
445                        Err(e) => kernel_data
446                            .schedule_upcall(0, (into_statuscode(e.into()), pointer as usize, 0)),
447                    };
448
449                    // Clear the current processid as it has finished running
450                    self.processid.clear();
451                })
452                .map_err(|err| {
453                    if err == kernel::process::Error::NoSuchApp
454                        || err == kernel::process::Error::InactiveApp
455                    {
456                        self.processid.clear();
457                    }
458                })
459        });
460
461        self.check_queue();
462        self.dest_buffer.replace(digest);
463    }
464}
465
466impl<
467    'a,
468    H: digest::Digest<'a, DIGEST_LEN>
469        + digest::HmacMd5
470        + digest::HmacSha1
471        + digest::HmacSha224
472        + digest::HmacSha256
473        + digest::HmacSha384
474        + digest::HmacSha512,
475    const DIGEST_LEN: usize,
476> digest::ClientVerify<DIGEST_LEN> for HmacDriver<'a, H, DIGEST_LEN>
477{
478    fn verification_done(
479        &self,
480        result: Result<bool, ErrorCode>,
481        compare: &'static mut [u8; DIGEST_LEN],
482    ) {
483        self.processid.map(|id| {
484            self.apps
485                .enter(id, |_app, kernel_data| {
486                    self.hmac.clear_data();
487
488                    let _ = match result {
489                        Ok(equal) => kernel_data.schedule_upcall(1, (0, equal as usize, 0)),
490                        Err(e) => kernel_data.schedule_upcall(1, (into_statuscode(e.into()), 0, 0)),
491                    };
492
493                    // Clear the current processid as it has finished running
494                    self.processid.clear();
495                })
496                .map_err(|err| {
497                    if err == kernel::process::Error::NoSuchApp
498                        || err == kernel::process::Error::InactiveApp
499                    {
500                        self.processid.clear();
501                    }
502                })
503        });
504
505        self.check_queue();
506        self.dest_buffer.replace(compare);
507    }
508}
509
510/// Specify memory regions to be used.
511///
512/// ### `allow_num`
513///
514/// - `0`: Allow a buffer for storing the key. The kernel will read from this
515///   when running This should not be changed after running `run` until the HMAC
516///   has completed
517/// - `1`: Allow a buffer for storing the buffer. The kernel will read from this
518///   when running This should not be changed after running `run` until the HMAC
519///   has completed
520/// - `2`: Allow a buffer for storing the digest. The kernel will fill this with
521///   the HMAC digest before calling the `hash_done` callback.
522impl<
523    'a,
524    H: digest::Digest<'a, DIGEST_LEN>
525        + digest::HmacMd5
526        + digest::HmacSha1
527        + digest::HmacSha224
528        + digest::HmacSha256
529        + digest::HmacSha384
530        + digest::HmacSha512,
531    const DIGEST_LEN: usize,
532> SyscallDriver for HmacDriver<'a, H, DIGEST_LEN>
533{
534    // Subscribe to HmacDriver events.
535    //
536    // ### `subscribe_num`
537    //
538    // - `0`: Subscribe to interrupts from HMAC events. The callback signature
539    //   is `fn(result: u32)`
540
541    /// Setup and run the HMAC hardware
542    ///
543    /// We expect userspace to setup buffers for the key, data and digest.
544    /// These buffers must be allocated and specified to the kernel from the
545    /// above allow calls.
546    ///
547    /// We expect userspace not to change the value while running. If userspace
548    /// changes the value we have no guarantee of what is passed to the
549    /// hardware. This isn't a security issue, it will just prove the requesting
550    /// app with invalid data.
551    ///
552    /// The driver will take care of clearing data from the underlying implementation
553    /// by calling the `clear_data()` function when the `hash_complete()` callback
554    /// is called or if an error is encountered.
555    ///
556    /// ### `command_num`
557    ///
558    /// - `0`: set_algorithm
559    /// - `1`: run
560    /// - `2`: update
561    /// - `3`: finish
562    fn command(
563        &self,
564        command_num: usize,
565        data1: usize,
566        _data2: usize,
567        processid: ProcessId,
568    ) -> CommandReturn {
569        let match_or_empty_or_nonexistant = self.processid.map_or(true, |owning_app| {
570            // We have recorded that an app has ownership of the HMAC.
571
572            // If the HMAC is still active, then we need to wait for the operation
573            // to finish and the app, whether it exists or not (it may have crashed),
574            // still owns this capsule. If the HMAC is not active, then
575            // we need to verify that that application still exists, and remove
576            // it as owner if not.
577            if self.active.get() {
578                owning_app == processid
579            } else {
580                // Check the app still exists.
581                //
582                // If the `.enter()` succeeds, then the app is still valid, and
583                // we can check if the owning app matches the one that called
584                // the command. If the `.enter()` fails, then the owning app no
585                // longer exists and we return `true` to signify the
586                // "or_nonexistant" case.
587                self.apps
588                    .enter(owning_app, |_, _| owning_app == processid)
589                    .unwrap_or(true)
590            }
591        });
592
593        let app_match = self.processid.map_or(false, |owning_app| {
594            // We have recorded that an app has ownership of the HMAC.
595
596            // If the HMAC is still active, then we need to wait for the operation
597            // to finish and the app, whether it exists or not (it may have crashed),
598            // still owns this capsule. If the HMAC is not active, then
599            // we need to verify that that application still exists, and remove
600            // it as owner if not.
601            if self.active.get() {
602                owning_app == processid
603            } else {
604                // Check the app still exists.
605                //
606                // If the `.enter()` succeeds, then the app is still valid, and
607                // we can check if the owning app matches the one that called
608                // the command. If the `.enter()` fails, then the owning app no
609                // longer exists and we return `true` to signify the
610                // "or_nonexistant" case.
611                self.apps
612                    .enter(owning_app, |_, _| owning_app == processid)
613                    .unwrap_or(true)
614            }
615        });
616
617        // Try the commands where we want to start an operation *not* entered in
618        // an app grant first.
619        if match_or_empty_or_nonexistant
620            && (command_num == 1 || command_num == 2 || command_num == 4)
621        {
622            self.processid.set(processid);
623
624            let _ = self.apps.enter(processid, |app, _| {
625                if command_num == 1 {
626                    // run
627                    // Use key and data to compute hash
628                    // This will trigger a callback once the digest is generated
629                    app.op.set(Some(UserSpaceOp::Run));
630                } else if command_num == 2 {
631                    // update
632                    // Input key and data, don't compute final hash yet
633                    // This will trigger a callback once the data has been added.
634                    app.op.set(Some(UserSpaceOp::Update));
635                } else if command_num == 4 {
636                    // verify
637                    // Use key and data to compute hash and comapre it against
638                    // the digest
639                    app.op.set(Some(UserSpaceOp::Verify));
640                }
641            });
642
643            return if let Err(e) = self.run() {
644                self.hmac.clear_data();
645                self.processid.clear();
646                self.check_queue();
647                CommandReturn::failure(e)
648            } else {
649                CommandReturn::success()
650            };
651        }
652
653        self.apps
654            .enter(processid, |app, kernel_data| {
655                match command_num {
656                    // set_algorithm
657                    0 => {
658                        match data1 {
659                            // SHA256
660                            0 => {
661                                app.sha_operation = Some(ShaOperation::Sha256);
662                                CommandReturn::success()
663                            }
664                            // SHA384
665                            1 => {
666                                app.sha_operation = Some(ShaOperation::Sha384);
667                                CommandReturn::success()
668                            }
669                            // SHA512
670                            2 => {
671                                app.sha_operation = Some(ShaOperation::Sha512);
672                                CommandReturn::success()
673                            }
674                            // SHA224
675                            3 => {
676                                app.sha_operation = Some(ShaOperation::Sha224);
677                                CommandReturn::success()
678                            }
679                            // SHA1
680                            4 => {
681                                app.sha_operation = Some(ShaOperation::Sha1);
682                                CommandReturn::success()
683                            }
684                            // Md5
685                            5 => {
686                                app.sha_operation = Some(ShaOperation::Md5);
687                                CommandReturn::success()
688                            }
689                            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
690                        }
691                    }
692
693                    // run
694                    1 => {
695                        // There is an active app, so queue this request (if possible).
696                        if app.pending_run_app.is_some() {
697                            // No more room in the queue, nowhere to store this
698                            // request.
699                            CommandReturn::failure(ErrorCode::NOMEM)
700                        } else {
701                            // We can store this, so lets do it.
702                            app.pending_run_app = Some(processid);
703                            app.op.set(Some(UserSpaceOp::Run));
704                            CommandReturn::success()
705                        }
706                    }
707
708                    // update
709                    2 => {
710                        // There is an active app, so queue this request (if possible).
711                        if app.pending_run_app.is_some() {
712                            // No more room in the queue, nowhere to store this
713                            // request.
714                            CommandReturn::failure(ErrorCode::NOMEM)
715                        } else {
716                            // We can store this, so lets do it.
717                            app.pending_run_app = Some(processid);
718                            app.op.set(Some(UserSpaceOp::Update));
719                            CommandReturn::success()
720                        }
721                    }
722
723                    // finish
724                    // Compute final hash yet, useful after a update command
725                    3 => {
726                        if app_match {
727                            if let Err(e) = self.calculate_digest() {
728                                let _ = kernel_data.schedule_upcall(
729                                    0,
730                                    (kernel::errorcode::into_statuscode(e.into()), 0, 0),
731                                );
732                            }
733                            CommandReturn::success()
734                        } else {
735                            // We don't queue this request, the user has to call
736                            // `update` first.
737                            CommandReturn::failure(ErrorCode::OFF)
738                        }
739                    }
740
741                    // verify
742                    4 => {
743                        // There is an active app, so queue this request (if possible).
744                        if app.pending_run_app.is_some() {
745                            // No more room in the queue, nowhere to store this
746                            // request.
747                            CommandReturn::failure(ErrorCode::NOMEM)
748                        } else {
749                            // We can store this, so lets do it.
750                            app.pending_run_app = Some(processid);
751                            app.op.set(Some(UserSpaceOp::Verify));
752                            CommandReturn::success()
753                        }
754                    }
755
756                    // verify_finish
757                    // Use key and data to compute hash and compare it against
758                    // the digest, useful after a update command
759                    5 => {
760                        if app_match {
761                            let _ = kernel_data
762                                .get_readonly_processbuffer(ro_allow::COMPARE)
763                                .and_then(|compare| {
764                                    compare.enter(|compare| {
765                                        let mut static_buffer_len = 0;
766                                        self.dest_buffer.map(|buf| {
767                                            // Determine the size of the static buffer we have
768                                            static_buffer_len = buf.len();
769
770                                            if static_buffer_len > compare.len() {
771                                                static_buffer_len = compare.len()
772                                            }
773
774                                            self.data_copied.set(static_buffer_len);
775
776                                            // Copy the data into the static buffer
777                                            compare[..static_buffer_len]
778                                                .copy_to_slice(&mut buf[..static_buffer_len]);
779                                        });
780                                    })
781                                });
782
783                            if let Err(e) = self.verify_digest() {
784                                let _ = kernel_data
785                                    .schedule_upcall(1, (into_statuscode(e.into()), 0, 0));
786                            }
787                            CommandReturn::success()
788                        } else {
789                            // We don't queue this request, the user has to call
790                            // `update` first.
791                            CommandReturn::failure(ErrorCode::OFF)
792                        }
793                    }
794
795                    // default
796                    _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
797                }
798            })
799            .unwrap_or_else(|err| err.into())
800    }
801
802    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
803        self.apps.enter(processid, |_, _| {})
804    }
805}
806
807#[derive(Copy, Clone, PartialEq)]
808enum UserSpaceOp {
809    Run,
810    Update,
811    Verify,
812}
813
814#[derive(Default)]
815pub struct App {
816    pending_run_app: Option<ProcessId>,
817    sha_operation: Option<ShaOperation>,
818    op: Cell<Option<UserSpaceOp>>,
819}