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