blob: 9e39436ae4c0018dca53c4badbf8f21b1c265f30 [file] [log] [blame]
David Brazdil9a83e612022-09-27 17:38:10 +00001/*
2 * Copyright 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! Bare metal wrapper around libopen_dice.
18
19#![no_std]
20
21use core::fmt::{self, Debug};
22use open_dice_cbor_bindgen::{
23 DiceHash, DiceResult, DiceResult_kDiceResultBufferTooSmall as DICE_RESULT_BUFFER_TOO_SMALL,
24 DiceResult_kDiceResultInvalidInput as DICE_RESULT_INVALID_INPUT,
25 DiceResult_kDiceResultOk as DICE_RESULT_OK,
26 DiceResult_kDiceResultPlatformError as DICE_RESULT_PLATFORM_ERROR,
27};
28
29const HASH_SIZE: usize = open_dice_cbor_bindgen::DICE_HASH_SIZE as usize;
30
31/// Array type of hashes used by DICE.
32pub type Hash = [u8; HASH_SIZE];
33
34/// Error type used by DICE.
35pub enum Error {
36 /// Provided input was invalid.
37 InvalidInput,
38 /// Provided buffer was too small.
39 BufferTooSmall,
40 /// Unexpected platform error.
41 PlatformError,
42 /// Unexpected return value.
43 Unknown(DiceResult),
44}
45
46impl Debug for Error {
47 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48 match self {
49 Error::InvalidInput => write!(f, "invalid input"),
50 Error::BufferTooSmall => write!(f, "buffer too small"),
51 Error::PlatformError => write!(f, "platform error"),
52 Error::Unknown(n) => write!(f, "unknown error: {}", n),
53 }
54 }
55}
56
57fn check_call(ret: DiceResult) -> Result<(), Error> {
58 match ret {
59 DICE_RESULT_OK => Ok(()),
60 DICE_RESULT_INVALID_INPUT => Err(Error::InvalidInput),
61 DICE_RESULT_BUFFER_TOO_SMALL => Err(Error::BufferTooSmall),
62 DICE_RESULT_PLATFORM_ERROR => Err(Error::PlatformError),
63 n => Err(Error::Unknown(n)),
64 }
65}
66
67fn ctx() -> *mut core::ffi::c_void {
68 core::ptr::null_mut()
69}
70
71/// Hash the provided input using DICE's default hash function.
72pub fn hash(bytes: &[u8]) -> Result<Hash, Error> {
73 let mut output: Hash = [0; HASH_SIZE];
74 // SAFETY - DiceHash takes a sized input buffer and writes to a constant-sized output buffer.
75 check_call(unsafe { DiceHash(ctx(), bytes.as_ptr(), bytes.len(), output.as_mut_ptr()) })?;
76 Ok(output)
77}