1 // Copyright 2023, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! This module mirrors the content in open-dice/include/dice/android.h
16
17 use crate::dice::{context, Cdi, CdiValues, DiceArtifacts, InputValues, CDI_SIZE};
18 use crate::error::{check_result, DiceError, Result};
19 use open_dice_android_bindgen::{
20 DiceAndroidConfigValues, DiceAndroidFormatConfigDescriptor, DiceAndroidHandoverParse,
21 DiceAndroidMainFlow, DICE_ANDROID_CONFIG_COMPONENT_NAME, DICE_ANDROID_CONFIG_COMPONENT_VERSION,
22 DICE_ANDROID_CONFIG_RESETTABLE, DICE_ANDROID_CONFIG_RKP_VM_MARKER,
23 DICE_ANDROID_CONFIG_SECURITY_VERSION,
24 };
25 use std::{ffi::CStr, ptr};
26
27 /// Contains the input values used to construct the Android Profile for DICE
28 /// configuration descriptor.
29 #[derive(Default, Debug)]
30 pub struct DiceConfigValues<'a> {
31 /// Name of the component.
32 pub component_name: Option<&'a CStr>,
33 /// Version of the component.
34 pub component_version: Option<u64>,
35 /// Whether the key changes on factory reset.
36 pub resettable: bool,
37 /// Monotonically increasing version of the component.
38 pub security_version: Option<u64>,
39 /// Whether the component can take part in running the RKP VM.
40 pub rkp_vm_marker: bool,
41 }
42
43 /// Formats a configuration descriptor following the Android Profile for DICE specification.
44 /// See https://pigweed.googlesource.com/open-dice/+/refs/heads/main/docs/android.md.
bcc_format_config_descriptor(values: &DiceConfigValues, buffer: &mut [u8]) -> Result<usize>45 pub fn bcc_format_config_descriptor(values: &DiceConfigValues, buffer: &mut [u8]) -> Result<usize> {
46 let mut configs = 0;
47
48 let component_name = values.component_name.map_or(ptr::null(), |name| {
49 configs |= DICE_ANDROID_CONFIG_COMPONENT_NAME;
50 name.as_ptr()
51 });
52 let component_version = values.component_version.map_or(0, |version| {
53 configs |= DICE_ANDROID_CONFIG_COMPONENT_VERSION;
54 version
55 });
56 if values.resettable {
57 configs |= DICE_ANDROID_CONFIG_RESETTABLE;
58 }
59 let security_version = values.security_version.map_or(0, |version| {
60 configs |= DICE_ANDROID_CONFIG_SECURITY_VERSION;
61 version
62 });
63 if values.rkp_vm_marker {
64 configs |= DICE_ANDROID_CONFIG_RKP_VM_MARKER;
65 }
66
67 let values =
68 DiceAndroidConfigValues { configs, component_name, component_version, security_version };
69
70 let mut buffer_size = 0;
71 check_result(
72 // SAFETY: The function writes to the buffer, within the given bounds, and only reads the
73 // input values. It writes its result to buffer_size.
74 unsafe {
75 DiceAndroidFormatConfigDescriptor(
76 &values,
77 buffer.len(),
78 buffer.as_mut_ptr(),
79 &mut buffer_size,
80 )
81 },
82 buffer_size,
83 )?;
84 Ok(buffer_size)
85 }
86
87 /// Executes the main Android DICE flow.
88 ///
89 /// Given a full set of input values along with the current DICE chain and CDI values,
90 /// computes the next CDI values and matching updated DICE chain.
bcc_main_flow( current_cdi_attest: &Cdi, current_cdi_seal: &Cdi, current_chain: &[u8], input_values: &InputValues, next_cdi_values: &mut CdiValues, next_chain: &mut [u8], ) -> Result<usize>91 pub fn bcc_main_flow(
92 current_cdi_attest: &Cdi,
93 current_cdi_seal: &Cdi,
94 current_chain: &[u8],
95 input_values: &InputValues,
96 next_cdi_values: &mut CdiValues,
97 next_chain: &mut [u8],
98 ) -> Result<usize> {
99 let mut next_chain_size = 0;
100 check_result(
101 // SAFETY: `DiceAndroidMainFlow` only reads the `current_chain` and CDI values and writes
102 // to `next_chain` and next CDI values within its bounds. It also reads `input_values` as a
103 // constant input and doesn't store any pointer.
104 // The first argument is a pointer to a valid |DiceContext_| object for multi-alg open-dice
105 // and a null pointer otherwise.
106 unsafe {
107 DiceAndroidMainFlow(
108 context(),
109 current_cdi_attest.as_ptr(),
110 current_cdi_seal.as_ptr(),
111 current_chain.as_ptr(),
112 current_chain.len(),
113 input_values.as_ptr(),
114 next_chain.len(),
115 next_chain.as_mut_ptr(),
116 &mut next_chain_size,
117 next_cdi_values.cdi_attest.as_mut_ptr(),
118 next_cdi_values.cdi_seal.as_mut_ptr(),
119 )
120 },
121 next_chain_size,
122 )?;
123 Ok(next_chain_size)
124 }
125
126 /// Executes the main Android DICE handover flow.
127 ///
128 /// A handover combines the DICE chain and CDIs in a single CBOR object.
129 /// This function takes the current boot stage's handover bundle and produces a
130 /// bundle for the next stage.
131 #[cfg(feature = "multialg")]
bcc_handover_main_flow( current_handover: &[u8], input_values: &InputValues, next_handover: &mut [u8], ctx: crate::dice::DiceContext, ) -> Result<usize>132 pub fn bcc_handover_main_flow(
133 current_handover: &[u8],
134 input_values: &InputValues,
135 next_handover: &mut [u8],
136 ctx: crate::dice::DiceContext,
137 ) -> Result<usize> {
138 let mut next_handover_size = 0;
139 let mut ctx: open_dice_cbor_bindgen::DiceContext_ = ctx.into();
140 check_result(
141 // SAFETY: The function only reads `current_handover` and writes to `next_handover`
142 // within its bounds,
143 // It also reads `input_values` as a constant input and doesn't store any pointer.
144 // The first argument is a pointer to a valid |DiceContext_| object.
145 unsafe {
146 open_dice_android_bindgen::DiceAndroidHandoverMainFlow(
147 &mut ctx as *mut _ as *mut std::ffi::c_void,
148 current_handover.as_ptr(),
149 current_handover.len(),
150 input_values.as_ptr(),
151 next_handover.len(),
152 next_handover.as_mut_ptr(),
153 &mut next_handover_size,
154 )
155 },
156 next_handover_size,
157 )?;
158
159 Ok(next_handover_size)
160 }
161
162 /// An Android DICE handover object combines the DICE chain and CDIs in a single CBOR object.
163 /// This struct is used as return of the function `android_dice_handover_parse`, its lifetime is
164 /// tied to the lifetime of the raw handover slice.
165 #[derive(Debug)]
166 pub struct BccHandover<'a> {
167 /// Attestation CDI.
168 cdi_attest: &'a [u8; CDI_SIZE],
169 /// Sealing CDI.
170 cdi_seal: &'a [u8; CDI_SIZE],
171 /// DICE chain.
172 bcc: Option<&'a [u8]>,
173 }
174
175 impl<'a> DiceArtifacts for BccHandover<'a> {
cdi_attest(&self) -> &[u8; CDI_SIZE]176 fn cdi_attest(&self) -> &[u8; CDI_SIZE] {
177 self.cdi_attest
178 }
179
cdi_seal(&self) -> &[u8; CDI_SIZE]180 fn cdi_seal(&self) -> &[u8; CDI_SIZE] {
181 self.cdi_seal
182 }
183
bcc(&self) -> Option<&[u8]>184 fn bcc(&self) -> Option<&[u8]> {
185 self.bcc
186 }
187 }
188
189 /// This function parses the `handover` to extracts the DICE chain and CDIs.
190 /// The lifetime of the returned `DiceAndroidHandover` is tied to the given `handover` slice.
bcc_handover_parse(handover: &[u8]) -> Result<BccHandover>191 pub fn bcc_handover_parse(handover: &[u8]) -> Result<BccHandover> {
192 let mut cdi_attest: *const u8 = ptr::null();
193 let mut cdi_seal: *const u8 = ptr::null();
194 let mut chain: *const u8 = ptr::null();
195 let mut chain_size = 0;
196 check_result(
197 // SAFETY: The `handover` is only read and never stored and the returned pointers should
198 // all point within the address range of the `handover` or be NULL.
199 unsafe {
200 DiceAndroidHandoverParse(
201 handover.as_ptr(),
202 handover.len(),
203 &mut cdi_attest,
204 &mut cdi_seal,
205 &mut chain,
206 &mut chain_size,
207 )
208 },
209 chain_size,
210 )?;
211 let cdi_attest = sub_slice(handover, cdi_attest, CDI_SIZE)?;
212 let cdi_seal = sub_slice(handover, cdi_seal, CDI_SIZE)?;
213 let bcc = sub_slice(handover, chain, chain_size).ok();
214 Ok(BccHandover {
215 cdi_attest: cdi_attest.try_into().map_err(|_| DiceError::PlatformError)?,
216 cdi_seal: cdi_seal.try_into().map_err(|_| DiceError::PlatformError)?,
217 bcc,
218 })
219 }
220
221 /// Gets a slice the `addr` points to and of length `len`.
222 /// The slice should be contained in the buffer.
sub_slice(buffer: &[u8], addr: *const u8, len: usize) -> Result<&[u8]>223 fn sub_slice(buffer: &[u8], addr: *const u8, len: usize) -> Result<&[u8]> {
224 if addr.is_null() || !buffer.as_ptr_range().contains(&addr) {
225 return Err(DiceError::PlatformError);
226 }
227 // SAFETY: This is safe because addr is not null and is within the range of the buffer.
228 let start: usize = unsafe {
229 addr.offset_from(buffer.as_ptr()).try_into().map_err(|_| DiceError::PlatformError)?
230 };
231 start.checked_add(len).and_then(|end| buffer.get(start..end)).ok_or(DiceError::PlatformError)
232 }
233