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 bcc;
23 mod bootargs;
24 mod config;
25 mod device_assignment;
26 mod dice;
27 mod entry;
28 mod exceptions;
29 mod fdt;
30 mod gpt;
31 mod instance;
32 mod memory;
33
34 use crate::bcc::Bcc;
35 use crate::dice::PartialInputs;
36 use crate::entry::RebootReason;
37 use crate::fdt::{modify_for_next_stage, sanitize_device_tree};
38 use crate::instance::EntryBody;
39 use crate::instance::Error as InstanceError;
40 use crate::instance::{get_recorded_entry, record_instance_entry};
41 use alloc::borrow::Cow;
42 use alloc::boxed::Box;
43 use bssl_avf::Digester;
44 use core::ops::Range;
45 use cstr::cstr;
46 use diced_open_dice::{bcc_handover_parse, DiceArtifacts, DiceContext, Hidden, VM_KEY_ALGORITHM};
47 use libfdt::{Fdt, FdtNode};
48 use log::{debug, error, info, trace, warn};
49 use pvmfw_avb::verify_payload;
50 use pvmfw_avb::Capability;
51 use pvmfw_avb::DebugLevel;
52 use pvmfw_embedded_key::PUBLIC_KEY;
53 use vmbase::fdt::pci::{PciError, PciInfo};
54 use vmbase::heap;
55 use vmbase::memory::{flush, init_shared_pool, SIZE_4KB};
56 use vmbase::rand;
57 use vmbase::virtio::pci;
58
main( untrusted_fdt: &mut Fdt, signed_kernel: &[u8], ramdisk: Option<&[u8]>, current_bcc_handover: &[u8], mut debug_policy: Option<&[u8]>, vm_dtbo: Option<&mut [u8]>, vm_ref_dt: Option<&[u8]>, ) -> Result<(Range<usize>, bool), RebootReason>59 fn main(
60 untrusted_fdt: &mut Fdt,
61 signed_kernel: &[u8],
62 ramdisk: Option<&[u8]>,
63 current_bcc_handover: &[u8],
64 mut debug_policy: Option<&[u8]>,
65 vm_dtbo: Option<&mut [u8]>,
66 vm_ref_dt: Option<&[u8]>,
67 ) -> Result<(Range<usize>, bool), RebootReason> {
68 info!("pVM firmware");
69 debug!("FDT: {:?}", untrusted_fdt.as_ptr());
70 debug!("Signed kernel: {:?} ({:#x} bytes)", signed_kernel.as_ptr(), signed_kernel.len());
71 debug!("AVB public key: addr={:?}, size={:#x} ({1})", PUBLIC_KEY.as_ptr(), PUBLIC_KEY.len());
72 if let Some(rd) = ramdisk {
73 debug!("Ramdisk: {:?} ({:#x} bytes)", rd.as_ptr(), rd.len());
74 } else {
75 debug!("Ramdisk: None");
76 }
77
78 let bcc_handover = bcc_handover_parse(current_bcc_handover).map_err(|e| {
79 error!("Invalid BCC Handover: {e:?}");
80 RebootReason::InvalidBcc
81 })?;
82 trace!("BCC: {bcc_handover:x?}");
83
84 let cdi_seal = bcc_handover.cdi_seal();
85
86 let bcc = Bcc::new(bcc_handover.bcc()).map_err(|e| {
87 error!("{e}");
88 RebootReason::InvalidBcc
89 })?;
90
91 // The bootloader should never pass us a debug policy when the boot is secure (the bootloader
92 // is locked). If it gets it wrong, disregard it & log it, to avoid it causing problems.
93 if debug_policy.is_some() && !bcc.is_debug_mode() {
94 warn!("Ignoring debug policy, BCC does not indicate Debug mode");
95 debug_policy = None;
96 }
97
98 let verified_boot_data = verify_payload(signed_kernel, ramdisk, PUBLIC_KEY).map_err(|e| {
99 error!("Failed to verify the payload: {e}");
100 RebootReason::PayloadVerificationError
101 })?;
102 let debuggable = verified_boot_data.debug_level != DebugLevel::None;
103 if debuggable {
104 info!("Successfully verified a debuggable payload.");
105 info!("Please disregard any previous libavb ERROR about initrd_normal.");
106 }
107
108 let guest_page_size = verified_boot_data.page_size.unwrap_or(SIZE_4KB);
109 let fdt_info = sanitize_device_tree(untrusted_fdt, vm_dtbo, vm_ref_dt, guest_page_size)?;
110 let fdt = untrusted_fdt; // DT has now been sanitized.
111 let pci_info = PciInfo::from_fdt(fdt).map_err(handle_pci_error)?;
112 debug!("PCI: {:#x?}", pci_info);
113 // Set up PCI bus for VirtIO devices.
114 let mut pci_root = pci::initialize(pci_info).map_err(|e| {
115 error!("Failed to initialize PCI: {e}");
116 RebootReason::InternalError
117 })?;
118 init_shared_pool(fdt_info.swiotlb_info.fixed_range()).map_err(|e| {
119 error!("Failed to initialize shared pool: {e}");
120 RebootReason::InternalError
121 })?;
122
123 let next_bcc_size = guest_page_size;
124 let next_bcc = heap::aligned_boxed_slice(next_bcc_size, guest_page_size).ok_or_else(|| {
125 error!("Failed to allocate the next-stage BCC");
126 RebootReason::InternalError
127 })?;
128 // By leaking the slice, its content will be left behind for the next stage.
129 let next_bcc = Box::leak(next_bcc);
130
131 let dice_inputs = PartialInputs::new(&verified_boot_data).map_err(|e| {
132 error!("Failed to compute partial DICE inputs: {e:?}");
133 RebootReason::InternalError
134 })?;
135
136 let instance_hash = if cfg!(llpvm_changes) { Some(salt_from_instance_id(fdt)?) } else { None };
137 let defer_rollback_protection = should_defer_rollback_protection(fdt)?
138 && verified_boot_data.has_capability(Capability::SecretkeeperProtection);
139 let (new_instance, salt) = if defer_rollback_protection {
140 info!("Guest OS is capable of Secretkeeper protection, deferring rollback protection");
141 // rollback_index of the image is used as security_version and is expected to be > 0 to
142 // discourage implicit allocation.
143 if verified_boot_data.rollback_index == 0 {
144 error!("Expected positive rollback_index, found 0");
145 return Err(RebootReason::InvalidPayload);
146 };
147 (false, instance_hash.unwrap())
148 } else if verified_boot_data.has_capability(Capability::RemoteAttest) {
149 info!("Service VM capable of remote attestation detected, performing version checks");
150 if service_vm_version::VERSION != verified_boot_data.rollback_index {
151 // For RKP VM, we only boot if the version in the AVB footer of its kernel matches
152 // the one embedded in pvmfw at build time.
153 // This prevents the pvmfw from booting a roll backed RKP VM.
154 error!(
155 "Service VM version mismatch: expected {}, found {}",
156 service_vm_version::VERSION,
157 verified_boot_data.rollback_index
158 );
159 return Err(RebootReason::InvalidPayload);
160 }
161 (false, instance_hash.unwrap())
162 } else if verified_boot_data.has_capability(Capability::TrustySecurityVm) {
163 // The rollback protection of Trusty VMs are handled by AuthMgr, so we don't need to
164 // handle it here.
165 info!("Trusty Security VM detected");
166 (false, instance_hash.unwrap())
167 } else {
168 info!("Fallback to instance.img based rollback checks");
169 let (recorded_entry, mut instance_img, header_index) =
170 get_recorded_entry(&mut pci_root, cdi_seal).map_err(|e| {
171 error!("Failed to get entry from instance.img: {e}");
172 RebootReason::InternalError
173 })?;
174 let (new_instance, salt) = if let Some(entry) = recorded_entry {
175 check_dice_measurements_match_entry(&dice_inputs, &entry)?;
176 let salt = instance_hash.unwrap_or(entry.salt);
177 (false, salt)
178 } else {
179 // New instance!
180 let salt = instance_hash.map_or_else(rand::random_array, Ok).map_err(|e| {
181 error!("Failed to generated instance.img salt: {e}");
182 RebootReason::InternalError
183 })?;
184
185 let entry = EntryBody::new(&dice_inputs, &salt);
186 record_instance_entry(&entry, cdi_seal, &mut instance_img, header_index).map_err(
187 |e| {
188 error!("Failed to get recorded entry in instance.img: {e}");
189 RebootReason::InternalError
190 },
191 )?;
192 (true, salt)
193 };
194 (new_instance, salt)
195 };
196 trace!("Got salt for instance: {salt:x?}");
197
198 let new_bcc_handover = if cfg!(dice_changes) {
199 Cow::Borrowed(current_bcc_handover)
200 } else {
201 // It is possible that the DICE chain we were given is rooted in the UDS. We do not want to
202 // give such a chain to the payload, or even the associated CDIs. So remove the
203 // entire chain we were given and taint the CDIs. Note that the resulting CDIs are
204 // still deterministically derived from those we received, so will vary iff they do.
205 // TODO(b/280405545): Remove this post Android 14.
206 let truncated_bcc_handover = bcc::truncate(bcc_handover).map_err(|e| {
207 error!("{e}");
208 RebootReason::InternalError
209 })?;
210 Cow::Owned(truncated_bcc_handover)
211 };
212
213 trace!("BCC leaf subject public key algorithm: {:?}", bcc.leaf_subject_pubkey().cose_alg);
214
215 let dice_context = DiceContext {
216 authority_algorithm: bcc.leaf_subject_pubkey().cose_alg.try_into().map_err(|e| {
217 error!("{e}");
218 RebootReason::InternalError
219 })?,
220 subject_algorithm: VM_KEY_ALGORITHM,
221 };
222 dice_inputs
223 .write_next_bcc(
224 new_bcc_handover.as_ref(),
225 &salt,
226 instance_hash,
227 defer_rollback_protection,
228 next_bcc,
229 dice_context,
230 )
231 .map_err(|e| {
232 error!("Failed to derive next-stage DICE secrets: {e:?}");
233 RebootReason::SecretDerivationError
234 })?;
235 flush(next_bcc);
236
237 let kaslr_seed = u64::from_ne_bytes(rand::random_array().map_err(|e| {
238 error!("Failed to generated guest KASLR seed: {e}");
239 RebootReason::InternalError
240 })?);
241 let strict_boot = true;
242 modify_for_next_stage(
243 fdt,
244 next_bcc,
245 new_instance,
246 strict_boot,
247 debug_policy,
248 debuggable,
249 kaslr_seed,
250 )
251 .map_err(|e| {
252 error!("Failed to configure device tree: {e}");
253 RebootReason::InternalError
254 })?;
255
256 info!("Starting payload...");
257
258 let bcc_range = {
259 let r = next_bcc.as_ptr_range();
260 (r.start as usize)..(r.end as usize)
261 };
262
263 Ok((bcc_range, debuggable))
264 }
265
check_dice_measurements_match_entry( dice_inputs: &PartialInputs, entry: &EntryBody, ) -> Result<(), RebootReason>266 fn check_dice_measurements_match_entry(
267 dice_inputs: &PartialInputs,
268 entry: &EntryBody,
269 ) -> Result<(), RebootReason> {
270 ensure_dice_measurements_match_entry(dice_inputs, entry).map_err(|e| {
271 error!(
272 "Dice measurements do not match recorded entry. \
273 This may be because of update: {e}"
274 );
275 RebootReason::InternalError
276 })?;
277
278 Ok(())
279 }
280
ensure_dice_measurements_match_entry( dice_inputs: &PartialInputs, entry: &EntryBody, ) -> Result<(), InstanceError>281 fn ensure_dice_measurements_match_entry(
282 dice_inputs: &PartialInputs,
283 entry: &EntryBody,
284 ) -> Result<(), InstanceError> {
285 if entry.code_hash != dice_inputs.code_hash {
286 Err(InstanceError::RecordedCodeHashMismatch)
287 } else if entry.auth_hash != dice_inputs.auth_hash {
288 Err(InstanceError::RecordedAuthHashMismatch)
289 } else if entry.mode() != dice_inputs.mode {
290 Err(InstanceError::RecordedDiceModeMismatch)
291 } else {
292 Ok(())
293 }
294 }
295
296 // Get the "salt" which is one of the input for DICE derivation.
297 // This provides differentiation of secrets for different VM instances with same payloads.
salt_from_instance_id(fdt: &Fdt) -> Result<Hidden, RebootReason>298 fn salt_from_instance_id(fdt: &Fdt) -> Result<Hidden, RebootReason> {
299 let id = instance_id(fdt)?;
300 let salt = Digester::sha512()
301 .digest(&[&b"InstanceId:"[..], id].concat())
302 .map_err(|e| {
303 error!("Failed to get digest of instance-id: {e}");
304 RebootReason::InternalError
305 })?
306 .try_into()
307 .map_err(|_| RebootReason::InternalError)?;
308 Ok(salt)
309 }
310
instance_id(fdt: &Fdt) -> Result<&[u8], RebootReason>311 fn instance_id(fdt: &Fdt) -> Result<&[u8], RebootReason> {
312 let node = avf_untrusted_node(fdt)?;
313 let id = node.getprop(cstr!("instance-id")).map_err(|e| {
314 error!("Failed to get instance-id in DT: {e}");
315 RebootReason::InvalidFdt
316 })?;
317 id.ok_or_else(|| {
318 error!("Missing instance-id");
319 RebootReason::InvalidFdt
320 })
321 }
322
should_defer_rollback_protection(fdt: &Fdt) -> Result<bool, RebootReason>323 fn should_defer_rollback_protection(fdt: &Fdt) -> Result<bool, RebootReason> {
324 let node = avf_untrusted_node(fdt)?;
325 let defer_rbp = node
326 .getprop(cstr!("defer-rollback-protection"))
327 .map_err(|e| {
328 error!("Failed to get defer-rollback-protection property in DT: {e}");
329 RebootReason::InvalidFdt
330 })?
331 .is_some();
332 Ok(defer_rbp)
333 }
334
avf_untrusted_node(fdt: &Fdt) -> Result<FdtNode, RebootReason>335 fn avf_untrusted_node(fdt: &Fdt) -> Result<FdtNode, RebootReason> {
336 let node = fdt.node(cstr!("/avf/untrusted")).map_err(|e| {
337 error!("Failed to get /avf/untrusted node: {e}");
338 RebootReason::InvalidFdt
339 })?;
340 node.ok_or_else(|| {
341 error!("/avf/untrusted node is missing in DT");
342 RebootReason::InvalidFdt
343 })
344 }
345
346 /// Logs the given PCI error and returns the appropriate `RebootReason`.
handle_pci_error(e: PciError) -> RebootReason347 fn handle_pci_error(e: PciError) -> RebootReason {
348 error!("{}", e);
349 match e {
350 PciError::FdtErrorPci(_)
351 | PciError::FdtNoPci
352 | PciError::FdtErrorReg(_)
353 | PciError::FdtMissingReg
354 | PciError::FdtRegEmpty
355 | PciError::FdtRegMissingSize
356 | PciError::CamWrongSize(_)
357 | PciError::FdtErrorRanges(_)
358 | PciError::FdtMissingRanges
359 | PciError::RangeAddressMismatch { .. }
360 | PciError::NoSuitableRange => RebootReason::InvalidFdt,
361 }
362 }
363