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