1 // Copyright 2022, 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 //! pVM firmware.
16
17 #![no_main]
18 #![no_std]
19
20 extern crate alloc;
21
22 mod arch;
23 mod bootargs;
24 mod config;
25 mod device_assignment;
26 mod dice;
27 mod entry;
28 mod fdt;
29 mod gpt;
30 mod instance;
31 mod memory;
32 mod rollback;
33
34 use crate::dice::{DiceChainInfo, PartialInputs};
35 use crate::entry::RebootReason;
36 use crate::fdt::{modify_for_next_stage, read_instance_id, sanitize_device_tree};
37 use crate::rollback::perform_rollback_protection;
38 use alloc::borrow::Cow;
39 use alloc::boxed::Box;
40 use alloc::vec::Vec;
41 use bssl_avf::Digester;
42 use diced_open_dice::{
43 bcc_handover_parse, DiceArtifacts, DiceContext, Hidden, HIDDEN_SIZE, VM_KEY_ALGORITHM,
44 };
45 use libfdt::Fdt;
46 use log::{debug, error, info, trace, warn};
47 use pvmfw_avb::verify_payload;
48 use pvmfw_avb::DebugLevel;
49 use pvmfw_avb::VerifiedBootData;
50 use pvmfw_embedded_key::PUBLIC_KEY;
51 use vmbase::heap;
52 use vmbase::memory::{flush, SIZE_4KB};
53 use vmbase::rand;
54
main<'a>( untrusted_fdt: &mut Fdt, signed_kernel: &[u8], ramdisk: Option<&[u8]>, current_dice_handover: Option<&[u8]>, mut debug_policy: Option<&[u8]>, vm_dtbo: Option<&mut [u8]>, vm_ref_dt: Option<&[u8]>, ) -> Result<(Option<&'a [u8]>, bool), RebootReason>55 fn main<'a>(
56 untrusted_fdt: &mut Fdt,
57 signed_kernel: &[u8],
58 ramdisk: Option<&[u8]>,
59 current_dice_handover: Option<&[u8]>,
60 mut debug_policy: Option<&[u8]>,
61 vm_dtbo: Option<&mut [u8]>,
62 vm_ref_dt: Option<&[u8]>,
63 ) -> Result<(Option<&'a [u8]>, bool), RebootReason> {
64 info!("pVM firmware");
65 debug!("FDT: {:?}", untrusted_fdt.as_ptr());
66 debug!("Signed kernel: {:?} ({:#x} bytes)", signed_kernel.as_ptr(), signed_kernel.len());
67 debug!("AVB public key: addr={:?}, size={:#x} ({1})", PUBLIC_KEY.as_ptr(), PUBLIC_KEY.len());
68 if let Some(rd) = ramdisk {
69 debug!("Ramdisk: {:?} ({:#x} bytes)", rd.as_ptr(), rd.len());
70 } else {
71 debug!("Ramdisk: None");
72 }
73
74 let (parsed_dice, dice_debug_mode) = parse_dice_handover(current_dice_handover)?;
75
76 // The bootloader should never pass us a debug policy when the boot is secure (the bootloader
77 // is locked). If it gets it wrong, disregard it & log it, to avoid it causing problems.
78 if debug_policy.is_some() && !dice_debug_mode {
79 warn!("Ignoring debug policy, DICE handover does not indicate Debug mode");
80 debug_policy = None;
81 }
82
83 // Policy/Hidden ABI: If the pvmfw loader (typically ABL) didn't pass a DICE handover (which is
84 // technically still mandatory, as per the config data specification), skip DICE, AVB, and RBP.
85 // This is to support Qualcomm QTVMs, which perform guest image verification in TrustZone.
86 let (verified_boot_data, debuggable, guest_page_size) = if current_dice_handover.is_none() {
87 warn!("Verified boot is disabled!");
88 (None, false, SIZE_4KB)
89 } else {
90 let (dat, debug, sz) = perform_verified_boot(signed_kernel, ramdisk)?;
91 (Some(dat), debug, sz)
92 };
93
94 let hyp_page_size = hypervisor_backends::get_granule_size();
95 let _ =
96 sanitize_device_tree(untrusted_fdt, vm_dtbo, vm_ref_dt, guest_page_size, hyp_page_size)?;
97 let fdt = untrusted_fdt; // DT has now been sanitized.
98
99 let (next_dice_handover, new_instance) = if let Some(ref data) = verified_boot_data {
100 let instance_hash = salt_from_instance_id(fdt)?;
101 let dice_inputs = PartialInputs::new(data, instance_hash).map_err(|e| {
102 error!("Failed to compute partial DICE inputs: {e:?}");
103 RebootReason::InternalError
104 })?;
105 let (dice_handover_bytes, dice_cdi_seal, dice_context) =
106 parsed_dice.expect("Missing DICE values with VB data");
107 let (new_instance, salt, defer_rollback_protection) =
108 perform_rollback_protection(fdt, data, &dice_inputs, &dice_cdi_seal)?;
109 trace!("Got salt for instance: {salt:x?}");
110
111 let next_dice_handover = perform_dice_derivation(
112 dice_handover_bytes.as_ref(),
113 dice_context,
114 dice_inputs,
115 &salt,
116 defer_rollback_protection,
117 guest_page_size,
118 guest_page_size,
119 )?;
120
121 (Some(next_dice_handover), new_instance)
122 } else {
123 (None, true)
124 };
125
126 let kaslr_seed = u64::from_ne_bytes(rand::random_array().map_err(|e| {
127 error!("Failed to generated guest KASLR seed: {e}");
128 RebootReason::InternalError
129 })?);
130 let strict_boot = true;
131 modify_for_next_stage(
132 fdt,
133 next_dice_handover,
134 new_instance,
135 strict_boot,
136 debug_policy,
137 debuggable,
138 kaslr_seed,
139 )
140 .map_err(|e| {
141 error!("Failed to configure device tree: {e}");
142 RebootReason::InternalError
143 })?;
144
145 info!("Starting payload...");
146 Ok((next_dice_handover, debuggable))
147 }
148
parse_dice_handover( bytes: Option<&[u8]>, ) -> Result<(Option<(Cow<'_, [u8]>, Vec<u8>, DiceContext)>, bool), RebootReason>149 fn parse_dice_handover(
150 bytes: Option<&[u8]>,
151 ) -> Result<(Option<(Cow<'_, [u8]>, Vec<u8>, DiceContext)>, bool), RebootReason> {
152 let Some(bytes) = bytes else {
153 return Ok((None, false));
154 };
155 let dice_handover = bcc_handover_parse(bytes).map_err(|e| {
156 error!("Invalid DICE Handover: {e:?}");
157 RebootReason::InvalidDiceHandover
158 })?;
159 trace!("DICE handover: {dice_handover:x?}");
160
161 let dice_chain_info = DiceChainInfo::new(dice_handover.bcc()).map_err(|e| {
162 error!("{e}");
163 RebootReason::InvalidDiceHandover
164 })?;
165 let is_debug_mode = dice_chain_info.is_debug_mode();
166 let cose_alg = dice_chain_info.leaf_subject_pubkey().cose_alg;
167 trace!("DICE chain leaf subject public key algorithm: {:?}", cose_alg);
168
169 let dice_context = DiceContext {
170 authority_algorithm: cose_alg.try_into().map_err(|e| {
171 error!("{e}");
172 RebootReason::InternalError
173 })?,
174 subject_algorithm: VM_KEY_ALGORITHM,
175 };
176
177 let cdi_seal = dice_handover.cdi_seal().to_vec();
178
179 let bytes_for_next = if cfg!(dice_changes) {
180 Cow::Borrowed(bytes)
181 } else {
182 // It is possible that the DICE chain we were given is rooted in the UDS. We do not want to
183 // give such a chain to the payload, or even the associated CDIs. So remove the
184 // entire chain we were given and taint the CDIs. Note that the resulting CDIs are
185 // still deterministically derived from those we received, so will vary iff they do.
186 // TODO(b/280405545): Remove this post Android 14.
187 let truncated_bytes = dice::chain::truncate(dice_handover).map_err(|e| {
188 error!("{e}");
189 RebootReason::InternalError
190 })?;
191 Cow::Owned(truncated_bytes)
192 };
193
194 Ok((Some((bytes_for_next, cdi_seal, dice_context)), is_debug_mode))
195 }
196
perform_dice_derivation<'a>( dice_handover_bytes: &[u8], dice_context: DiceContext, dice_inputs: PartialInputs, salt: &[u8; HIDDEN_SIZE], defer_rollback_protection: bool, next_handover_size: usize, next_handover_align: usize, ) -> Result<&'a [u8], RebootReason>197 fn perform_dice_derivation<'a>(
198 dice_handover_bytes: &[u8],
199 dice_context: DiceContext,
200 dice_inputs: PartialInputs,
201 salt: &[u8; HIDDEN_SIZE],
202 defer_rollback_protection: bool,
203 next_handover_size: usize,
204 next_handover_align: usize,
205 ) -> Result<&'a [u8], RebootReason> {
206 let next_dice_handover = heap::aligned_boxed_slice(next_handover_size, next_handover_align)
207 .ok_or_else(|| {
208 error!("Failed to allocate the next-stage DICE handover");
209 RebootReason::InternalError
210 })?;
211 // By leaking the slice, its content will be left behind for the next stage.
212 let next_dice_handover = Box::leak(next_dice_handover);
213
214 dice_inputs
215 .write_next_handover(
216 dice_handover_bytes.as_ref(),
217 salt,
218 defer_rollback_protection,
219 next_dice_handover,
220 dice_context,
221 )
222 .map_err(|e| {
223 error!("Failed to derive next-stage DICE secrets: {e:?}");
224 RebootReason::SecretDerivationError
225 })?;
226 flush(next_dice_handover);
227 Ok(next_dice_handover)
228 }
229
perform_verified_boot<'a>( signed_kernel: &[u8], ramdisk: Option<&[u8]>, ) -> Result<(VerifiedBootData<'a>, bool, usize), RebootReason>230 fn perform_verified_boot<'a>(
231 signed_kernel: &[u8],
232 ramdisk: Option<&[u8]>,
233 ) -> Result<(VerifiedBootData<'a>, bool, usize), RebootReason> {
234 let verified_boot_data = verify_payload(signed_kernel, ramdisk, PUBLIC_KEY).map_err(|e| {
235 error!("Failed to verify the payload: {e}");
236 RebootReason::PayloadVerificationError
237 })?;
238 let debuggable = verified_boot_data.debug_level != DebugLevel::None;
239 if debuggable {
240 info!("Successfully verified a debuggable payload.");
241 info!("Please disregard any previous libavb ERROR about initrd_normal.");
242 }
243 let guest_page_size = verified_boot_data.page_size.unwrap_or(SIZE_4KB);
244
245 Ok((verified_boot_data, debuggable, guest_page_size))
246 }
247
248 // Get the "salt" which is one of the input for DICE derivation.
249 // This provides differentiation of secrets for different VM instances with same payloads.
salt_from_instance_id(fdt: &Fdt) -> Result<Option<Hidden>, RebootReason>250 fn salt_from_instance_id(fdt: &Fdt) -> Result<Option<Hidden>, RebootReason> {
251 let Some(id) = read_instance_id(fdt).map_err(|e| {
252 error!("Failed to get instance-id in DT: {e}");
253 RebootReason::InvalidFdt
254 })?
255 else {
256 return Ok(None);
257 };
258 let salt = Digester::sha512()
259 .digest(&[&b"InstanceId:"[..], id].concat())
260 .map_err(|e| {
261 error!("Failed to get digest of instance-id: {e}");
262 RebootReason::InternalError
263 })?
264 .try_into()
265 .map_err(|_| RebootReason::InternalError)?;
266 Ok(Some(salt))
267 }
268