Merge changes from topic "bootstrap-service-virtualization-jar" into main
* changes:
Track dependency between llpvm, remote attestation and dice flags
Add a VirtualizationSystemService that runs inside system_server
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index e577f40..e8ef195 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -949,7 +949,8 @@
@FlaggedApi("RELEASE_AVF_ENABLE_VENDOR_MODULES")
@NonNull
public Builder setVendorDiskImage(@NonNull File vendorDiskImage) {
- mVendorDiskImage = vendorDiskImage;
+ mVendorDiskImage =
+ requireNonNull(vendorDiskImage, "vendor disk image must not be null");
return this;
}
diff --git a/microdroid_manager/src/vm_secret.rs b/microdroid_manager/src/vm_secret.rs
index 35acdd3..0e1ec71 100644
--- a/microdroid_manager/src/vm_secret.rs
+++ b/microdroid_manager/src/vm_secret.rs
@@ -20,7 +20,7 @@
use secretkeeper_comm::data_types::request::Request;
use binder::{Strong};
use coset::CborSerializable;
-use dice_policy_builder::{ConstraintSpec, ConstraintType, policy_for_dice_chain, MissingAction};
+use dice_policy_builder::{CertIndex, ConstraintSpec, ConstraintType, policy_for_dice_chain, MissingAction, WILDCARD_FULL_ARRAY};
use diced_open_dice::{DiceArtifacts, OwnedDiceArtifacts};
use keystore2_crypto::ZVec;
use openssl::hkdf::hkdf;
@@ -41,6 +41,12 @@
const MODE: i64 = -4670551;
const CONFIG_DESC: i64 = -4670548;
const SECURITY_VERSION: i64 = -70005;
+const SUBCOMPONENT_DESCRIPTORS: i64 = -71002;
+const SUBCOMPONENT_SECURITY_VERSION: i64 = 2;
+const SUBCOMPONENT_AUTHORITY_HASH: i64 = 4;
+// Index of DiceChainEntry corresponding to Payload (relative to the end considering DICE Chain
+// as an array)
+const PAYLOAD_INDEX_FROM_END: usize = 0;
// Generated using hexdump -vn32 -e'14/1 "0x%02X, " 1 "\n"' /dev/urandom
const SALT_ENCRYPTED_STORE: &[u8] = &[
@@ -161,15 +167,51 @@
// components may chose to prevent booting of rollback images for ex, ABL is expected to provide
// rollback protection of pvmfw. Such components may chose to not put SECURITY_VERSION in the
// corresponding DiceChainEntry.
-// TODO(b/291219197) : Add constraints on Extra apks as well!
+// 4. For each Subcomponent on the last DiceChainEntry (which corresponds to VM payload, See
+// microdroid_manager/src/vm_config.cddl):
+// - GreaterOrEqual on SECURITY_VERSION (Required)
+// - ExactMatch on AUTHORITY_HASH (Required).
fn sealing_policy(dice: &[u8]) -> Result<Vec<u8>, String> {
let constraint_spec = [
- ConstraintSpec::new(ConstraintType::ExactMatch, vec![AUTHORITY_HASH], MissingAction::Fail),
- ConstraintSpec::new(ConstraintType::ExactMatch, vec![MODE], MissingAction::Fail),
+ ConstraintSpec::new(
+ ConstraintType::ExactMatch,
+ vec![AUTHORITY_HASH],
+ MissingAction::Fail,
+ CertIndex::All,
+ ),
+ ConstraintSpec::new(
+ ConstraintType::ExactMatch,
+ vec![MODE],
+ MissingAction::Fail,
+ CertIndex::All,
+ ),
ConstraintSpec::new(
ConstraintType::GreaterOrEqual,
vec![CONFIG_DESC, SECURITY_VERSION],
MissingAction::Ignore,
+ CertIndex::All,
+ ),
+ ConstraintSpec::new(
+ ConstraintType::GreaterOrEqual,
+ vec![
+ CONFIG_DESC,
+ SUBCOMPONENT_DESCRIPTORS,
+ WILDCARD_FULL_ARRAY,
+ SUBCOMPONENT_SECURITY_VERSION,
+ ],
+ MissingAction::Fail,
+ CertIndex::FromEnd(PAYLOAD_INDEX_FROM_END),
+ ),
+ ConstraintSpec::new(
+ ConstraintType::ExactMatch,
+ vec![
+ CONFIG_DESC,
+ SUBCOMPONENT_DESCRIPTORS,
+ WILDCARD_FULL_ARRAY,
+ SUBCOMPONENT_AUTHORITY_HASH,
+ ],
+ MissingAction::Fail,
+ CertIndex::FromEnd(PAYLOAD_INDEX_FROM_END),
),
];
diff --git a/pvmfw/avb/Android.bp b/pvmfw/avb/Android.bp
index 6df1c4d..6101a0c 100644
--- a/pvmfw/avb/Android.bp
+++ b/pvmfw/avb/Android.bp
@@ -9,7 +9,6 @@
srcs: ["src/lib.rs"],
prefer_rlib: true,
rustlibs: [
- "libavb_bindgen_nostd",
"libavb_rs_nostd",
"libtinyvec_nostd",
],
diff --git a/pvmfw/avb/src/descriptor.rs b/pvmfw/avb/src/descriptor.rs
deleted file mode 100644
index a3db0e5..0000000
--- a/pvmfw/avb/src/descriptor.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2023, The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! Structs and functions relating to the descriptors.
-
-mod collection;
-mod common;
-mod hash;
-mod property;
-
-pub(crate) use collection::Descriptors;
-pub use hash::Digest;
diff --git a/pvmfw/avb/src/descriptor/collection.rs b/pvmfw/avb/src/descriptor/collection.rs
deleted file mode 100644
index 6784758..0000000
--- a/pvmfw/avb/src/descriptor/collection.rs
+++ /dev/null
@@ -1,190 +0,0 @@
-// Copyright 2023, The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! Structs and functions relating to the descriptor collection.
-
-use super::common::get_valid_descriptor;
-use super::hash::HashDescriptor;
-use super::property::PropertyDescriptor;
-use crate::partition::PartitionName;
-use crate::utils::{to_usize, usize_checked_add};
-use crate::PvmfwVerifyError;
-use avb::{IoError, IoResult, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData};
-use avb_bindgen::{
- avb_descriptor_foreach, avb_descriptor_validate_and_byteswap, AvbDescriptor, AvbDescriptorTag,
-};
-use core::{ffi::c_void, mem::size_of, slice};
-use tinyvec::ArrayVec;
-
-/// `Descriptors` can have at most one `HashDescriptor` per known partition and at most one
-/// `PropertyDescriptor`.
-#[derive(Default)]
-pub(crate) struct Descriptors<'a> {
- hash_descriptors: ArrayVec<[HashDescriptor<'a>; PartitionName::NUM_OF_KNOWN_PARTITIONS]>,
- prop_descriptor: Option<PropertyDescriptor<'a>>,
-}
-
-impl<'a> Descriptors<'a> {
- /// Builds `Descriptors` from `VbmetaData`.
- /// Returns an error if the given `VbmetaData` contains non-hash descriptor, hash
- /// descriptor of unknown `PartitionName` or duplicated hash descriptors.
- pub(crate) fn from_vbmeta(vbmeta: &'a VbmetaData) -> Result<Self, PvmfwVerifyError> {
- let mut res: IoResult<Self> = Ok(Self::default());
- // SAFETY: It is safe as `vbmeta.data()` contains a valid VBMeta structure.
- let output = unsafe {
- avb_descriptor_foreach(
- vbmeta.data().as_ptr(),
- vbmeta.data().len(),
- Some(check_and_save_descriptor),
- &mut res as *mut _ as *mut c_void,
- )
- };
- if output == res.is_ok() {
- res.map_err(PvmfwVerifyError::InvalidDescriptors)
- } else {
- Err(SlotVerifyError::InvalidMetadata.into())
- }
- }
-
- pub(crate) fn num_hash_descriptor(&self) -> usize {
- self.hash_descriptors.len()
- }
-
- /// Finds the `HashDescriptor` for the given `PartitionName`.
- /// Throws an error if no corresponding descriptor found.
- pub(crate) fn find_hash_descriptor(
- &self,
- partition_name: PartitionName,
- ) -> SlotVerifyNoDataResult<&HashDescriptor> {
- self.hash_descriptors
- .iter()
- .find(|d| d.partition_name == partition_name)
- .ok_or(SlotVerifyError::InvalidMetadata)
- }
-
- pub(crate) fn has_property_descriptor(&self) -> bool {
- self.prop_descriptor.is_some()
- }
-
- pub(crate) fn find_property_value(&self, key: &[u8]) -> Option<&[u8]> {
- self.prop_descriptor.as_ref().filter(|desc| desc.key == key).map(|desc| desc.value)
- }
-
- fn push(&mut self, descriptor: Descriptor<'a>) -> IoResult<()> {
- match descriptor {
- Descriptor::Hash(d) => self.push_hash_descriptor(d),
- Descriptor::Property(d) => self.push_property_descriptor(d),
- }
- }
-
- fn push_hash_descriptor(&mut self, descriptor: HashDescriptor<'a>) -> IoResult<()> {
- if self.hash_descriptors.iter().any(|d| d.partition_name == descriptor.partition_name) {
- return Err(IoError::Io);
- }
- self.hash_descriptors.push(descriptor);
- Ok(())
- }
-
- fn push_property_descriptor(&mut self, descriptor: PropertyDescriptor<'a>) -> IoResult<()> {
- if self.prop_descriptor.is_some() {
- return Err(IoError::Io);
- }
- self.prop_descriptor.replace(descriptor);
- Ok(())
- }
-}
-
-/// # Safety
-///
-/// Behavior is undefined if any of the following conditions are violated:
-/// * The `descriptor` pointer must be non-null and points to a valid `AvbDescriptor` struct.
-/// * The `user_data` pointer must be non-null, points to a valid `IoResult<Descriptors>`
-/// struct and is initialized.
-unsafe extern "C" fn check_and_save_descriptor(
- descriptor: *const AvbDescriptor,
- user_data: *mut c_void,
-) -> bool {
- // SAFETY: It is safe because the caller ensures that `user_data` points to a valid struct and
- // is initialized.
- let Some(res) = (unsafe { (user_data as *mut IoResult<Descriptors>).as_mut() }) else {
- return false;
- };
- let Ok(descriptors) = res else {
- return false;
- };
- // SAFETY: It is safe because the caller ensures that the `descriptor` pointer is non-null
- // and valid.
- unsafe { try_check_and_save_descriptor(descriptor, descriptors) }.map_or_else(
- |e| {
- *res = Err(e);
- false
- },
- |_| true,
- )
-}
-
-/// # Safety
-///
-/// Behavior is undefined if any of the following conditions are violated:
-/// * The `descriptor` pointer must be non-null and points to a valid `AvbDescriptor` struct.
-unsafe fn try_check_and_save_descriptor(
- descriptor: *const AvbDescriptor,
- descriptors: &mut Descriptors,
-) -> IoResult<()> {
- // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null pointer
- // pointing to a valid struct.
- let descriptor = unsafe { Descriptor::from_descriptor_ptr(descriptor)? };
- descriptors.push(descriptor)
-}
-
-enum Descriptor<'a> {
- Hash(HashDescriptor<'a>),
- Property(PropertyDescriptor<'a>),
-}
-
-impl<'a> Descriptor<'a> {
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> IoResult<Self> {
- let avb_descriptor =
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- unsafe { get_valid_descriptor(descriptor, avb_descriptor_validate_and_byteswap)? };
- let len = usize_checked_add(
- size_of::<AvbDescriptor>(),
- to_usize(avb_descriptor.num_bytes_following)?,
- )?;
- // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null pointer
- // pointing to a valid struct.
- let data = unsafe { slice::from_raw_parts(descriptor as *const u8, len) };
- match avb_descriptor.tag.try_into() {
- Ok(AvbDescriptorTag::AVB_DESCRIPTOR_TAG_HASH) => {
- // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null
- // pointer pointing to a valid struct.
- let descriptor = unsafe { HashDescriptor::from_descriptor_ptr(descriptor, data)? };
- Ok(Self::Hash(descriptor))
- }
- Ok(AvbDescriptorTag::AVB_DESCRIPTOR_TAG_PROPERTY) => {
- let descriptor =
- // SAFETY: It is safe because the caller ensures that `descriptor` is a non-null
- // pointer pointing to a valid struct.
- unsafe { PropertyDescriptor::from_descriptor_ptr(descriptor, data)? };
- Ok(Self::Property(descriptor))
- }
- _ => Err(IoError::NoSuchValue),
- }
- }
-}
diff --git a/pvmfw/avb/src/descriptor/common.rs b/pvmfw/avb/src/descriptor/common.rs
deleted file mode 100644
index 6063a7c..0000000
--- a/pvmfw/avb/src/descriptor/common.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2023, The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! Structs and functions used by all the descriptors.
-
-use crate::utils::is_not_null;
-use avb::{IoError, IoResult};
-use core::mem::MaybeUninit;
-
-/// # Safety
-///
-/// Behavior is undefined if any of the following conditions are violated:
-/// * The `descriptor_ptr` pointer must be non-null and point to a valid `AvbDescriptor`.
-pub(super) unsafe fn get_valid_descriptor<T>(
- descriptor_ptr: *const T,
- descriptor_validate_and_byteswap: unsafe extern "C" fn(src: *const T, dest: *mut T) -> bool,
-) -> IoResult<T> {
- is_not_null(descriptor_ptr)?;
- // SAFETY: It is safe because the caller ensures that `descriptor_ptr` is a non-null pointer
- // pointing to a valid struct.
- let descriptor = unsafe {
- let mut desc = MaybeUninit::uninit();
- if !descriptor_validate_and_byteswap(descriptor_ptr, desc.as_mut_ptr()) {
- return Err(IoError::Io);
- }
- desc.assume_init()
- };
- Ok(descriptor)
-}
diff --git a/pvmfw/avb/src/descriptor/hash.rs b/pvmfw/avb/src/descriptor/hash.rs
deleted file mode 100644
index 35db66d..0000000
--- a/pvmfw/avb/src/descriptor/hash.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright 2023, The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! Structs and functions relating to the hash descriptor.
-
-use super::common::get_valid_descriptor;
-use crate::partition::PartitionName;
-use crate::utils::{to_usize, usize_checked_add};
-use avb::{IoError, IoResult};
-use avb_bindgen::{
- avb_hash_descriptor_validate_and_byteswap, AvbDescriptor, AvbHashDescriptor,
- AVB_SHA256_DIGEST_SIZE,
-};
-use core::{mem::size_of, ops::Range};
-
-/// Digest type for kernel and initrd.
-pub type Digest = [u8; AVB_SHA256_DIGEST_SIZE as usize];
-
-pub(crate) struct HashDescriptor<'a> {
- pub(crate) partition_name: PartitionName,
- pub(crate) digest: &'a Digest,
-}
-
-impl<'a> Default for HashDescriptor<'a> {
- fn default() -> Self {
- Self { partition_name: Default::default(), digest: &Self::EMPTY_DIGEST }
- }
-}
-
-impl<'a> HashDescriptor<'a> {
- const EMPTY_DIGEST: Digest = [0u8; AVB_SHA256_DIGEST_SIZE as usize];
-
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- pub(super) unsafe fn from_descriptor_ptr(
- descriptor: *const AvbDescriptor,
- data: &'a [u8],
- ) -> IoResult<Self> {
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- let h = unsafe { HashDescriptorHeader::from_descriptor_ptr(descriptor)? };
- let partition_name = data
- .get(h.partition_name_range()?)
- .ok_or(IoError::RangeOutsidePartition)?
- .try_into()?;
- let digest = data
- .get(h.digest_range()?)
- .ok_or(IoError::RangeOutsidePartition)?
- .try_into()
- .map_err(|_| IoError::InvalidValueSize)?;
- Ok(Self { partition_name, digest })
- }
-}
-
-struct HashDescriptorHeader(AvbHashDescriptor);
-
-impl HashDescriptorHeader {
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> IoResult<Self> {
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- unsafe {
- get_valid_descriptor(
- descriptor as *const AvbHashDescriptor,
- avb_hash_descriptor_validate_and_byteswap,
- )
- .map(Self)
- }
- }
-
- fn partition_name_end(&self) -> IoResult<usize> {
- usize_checked_add(size_of::<AvbHashDescriptor>(), to_usize(self.0.partition_name_len)?)
- }
-
- fn partition_name_range(&self) -> IoResult<Range<usize>> {
- let start = size_of::<AvbHashDescriptor>();
- Ok(start..(self.partition_name_end()?))
- }
-
- fn digest_range(&self) -> IoResult<Range<usize>> {
- let start = usize_checked_add(self.partition_name_end()?, to_usize(self.0.salt_len)?)?;
- let end = usize_checked_add(start, to_usize(self.0.digest_len)?)?;
- Ok(start..end)
- }
-}
diff --git a/pvmfw/avb/src/descriptor/property.rs b/pvmfw/avb/src/descriptor/property.rs
deleted file mode 100644
index 8145d64..0000000
--- a/pvmfw/avb/src/descriptor/property.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2023, The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! Structs and functions relating to the property descriptor.
-
-use super::common::get_valid_descriptor;
-use crate::utils::{to_usize, usize_checked_add};
-use avb::{IoError, IoResult};
-use avb_bindgen::{
- avb_property_descriptor_validate_and_byteswap, AvbDescriptor, AvbPropertyDescriptor,
-};
-use core::mem::size_of;
-
-pub(super) struct PropertyDescriptor<'a> {
- pub(super) key: &'a [u8],
- pub(super) value: &'a [u8],
-}
-
-impl<'a> PropertyDescriptor<'a> {
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- pub(super) unsafe fn from_descriptor_ptr(
- descriptor: *const AvbDescriptor,
- data: &'a [u8],
- ) -> IoResult<Self> {
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- let h = unsafe { PropertyDescriptorHeader::from_descriptor_ptr(descriptor)? };
- let key = Self::get_valid_slice(data, h.key_start(), h.key_end()?)?;
- let value = Self::get_valid_slice(data, h.value_start()?, h.value_end()?)?;
- Ok(Self { key, value })
- }
-
- fn get_valid_slice(data: &[u8], start: usize, end: usize) -> IoResult<&[u8]> {
- const NUL_BYTE: u8 = b'\0';
-
- match data.get(end) {
- Some(&NUL_BYTE) => data.get(start..end).ok_or(IoError::RangeOutsidePartition),
- _ => Err(IoError::NoSuchValue),
- }
- }
-}
-
-struct PropertyDescriptorHeader(AvbPropertyDescriptor);
-
-impl PropertyDescriptorHeader {
- /// # Safety
- ///
- /// Behavior is undefined if any of the following conditions are violated:
- /// * The `descriptor` pointer must be non-null and point to a valid `AvbDescriptor`.
- unsafe fn from_descriptor_ptr(descriptor: *const AvbDescriptor) -> IoResult<Self> {
- // SAFETY: It is safe as the raw pointer `descriptor` is non-null and points to
- // a valid `AvbDescriptor`.
- unsafe {
- get_valid_descriptor(
- descriptor as *const AvbPropertyDescriptor,
- avb_property_descriptor_validate_and_byteswap,
- )
- .map(Self)
- }
- }
-
- fn key_start(&self) -> usize {
- size_of::<AvbPropertyDescriptor>()
- }
-
- fn key_end(&self) -> IoResult<usize> {
- usize_checked_add(self.key_start(), to_usize(self.0.key_num_bytes)?)
- }
-
- fn value_start(&self) -> IoResult<usize> {
- // There is a NUL byte between key and value.
- usize_checked_add(self.key_end()?, 1)
- }
-
- fn value_end(&self) -> IoResult<usize> {
- usize_checked_add(self.value_start()?, to_usize(self.0.value_num_bytes)?)
- }
-}
diff --git a/pvmfw/avb/src/error.rs b/pvmfw/avb/src/error.rs
index 4e3f27e..2e1950a 100644
--- a/pvmfw/avb/src/error.rs
+++ b/pvmfw/avb/src/error.rs
@@ -15,7 +15,7 @@
//! This module contains the error thrown by the payload verification API
//! and other errors used in the library.
-use avb::{IoError, SlotVerifyError};
+use avb::{DescriptorError, SlotVerifyError};
use core::fmt;
/// Wrapper around `SlotVerifyError` to add custom pvmfw errors.
@@ -25,7 +25,7 @@
/// Passthrough `SlotVerifyError` with no `SlotVerifyData`.
AvbError(SlotVerifyError<'static>),
/// VBMeta has invalid descriptors.
- InvalidDescriptors(IoError),
+ InvalidDescriptors(DescriptorError),
/// Unknown vbmeta property.
UnknownVbmetaProperty,
}
@@ -37,6 +37,12 @@
}
}
+impl From<DescriptorError> for PvmfwVerifyError {
+ fn from(error: DescriptorError) -> Self {
+ Self::InvalidDescriptors(error)
+ }
+}
+
impl fmt::Display for PvmfwVerifyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
diff --git a/pvmfw/avb/src/lib.rs b/pvmfw/avb/src/lib.rs
index 9c3fe11..fd68652 100644
--- a/pvmfw/avb/src/lib.rs
+++ b/pvmfw/avb/src/lib.rs
@@ -18,13 +18,10 @@
extern crate alloc;
-mod descriptor;
mod error;
mod ops;
mod partition;
-mod utils;
mod verify;
-pub use descriptor::Digest;
pub use error::PvmfwVerifyError;
-pub use verify::{verify_payload, Capability, DebugLevel, VerifiedBootData};
+pub use verify::{verify_payload, Capability, DebugLevel, Digest, VerifiedBootData};
diff --git a/pvmfw/avb/src/partition.rs b/pvmfw/avb/src/partition.rs
index c05a0ac..02a78c6 100644
--- a/pvmfw/avb/src/partition.rs
+++ b/pvmfw/avb/src/partition.rs
@@ -27,8 +27,6 @@
}
impl PartitionName {
- pub(crate) const NUM_OF_KNOWN_PARTITIONS: usize = 3;
-
const KERNEL_PARTITION_NAME: &'static [u8] = b"boot\0";
const INITRD_NORMAL_PARTITION_NAME: &'static [u8] = b"initrd_normal\0";
const INITRD_DEBUG_PARTITION_NAME: &'static [u8] = b"initrd_debug\0";
diff --git a/pvmfw/avb/src/utils.rs b/pvmfw/avb/src/utils.rs
deleted file mode 100644
index b4f099b..0000000
--- a/pvmfw/avb/src/utils.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2023, The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! Common utility functions.
-
-use avb::{IoError, IoResult};
-
-pub(crate) fn is_not_null<T>(ptr: *const T) -> IoResult<()> {
- if ptr.is_null() {
- Err(IoError::NoSuchValue)
- } else {
- Ok(())
- }
-}
-
-pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> IoResult<usize> {
- num.try_into().map_err(|_| IoError::InvalidValueSize)
-}
-
-pub(crate) fn usize_checked_add(x: usize, y: usize) -> IoResult<usize> {
- x.checked_add(y).ok_or(IoError::InvalidValueSize)
-}
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index a85dbbb..2ebe9a1 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -14,17 +14,22 @@
//! This module handles the pvmfw payload verification.
-use crate::descriptor::{Descriptors, Digest};
use crate::ops::{Ops, Payload};
use crate::partition::PartitionName;
use crate::PvmfwVerifyError;
use alloc::vec;
use alloc::vec::Vec;
-use avb::{PartitionData, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData};
+use avb::{
+ Descriptor, DescriptorError, DescriptorResult, HashDescriptor, PartitionData,
+ PropertyDescriptor, SlotVerifyError, SlotVerifyNoDataResult, VbmetaData,
+};
// We use this for the rollback_index field if SlotVerifyData has empty rollback_indexes
const DEFAULT_ROLLBACK_INDEX: u64 = 0;
+/// SHA256 digest type for kernel and initrd.
+pub type Digest = [u8; 32];
+
/// Verified data returned when the payload verification succeeds.
#[derive(Debug, PartialEq, Eq)]
pub struct VerifiedBootData<'a> {
@@ -68,15 +73,21 @@
}
impl Capability {
- const KEY: &'static [u8] = b"com.android.virt.cap";
+ const KEY: &'static str = "com.android.virt.cap";
const REMOTE_ATTEST: &'static [u8] = b"remote_attest";
const SECRETKEEPER_PROTECTION: &'static [u8] = b"secretkeeper_protection";
const SEPARATOR: u8 = b'|';
- fn get_capabilities(property_value: &[u8]) -> Result<Vec<Self>, PvmfwVerifyError> {
+ /// Returns the capabilities indicated in `descriptor`, or error if the descriptor has
+ /// unexpected contents.
+ fn get_capabilities(descriptor: &PropertyDescriptor) -> Result<Vec<Self>, PvmfwVerifyError> {
+ if descriptor.key != Self::KEY {
+ return Err(PvmfwVerifyError::UnknownVbmetaProperty);
+ }
+
let mut res = Vec::new();
- for v in property_value.split(|b| *b == Self::SEPARATOR) {
+ for v in descriptor.value.split(|b| *b == Self::SEPARATOR) {
let cap = match v {
Self::REMOTE_ATTEST => Self::RemoteAttest,
Self::SECRETKEEPER_PROTECTION => Self::SecretkeeperProtection,
@@ -106,16 +117,6 @@
}
}
-fn verify_vbmeta_has_only_one_hash_descriptor(
- descriptors: &Descriptors,
-) -> SlotVerifyNoDataResult<()> {
- if descriptors.num_hash_descriptor() == 1 {
- Ok(())
- } else {
- Err(SlotVerifyError::InvalidMetadata)
- }
-}
-
fn verify_loaded_partition_has_expected_length(
loaded_partitions: &[PartitionData],
partition_name: PartitionName,
@@ -142,15 +143,91 @@
/// Verifies that the vbmeta contains at most one property descriptor and it indicates the
/// vm type is service VM.
fn verify_property_and_get_capabilities(
- descriptors: &Descriptors,
+ descriptors: &[Descriptor],
) -> Result<Vec<Capability>, PvmfwVerifyError> {
- if !descriptors.has_property_descriptor() {
- return Ok(vec![]);
+ let mut iter = descriptors.iter().filter_map(|d| match d {
+ Descriptor::Property(p) => Some(p),
+ _ => None,
+ });
+
+ let descriptor = match iter.next() {
+ // No property descriptors -> no capabilities.
+ None => return Ok(vec![]),
+ Some(d) => d,
+ };
+
+ // Multiple property descriptors -> error.
+ if iter.next().is_some() {
+ return Err(DescriptorError::InvalidContents.into());
}
- descriptors
- .find_property_value(Capability::KEY)
- .ok_or(PvmfwVerifyError::UnknownVbmetaProperty)
- .and_then(Capability::get_capabilities)
+
+ Capability::get_capabilities(descriptor)
+}
+
+/// Hash descriptors extracted from a vbmeta image.
+///
+/// We always have a kernel hash descriptor and may have initrd normal or debug descriptors.
+struct HashDescriptors<'a> {
+ kernel: &'a HashDescriptor<'a>,
+ initrd_normal: Option<&'a HashDescriptor<'a>>,
+ initrd_debug: Option<&'a HashDescriptor<'a>>,
+}
+
+impl<'a> HashDescriptors<'a> {
+ /// Extracts the hash descriptors from all vbmeta descriptors. Any unexpected hash descriptor
+ /// is an error.
+ fn get(descriptors: &'a [Descriptor<'a>]) -> DescriptorResult<Self> {
+ let mut kernel = None;
+ let mut initrd_normal = None;
+ let mut initrd_debug = None;
+
+ for descriptor in descriptors.iter().filter_map(|d| match d {
+ Descriptor::Hash(h) => Some(h),
+ _ => None,
+ }) {
+ let target = match descriptor
+ .partition_name
+ .as_bytes()
+ .try_into()
+ .map_err(|_| DescriptorError::InvalidContents)?
+ {
+ PartitionName::Kernel => &mut kernel,
+ PartitionName::InitrdNormal => &mut initrd_normal,
+ PartitionName::InitrdDebug => &mut initrd_debug,
+ };
+
+ if target.is_some() {
+ // Duplicates of the same partition name is an error.
+ return Err(DescriptorError::InvalidContents);
+ }
+ target.replace(descriptor);
+ }
+
+ // Kernel is required, the others are optional.
+ Ok(Self {
+ kernel: kernel.ok_or(DescriptorError::InvalidContents)?,
+ initrd_normal,
+ initrd_debug,
+ })
+ }
+
+ /// Returns an error if either initrd descriptor exists.
+ fn verify_no_initrd(&self) -> Result<(), PvmfwVerifyError> {
+ match self.initrd_normal.or(self.initrd_debug) {
+ Some(_) => Err(SlotVerifyError::InvalidMetadata.into()),
+ None => Ok(()),
+ }
+ }
+}
+
+/// Returns a copy of the SHA256 digest in `descriptor`, or error if the sizes don't match.
+fn copy_digest(descriptor: &HashDescriptor) -> SlotVerifyNoDataResult<Digest> {
+ let mut digest = Digest::default();
+ if descriptor.digest.len() != digest.len() {
+ return Err(SlotVerifyError::InvalidMetadata);
+ }
+ digest.clone_from_slice(descriptor.digest);
+ Ok(digest)
}
/// Verifies the given initrd partition, and checks that the resulting contents looks like expected.
@@ -186,15 +263,15 @@
verify_only_one_vbmeta_exists(vbmeta_images)?;
let vbmeta_image = &vbmeta_images[0];
verify_vbmeta_is_from_kernel_partition(vbmeta_image)?;
- let descriptors = Descriptors::from_vbmeta(vbmeta_image)?;
+ let descriptors = vbmeta_image.descriptors()?;
+ let hash_descriptors = HashDescriptors::get(&descriptors)?;
let capabilities = verify_property_and_get_capabilities(&descriptors)?;
- let kernel_descriptor = descriptors.find_hash_descriptor(PartitionName::Kernel)?;
if initrd.is_none() {
- verify_vbmeta_has_only_one_hash_descriptor(&descriptors)?;
+ hash_descriptors.verify_no_initrd()?;
return Ok(VerifiedBootData {
debug_level: DebugLevel::None,
- kernel_digest: *kernel_descriptor.digest,
+ kernel_digest: copy_digest(hash_descriptors.kernel)?,
initrd_digest: None,
public_key: trusted_public_key,
capabilities,
@@ -204,19 +281,19 @@
let initrd = initrd.unwrap();
let mut initrd_ops = Ops::new(&payload);
- let (debug_level, initrd_partition_name) =
+ let (debug_level, initrd_descriptor) =
if verify_initrd(&mut initrd_ops, PartitionName::InitrdNormal, initrd).is_ok() {
- (DebugLevel::None, PartitionName::InitrdNormal)
+ (DebugLevel::None, hash_descriptors.initrd_normal)
} else if verify_initrd(&mut initrd_ops, PartitionName::InitrdDebug, initrd).is_ok() {
- (DebugLevel::Full, PartitionName::InitrdDebug)
+ (DebugLevel::Full, hash_descriptors.initrd_debug)
} else {
return Err(SlotVerifyError::Verification(None).into());
};
- let initrd_descriptor = descriptors.find_hash_descriptor(initrd_partition_name)?;
+ let initrd_descriptor = initrd_descriptor.ok_or(DescriptorError::InvalidContents)?;
Ok(VerifiedBootData {
debug_level,
- kernel_digest: *kernel_descriptor.digest,
- initrd_digest: Some(*initrd_descriptor.digest),
+ kernel_digest: copy_digest(hash_descriptors.kernel)?,
+ initrd_digest: Some(copy_digest(initrd_descriptor)?),
public_key: trusted_public_key,
capabilities,
rollback_index,
diff --git a/pvmfw/avb/tests/api_test.rs b/pvmfw/avb/tests/api_test.rs
index 6dc5a0a..c6f26ac 100644
--- a/pvmfw/avb/tests/api_test.rs
+++ b/pvmfw/avb/tests/api_test.rs
@@ -17,7 +17,7 @@
mod utils;
use anyhow::{anyhow, Result};
-use avb::{IoError, SlotVerifyError};
+use avb::{DescriptorError, SlotVerifyError};
use avb_bindgen::{AvbFooter, AvbVBMetaImageHeader};
use pvmfw_avb::{verify_payload, Capability, DebugLevel, PvmfwVerifyError, VerifiedBootData};
use std::{fs, mem::size_of, ptr};
@@ -88,7 +88,7 @@
&fs::read(TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH)?,
/* initrd= */ None,
&load_trusted_public_key()?,
- PvmfwVerifyError::InvalidDescriptors(IoError::NoSuchPartition),
+ PvmfwVerifyError::InvalidDescriptors(DescriptorError::InvalidContents),
)
}
@@ -98,7 +98,7 @@
&fs::read(TEST_IMG_WITH_INITRD_AND_NON_INITRD_DESC_PATH)?,
&load_latest_initrd_normal()?,
&load_trusted_public_key()?,
- PvmfwVerifyError::InvalidDescriptors(IoError::NoSuchPartition),
+ PvmfwVerifyError::InvalidDescriptors(DescriptorError::InvalidContents),
)
}
@@ -142,7 +142,7 @@
&fs::read(TEST_IMG_WITH_MULTIPLE_PROPS_PATH)?,
/* initrd= */ None,
&load_trusted_public_key()?,
- PvmfwVerifyError::InvalidDescriptors(IoError::Io),
+ PvmfwVerifyError::InvalidDescriptors(DescriptorError::InvalidContents),
)
}
diff --git a/tests/aidl/Android.bp b/tests/aidl/Android.bp
index ed4e8ff..7e22646 100644
--- a/tests/aidl/Android.bp
+++ b/tests/aidl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/benchmark/Android.bp b/tests/benchmark/Android.bp
index 657241c..31fe0f6 100644
--- a/tests/benchmark/Android.bp
+++ b/tests/benchmark/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/benchmark/src/jni/Android.bp b/tests/benchmark/src/jni/Android.bp
index e1bc8b0..c2e1b7c 100644
--- a/tests/benchmark/src/jni/Android.bp
+++ b/tests/benchmark/src/jni/Android.bp
@@ -1,10 +1,11 @@
-package{
- default_applicable_licenses : ["Android-Apache-2.0"],
+package {
+ default_team: "trendy_team_virtualization",
+ default_applicable_licenses: ["Android-Apache-2.0"],
}
cc_library_shared {
name: "libiovsock_host_jni",
- srcs: [ "io_vsock_host_jni.cpp" ],
+ srcs: ["io_vsock_host_jni.cpp"],
header_libs: ["jni_headers"],
shared_libs: ["libbase"],
-}
\ No newline at end of file
+}
diff --git a/tests/benchmark_hostside/Android.bp b/tests/benchmark_hostside/Android.bp
index b613a8a..8727b05 100644
--- a/tests/benchmark_hostside/Android.bp
+++ b/tests/benchmark_hostside/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/helper/Android.bp b/tests/helper/Android.bp
index 614c70c..9223391 100644
--- a/tests/helper/Android.bp
+++ b/tests/helper/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/hostside/Android.bp b/tests/hostside/Android.bp
index e3d9cbe..2cfaffa 100644
--- a/tests/hostside/Android.bp
+++ b/tests/hostside/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/hostside/helper/Android.bp b/tests/hostside/helper/Android.bp
index 75553d0..890e14a 100644
--- a/tests/hostside/helper/Android.bp
+++ b/tests/hostside/helper/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/no_avf/Android.bp b/tests/no_avf/Android.bp
index 22d099e..cdc9e9f 100644
--- a/tests/no_avf/Android.bp
+++ b/tests/no_avf/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/pvmfw/Android.bp b/tests/pvmfw/Android.bp
index c12f67a..03dcc35 100644
--- a/tests/pvmfw/Android.bp
+++ b/tests/pvmfw/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/pvmfw/helper/Android.bp b/tests/pvmfw/helper/Android.bp
index 1b96842..7258c68 100644
--- a/tests/pvmfw/helper/Android.bp
+++ b/tests/pvmfw/helper/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/pvmfw/tools/Android.bp b/tests/pvmfw/tools/Android.bp
index 7bd3ef5..e4a31d5 100644
--- a/tests/pvmfw/tools/Android.bp
+++ b/tests/pvmfw/tools/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/testapk/Android.bp b/tests/testapk/Android.bp
index 6a30b1c..10bbfb4 100644
--- a/tests/testapk/Android.bp
+++ b/tests/testapk/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
index 3d83f40..df6280d 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -73,6 +73,7 @@
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
@@ -543,6 +544,7 @@
assertThrows(NullPointerException.class, () -> builder.setApkPath(null));
assertThrows(NullPointerException.class, () -> builder.setPayloadConfigPath(null));
assertThrows(NullPointerException.class, () -> builder.setPayloadBinaryName(null));
+ assertThrows(NullPointerException.class, () -> builder.setVendorDiskImage(null));
assertThrows(NullPointerException.class, () -> builder.setOs(null));
// Individual property checks.
@@ -2131,6 +2133,10 @@
.contains("android.permission.USE_CUSTOM_VIRTUAL_MACHINE permission");
}
+ // TODO(b/323768068): Enable this test when we can inject vendor hashkey for test purpose.
+ // After introducing VM reference DT, non-pVM cannot trust test_microdroid_vendor_image.img
+ // as well, because it doesn't pass the hashtree digest of testing image into VM.
+ @Ignore
@Test
public void bootsWithVendorPartition() throws Exception {
assumeSupportedDevice();
@@ -2140,10 +2146,6 @@
// after introducing verification based on DT and fstab in microdroid vendor partition.
assumeFalse(
"Boot with vendor partition is failing in HWASAN enabled Microdroid.", isHwasan());
- assumeFalse(
- "Skip test for protected VM, pvmfw config data doesn't contain any information of"
- + " test images, such as root digest.",
- isProtectedVm());
assumeFeatureEnabled(VirtualMachineManager.FEATURE_VENDOR_MODULES);
grantPermission(VirtualMachine.USE_CUSTOM_VIRTUAL_MACHINE_PERMISSION);
@@ -2194,8 +2196,9 @@
.build();
VirtualMachine vm = forceCreateNewVirtualMachine("test_boot_with_unsigned_vendor", config);
- assertThrowsVmExceptionContaining(
- () -> vm.run(), "Failed to get vbmeta from microdroid-vendor.img");
+ BootResult bootResult = tryBootVm(TAG, "test_boot_with_unsigned_vendor");
+ assertThat(bootResult.payloadStarted).isFalse();
+ assertThat(bootResult.deathReason).isEqualTo(VirtualMachineCallback.STOP_REASON_REBOOT);
}
@Test
diff --git a/tests/vendor_images/Android.bp b/tests/vendor_images/Android.bp
index 26dbc01..ecf0bb4 100644
--- a/tests/vendor_images/Android.bp
+++ b/tests/vendor_images/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/vmshareapp/Android.bp b/tests/vmshareapp/Android.bp
index 5f6dc57..d4113bf 100644
--- a/tests/vmshareapp/Android.bp
+++ b/tests/vmshareapp/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}
diff --git a/tests/vmshareapp/aidl/Android.bp b/tests/vmshareapp/aidl/Android.bp
index df4a4b4..09e3405 100644
--- a/tests/vmshareapp/aidl/Android.bp
+++ b/tests/vmshareapp/aidl/Android.bp
@@ -1,4 +1,5 @@
package {
+ default_team: "trendy_team_virtualization",
default_applicable_licenses: ["Android-Apache-2.0"],
}