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::{Cdi, CdiValues, DiceArtifacts, InputValues, CDI_SIZE};
18 use crate::error::{check_result, DiceError, Result};
19 use open_dice_android_bindgen::{
20 DiceAndroidConfigValues, DiceAndroidFormatConfigDescriptor, DiceAndroidHandoverMainFlow,
21 DiceAndroidHandoverParse, DiceAndroidMainFlow, DICE_ANDROID_CONFIG_COMPONENT_NAME,
22 DICE_ANDROID_CONFIG_COMPONENT_VERSION, DICE_ANDROID_CONFIG_RESETTABLE,
23 DICE_ANDROID_CONFIG_RKP_VM_MARKER, 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 can be null and is not used in the current implementation.
105 unsafe {
106 DiceAndroidMainFlow(
107 ptr::null_mut(), // context
108 current_cdi_attest.as_ptr(),
109 current_cdi_seal.as_ptr(),
110 current_chain.as_ptr(),
111 current_chain.len(),
112 input_values.as_ptr(),
113 next_chain.len(),
114 next_chain.as_mut_ptr(),
115 &mut next_chain_size,
116 next_cdi_values.cdi_attest.as_mut_ptr(),
117 next_cdi_values.cdi_seal.as_mut_ptr(),
118 )
119 },
120 next_chain_size,
121 )?;
122 Ok(next_chain_size)
123 }
124
125 /// Executes the main Android DICE handover flow.
126 ///
127 /// A handover combines the DICE chain and CDIs in a single CBOR object.
128 /// This function takes the current boot stage's handover bundle and produces a
129 /// bundle for the next stage.
bcc_handover_main_flow( current_handover: &[u8], input_values: &InputValues, next_handover: &mut [u8], ) -> Result<usize>130 pub fn bcc_handover_main_flow(
131 current_handover: &[u8],
132 input_values: &InputValues,
133 next_handover: &mut [u8],
134 ) -> Result<usize> {
135 let mut next_handover_size = 0;
136 check_result(
137 // SAFETY: The function only reads `current_handover` and writes to `next_handover`
138 // within its bounds,
139 // It also reads `input_values` as a constant input and doesn't store any pointer.
140 // The first argument can be null and is not used in the current implementation.
141 unsafe {
142 DiceAndroidHandoverMainFlow(
143 ptr::null_mut(), // context
144 current_handover.as_ptr(),
145 current_handover.len(),
146 input_values.as_ptr(),
147 next_handover.len(),
148 next_handover.as_mut_ptr(),
149 &mut next_handover_size,
150 )
151 },
152 next_handover_size,
153 )?;
154
155 Ok(next_handover_size)
156 }
157
158 /// An Android DICE handover object combines the DICE chain and CDIs in a single CBOR object.
159 /// This struct is used as return of the function `android_dice_handover_parse`, its lifetime is
160 /// tied to the lifetime of the raw handover slice.
161 #[derive(Debug)]
162 pub struct BccHandover<'a> {
163 /// Attestation CDI.
164 cdi_attest: &'a [u8; CDI_SIZE],
165 /// Sealing CDI.
166 cdi_seal: &'a [u8; CDI_SIZE],
167 /// DICE chain.
168 bcc: Option<&'a [u8]>,
169 }
170
171 impl<'a> DiceArtifacts for BccHandover<'a> {
cdi_attest(&self) -> &[u8; CDI_SIZE]172 fn cdi_attest(&self) -> &[u8; CDI_SIZE] {
173 self.cdi_attest
174 }
175
cdi_seal(&self) -> &[u8; CDI_SIZE]176 fn cdi_seal(&self) -> &[u8; CDI_SIZE] {
177 self.cdi_seal
178 }
179
bcc(&self) -> Option<&[u8]>180 fn bcc(&self) -> Option<&[u8]> {
181 self.bcc
182 }
183 }
184
185 /// This function parses the `handover` to extracts the DICE chain and CDIs.
186 /// The lifetime of the returned `DiceAndroidHandover` is tied to the given `handover` slice.
bcc_handover_parse(handover: &[u8]) -> Result<BccHandover>187 pub fn bcc_handover_parse(handover: &[u8]) -> Result<BccHandover> {
188 let mut cdi_attest: *const u8 = ptr::null();
189 let mut cdi_seal: *const u8 = ptr::null();
190 let mut chain: *const u8 = ptr::null();
191 let mut chain_size = 0;
192 check_result(
193 // SAFETY: The `handover` is only read and never stored and the returned pointers should
194 // all point within the address range of the `handover` or be NULL.
195 unsafe {
196 DiceAndroidHandoverParse(
197 handover.as_ptr(),
198 handover.len(),
199 &mut cdi_attest,
200 &mut cdi_seal,
201 &mut chain,
202 &mut chain_size,
203 )
204 },
205 chain_size,
206 )?;
207 let cdi_attest = sub_slice(handover, cdi_attest, CDI_SIZE)?;
208 let cdi_seal = sub_slice(handover, cdi_seal, CDI_SIZE)?;
209 let bcc = sub_slice(handover, chain, chain_size).ok();
210 Ok(BccHandover {
211 cdi_attest: cdi_attest.try_into().map_err(|_| DiceError::PlatformError)?,
212 cdi_seal: cdi_seal.try_into().map_err(|_| DiceError::PlatformError)?,
213 bcc,
214 })
215 }
216
217 /// Gets a slice the `addr` points to and of length `len`.
218 /// The slice should be contained in the buffer.
sub_slice(buffer: &[u8], addr: *const u8, len: usize) -> Result<&[u8]>219 fn sub_slice(buffer: &[u8], addr: *const u8, len: usize) -> Result<&[u8]> {
220 if addr.is_null() || !buffer.as_ptr_range().contains(&addr) {
221 return Err(DiceError::PlatformError);
222 }
223 // SAFETY: This is safe because addr is not null and is within the range of the buffer.
224 let start: usize = unsafe {
225 addr.offset_from(buffer.as_ptr()).try_into().map_err(|_| DiceError::PlatformError)?
226 };
227 start.checked_add(len).and_then(|end| buffer.get(start..end)).ok_or(DiceError::PlatformError)
228 }
229