Merge changes from topic "vm_permission_to_platform_app"
* changes:
Sign demo app with the platform key
Restrict MANAGE_VIRTUAL_MACHINE to platform signed apps
diff --git a/apkdmverity/src/main.rs b/apkdmverity/src/main.rs
index 2cc0758..cabeb35 100644
--- a/apkdmverity/src/main.rs
+++ b/apkdmverity/src/main.rs
@@ -62,7 +62,7 @@
let apk = matches.value_of("apk").unwrap();
let idsig = matches.value_of("idsig").unwrap();
let name = matches.value_of("name").unwrap();
- let roothash = if let Ok(val) = system_properties::read("microdroid_manager.apk_roothash") {
+ let roothash = if let Ok(val) = system_properties::read("microdroid_manager.apk_root_hash") {
Some(util::parse_hexstring(&val)?)
} else {
// This failure is not an error. We will use the roothash read from the idsig file.
diff --git a/compos/Android.bp b/compos/Android.bp
index 6705ea8..2af19c8 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -12,6 +12,7 @@
"libbinder_rpc_unstable_bindgen",
"libbinder_rs",
"libclap",
+ "libcompos_common",
"liblibc",
"liblog_rust",
"libminijail_rust",
@@ -40,6 +41,7 @@
"libbinder_rpc_unstable_bindgen",
"libbinder_rs",
"libclap",
+ "libcompos_common",
"liblibc",
"liblog_rust",
"libminijail_rust",
diff --git a/compos/common/Android.bp b/compos/common/Android.bp
new file mode 100644
index 0000000..d8fec81
--- /dev/null
+++ b/compos/common/Android.bp
@@ -0,0 +1,24 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_library {
+ name: "libcompos_common",
+ crate_name: "compos_common",
+ srcs: ["lib.rs"],
+ edition: "2018",
+ rustlibs: [
+ "android.system.virtualizationservice-rust",
+ "compos_aidl_interface-rust",
+ "libanyhow",
+ "libbinder_rpc_unstable_bindgen",
+ "libbinder_rs",
+ "liblog_rust",
+ ],
+ shared_libs: [
+ "libbinder_rpc_unstable",
+ ],
+ apex_available: [
+ "com.android.compos",
+ ],
+}
diff --git a/compos/common/compos_client.rs b/compos/common/compos_client.rs
new file mode 100644
index 0000000..dd8e54f
--- /dev/null
+++ b/compos/common/compos_client.rs
@@ -0,0 +1,218 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+//! Support for starting CompOS in a VM and connecting to the service
+
+use crate::{COMPOS_APEX_ROOT, COMPOS_DATA_ROOT, COMPOS_VSOCK_PORT};
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
+ IVirtualMachine::IVirtualMachine,
+ IVirtualMachineCallback::{BnVirtualMachineCallback, IVirtualMachineCallback},
+ IVirtualizationService::IVirtualizationService,
+ VirtualMachineAppConfig::VirtualMachineAppConfig,
+ VirtualMachineConfig::VirtualMachineConfig,
+};
+use android_system_virtualizationservice::binder::{
+ wait_for_interface, BinderFeatures, DeathRecipient, IBinder, Interface, ParcelFileDescriptor,
+ Result as BinderResult, Strong,
+};
+use anyhow::{anyhow, bail, Context, Result};
+use binder::{
+ unstable_api::{new_spibinder, AIBinder},
+ FromIBinder,
+};
+use compos_aidl_interface::aidl::com::android::compos::ICompOsService::ICompOsService;
+use std::fs::File;
+use std::path::Path;
+use std::sync::{Arc, Condvar, Mutex};
+use std::thread;
+use std::time::Duration;
+
+/// This owns an instance of the CompOS VM.
+pub struct VmInstance {
+ #[allow(dead_code)] // Keeps the vm alive even if we don`t touch it
+ vm: Strong<dyn IVirtualMachine>,
+ cid: i32,
+}
+
+impl VmInstance {
+ /// Start a new CompOS VM instance using the specified instance image file.
+ pub fn start(instance_image: &Path) -> Result<VmInstance> {
+ let instance_image =
+ File::open(instance_image).context("Failed to open instance image file")?;
+ let instance_fd = ParcelFileDescriptor::new(instance_image);
+
+ let apex_dir = Path::new(COMPOS_APEX_ROOT);
+ let data_dir = Path::new(COMPOS_DATA_ROOT);
+
+ let apk_fd = File::open(apex_dir.join("app/CompOSPayloadApp/CompOSPayloadApp.apk"))
+ .context("Failed to open config APK file")?;
+ let apk_fd = ParcelFileDescriptor::new(apk_fd);
+
+ let idsig_fd = File::open(apex_dir.join("etc/CompOSPayloadApp.apk.idsig"))
+ .context("Failed to open config APK idsig file")?;
+ let idsig_fd = ParcelFileDescriptor::new(idsig_fd);
+
+ // TODO: Send this to stdout instead? Or specify None?
+ let log_fd = File::create(data_dir.join("vm.log")).context("Failed to create log file")?;
+ let log_fd = ParcelFileDescriptor::new(log_fd);
+
+ let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
+ apk: Some(apk_fd),
+ idsig: Some(idsig_fd),
+ instanceImage: Some(instance_fd),
+ configPath: "assets/vm_config.json".to_owned(),
+ ..Default::default()
+ });
+
+ let service = wait_for_interface::<dyn IVirtualizationService>(
+ "android.system.virtualizationservice",
+ )
+ .context("Failed to find VirtualizationService")?;
+
+ let vm = service.startVm(&config, Some(&log_fd)).context("Failed to start VM")?;
+ let vm_state = Arc::new(VmStateMonitor::default());
+
+ let vm_state_clone = Arc::clone(&vm_state);
+ vm.as_binder().link_to_death(&mut DeathRecipient::new(move || {
+ vm_state_clone.set_died();
+ log::error!("VirtualizationService died");
+ }))?;
+
+ let vm_state_clone = Arc::clone(&vm_state);
+ let callback = BnVirtualMachineCallback::new_binder(
+ VmCallback(vm_state_clone),
+ BinderFeatures::default(),
+ );
+ vm.registerCallback(&callback)?;
+
+ let cid = vm_state.wait_for_start()?;
+
+ // TODO: Use onPayloadReady to avoid this
+ thread::sleep(Duration::from_secs(3));
+
+ Ok(VmInstance { vm, cid })
+ }
+
+ /// Create and return an RPC Binder connection to the Comp OS service in the VM.
+ pub fn get_service(&self) -> Result<Strong<dyn ICompOsService>> {
+ let cid = self.cid as u32;
+ // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership
+ // can be safely taken by new_spibinder.
+ let ibinder = unsafe {
+ new_spibinder(
+ binder_rpc_unstable_bindgen::RpcClient(cid, COMPOS_VSOCK_PORT) as *mut AIBinder
+ )
+ }
+ .ok_or_else(|| anyhow!("Failed to connect to CompOS service"))?;
+
+ FromIBinder::try_from(ibinder).context("Connecting to CompOS service")
+ }
+}
+
+#[derive(Debug)]
+struct VmState {
+ has_died: bool,
+ cid: Option<i32>,
+}
+
+impl Default for VmState {
+ fn default() -> Self {
+ Self { has_died: false, cid: None }
+ }
+}
+
+#[derive(Debug)]
+struct VmStateMonitor {
+ mutex: Mutex<VmState>,
+ state_ready: Condvar,
+}
+
+impl Default for VmStateMonitor {
+ fn default() -> Self {
+ Self { mutex: Mutex::new(Default::default()), state_ready: Condvar::new() }
+ }
+}
+
+impl VmStateMonitor {
+ fn set_died(&self) {
+ let mut state = self.mutex.lock().unwrap();
+ state.has_died = true;
+ state.cid = None;
+ drop(state); // Unlock the mutex prior to notifying
+ self.state_ready.notify_all();
+ }
+
+ fn set_started(&self, cid: i32) {
+ let mut state = self.mutex.lock().unwrap();
+ if state.has_died {
+ return;
+ }
+ state.cid = Some(cid);
+ drop(state); // Unlock the mutex prior to notifying
+ self.state_ready.notify_all();
+ }
+
+ fn wait_for_start(&self) -> Result<i32> {
+ let (state, result) = self
+ .state_ready
+ .wait_timeout_while(self.mutex.lock().unwrap(), Duration::from_secs(10), |state| {
+ state.cid.is_none() && !state.has_died
+ })
+ .unwrap();
+ if result.timed_out() {
+ bail!("Timed out waiting for VM")
+ }
+ state.cid.ok_or_else(|| anyhow!("VM died"))
+ }
+}
+
+#[derive(Debug)]
+struct VmCallback(Arc<VmStateMonitor>);
+
+impl Interface for VmCallback {}
+
+impl IVirtualMachineCallback for VmCallback {
+ fn onDied(&self, cid: i32) -> BinderResult<()> {
+ self.0.set_died();
+ log::warn!("VM died, cid = {}", cid);
+ Ok(())
+ }
+
+ fn onPayloadStarted(
+ &self,
+ cid: i32,
+ _stream: Option<&binder::parcel::ParcelFileDescriptor>,
+ ) -> BinderResult<()> {
+ self.0.set_started(cid);
+ // TODO: Use the stream?
+ log::info!("VM payload started, cid = {}", cid);
+ Ok(())
+ }
+
+ fn onPayloadReady(&self, cid: i32) -> BinderResult<()> {
+ // TODO: Use this to trigger vsock connection
+ log::info!("VM payload ready, cid = {}", cid);
+ Ok(())
+ }
+
+ fn onPayloadFinished(&self, cid: i32, exit_code: i32) -> BinderResult<()> {
+ // This should probably never happen in our case, but if it does we means our VM is no
+ // longer running
+ self.0.set_died();
+ log::warn!("VM payload finished, cid = {}, exit code = {}", cid, exit_code);
+ Ok(())
+ }
+}
diff --git a/compos/common/lib.rs b/compos/common/lib.rs
new file mode 100644
index 0000000..081f086
--- /dev/null
+++ b/compos/common/lib.rs
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2021 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 items used by CompOS server and/or clients
+
+pub mod compos_client;
+
+/// VSock port that the CompOS server listens on for RPC binder connections. This should be out of
+/// future port range (if happens) that microdroid may reserve for system components.
+pub const COMPOS_VSOCK_PORT: u32 = 6432;
+
+/// The root directory where the CompOS APEX is mounted (read only).
+pub const COMPOS_APEX_ROOT: &str = "/apex/com.android.compos";
+
+/// The root of the data directory available for private use by the CompOS APEX.
+pub const COMPOS_DATA_ROOT: &str = "/data/misc/apexdata/com.android.compos";
diff --git a/compos/src/common.rs b/compos/src/common.rs
deleted file mode 100644
index ca831bb..0000000
--- a/compos/src/common.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * Copyright (C) 2021 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.
- */
-
-/// Port to listen. This should be out of future port range (if happens) that microdroid may
-/// reserve for system components.
-pub const VSOCK_PORT: u32 = 6432;
diff --git a/compos/src/compsvc_main.rs b/compos/src/compsvc_main.rs
index 46c8f8c..9855b53 100644
--- a/compos/src/compsvc_main.rs
+++ b/compos/src/compsvc_main.rs
@@ -16,16 +16,15 @@
//! A tool to start a standalone compsvc server that serves over RPC binder.
-mod common;
mod compilation;
mod compos_key_service;
mod compsvc;
mod fsverity;
mod signer;
-use crate::common::VSOCK_PORT;
use anyhow::{bail, Result};
use binder::unstable_api::AsNative;
+use compos_common::COMPOS_VSOCK_PORT;
use log::debug;
fn main() -> Result<()> {
@@ -40,7 +39,7 @@
let retval = unsafe {
binder_rpc_unstable_bindgen::RunRpcServer(
service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
- VSOCK_PORT,
+ COMPOS_VSOCK_PORT,
)
};
if retval {
diff --git a/compos/src/pvm_exec.rs b/compos/src/pvm_exec.rs
index 6938370..b6fc729 100644
--- a/compos/src/pvm_exec.rs
+++ b/compos/src/pvm_exec.rs
@@ -41,9 +41,7 @@
FdAnnotation::FdAnnotation, ICompOsService::ICompOsService,
};
use compos_aidl_interface::binder::Strong;
-
-mod common;
-use common::VSOCK_PORT;
+use compos_common::COMPOS_VSOCK_PORT;
const FD_SERVER_BIN: &str = "/apex/com.android.virt/bin/fd_server";
@@ -51,7 +49,9 @@
// SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
// safely taken by new_spibinder.
let ibinder = unsafe {
- new_spibinder(binder_rpc_unstable_bindgen::RpcClient(cid, VSOCK_PORT) as *mut AIBinder)
+ new_spibinder(
+ binder_rpc_unstable_bindgen::RpcClient(cid, COMPOS_VSOCK_PORT) as *mut AIBinder
+ )
};
if let Some(ibinder) = ibinder {
<dyn ICompOsService>::try_from(ibinder).context("Cannot connect to RPC service")
diff --git a/compos/verify_key/Android.bp b/compos/verify_key/Android.bp
index dd54f76..a5892b8 100644
--- a/compos/verify_key/Android.bp
+++ b/compos/verify_key/Android.bp
@@ -5,18 +5,17 @@
rust_binary {
name: "compos_verify_key",
srcs: ["verify_key.rs"],
+ edition: "2018",
rustlibs: [
- "android.system.virtualizationservice-rust",
"compos_aidl_interface-rust",
+ "libandroid_logger",
"libanyhow",
- "libbinder_rpc_unstable_bindgen",
"libbinder_rs",
"libclap",
+ "libcompos_common",
+ "liblog_rust",
],
prefer_rlib: true,
- shared_libs: [
- "libbinder_rpc_unstable",
- ],
apex_available: [
"com.android.compos",
],
diff --git a/compos/verify_key/verify_key.rs b/compos/verify_key/verify_key.rs
index f279b93..2e3d206 100644
--- a/compos/verify_key/verify_key.rs
+++ b/compos/verify_key/verify_key.rs
@@ -14,35 +14,17 @@
* limitations under the License.
*/
-//! A tool to verify whether a CompOs instance image and key pair are valid. It starts a CompOs VM
+//! A tool to verify whether a CompOS instance image and key pair are valid. It starts a CompOS VM
//! as part of this. The tool is intended to be run by odsign during boot.
-use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
- IVirtualMachine::IVirtualMachine,
- IVirtualMachineCallback::{BnVirtualMachineCallback, IVirtualMachineCallback},
- IVirtualizationService::IVirtualizationService,
- VirtualMachineAppConfig::VirtualMachineAppConfig,
- VirtualMachineConfig::VirtualMachineConfig,
-};
-use android_system_virtualizationservice::binder::{
- wait_for_interface, BinderFeatures, DeathRecipient, IBinder, Interface, ParcelFileDescriptor,
- ProcessState, Result as BinderResult, Strong,
-};
-use anyhow::{anyhow, bail, Context, Result};
-use binder::{
- unstable_api::{new_spibinder, AIBinder},
- FromIBinder,
-};
-use compos_aidl_interface::aidl::com::android::compos::ICompOsService::ICompOsService;
+use anyhow::{bail, Context, Result};
+use compos_aidl_interface::binder::ProcessState;
+use compos_common::compos_client::VmInstance;
+use compos_common::COMPOS_DATA_ROOT;
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};
-use std::sync::{Arc, Condvar, Mutex};
-use std::thread;
-use std::time::Duration;
-const COMPOS_APEX_ROOT: &str = "/apex/com.android.compos";
-const COMPOS_DATA_ROOT: &str = "/data/misc/apexdata/com.android.compos";
const CURRENT_DIR: &str = "current";
const PENDING_DIR: &str = "pending";
const PRIVATE_KEY_BLOB_FILE: &str = "key.blob";
@@ -51,9 +33,13 @@
const MAX_FILE_SIZE_BYTES: u64 = 8 * 1024;
-const COMPOS_SERVICE_PORT: u32 = 6432;
-
fn main() -> Result<()> {
+ android_logger::init_once(
+ android_logger::Config::default()
+ .with_tag("compos_verify_key")
+ .with_min_level(log::Level::Info),
+ );
+
let matches = clap::App::new("compos_verify_key")
.arg(
clap::Arg::with_name("instance")
@@ -79,7 +65,7 @@
if do_pending {
// If the pending instance is ok, then it must actually match the current system state,
// so we promote it to current.
- println!("Promoting pending to current");
+ log::info!("Promoting pending to current");
promote_to_current(&instance_dir)
} else {
Ok(())
@@ -88,9 +74,9 @@
if result.is_err() {
// This is best efforts, and we still want to report the original error as our result
- println!("Removing {}", instance_dir.display());
+ log::info!("Removing {}", instance_dir.display());
if let Err(e) = fs::remove_dir_all(&instance_dir) {
- eprintln!("Failed to remove directory: {}", e);
+ log::warn!("Failed to remove directory: {}", e);
}
}
@@ -100,14 +86,13 @@
fn verify(instance_dir: &Path) -> Result<()> {
let blob = instance_dir.join(PRIVATE_KEY_BLOB_FILE);
let public_key = instance_dir.join(PUBLIC_KEY_FILE);
- let instance = instance_dir.join(INSTANCE_IMAGE_FILE);
+ let instance_image = instance_dir.join(INSTANCE_IMAGE_FILE);
let blob = read_small_file(blob).context("Failed to read key blob")?;
let public_key = read_small_file(public_key).context("Failed to read public key")?;
- let instance = File::open(instance).context("Failed to open instance image file")?;
- let vm_instance = VmInstance::start(instance)?;
- let service = get_service(vm_instance.cid).context("Failed to connect to CompOs service")?;
+ let vm_instance = VmInstance::start(&instance_image)?;
+ let service = vm_instance.get_service()?;
let result = service.verifySigningKey(&blob, &public_key).context("Verifying signing key")?;
@@ -128,20 +113,6 @@
Ok(data)
}
-fn get_service(cid: i32) -> Result<Strong<dyn ICompOsService>> {
- let cid = cid as u32;
- // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
- // safely taken by new_spibinder.
- let ibinder = unsafe {
- new_spibinder(
- binder_rpc_unstable_bindgen::RpcClient(cid, COMPOS_SERVICE_PORT) as *mut AIBinder
- )
- }
- .ok_or_else(|| anyhow!("Invalid raw AIBinder"))?;
-
- Ok(FromIBinder::try_from(ibinder)?)
-}
-
fn promote_to_current(instance_dir: &Path) -> Result<()> {
let current_dir: PathBuf = [COMPOS_DATA_ROOT, CURRENT_DIR].iter().collect();
@@ -153,161 +124,3 @@
.context("Unable to promote pending instance to current")?;
Ok(())
}
-
-#[derive(Debug)]
-struct VmState {
- has_died: bool,
- cid: Option<i32>,
-}
-
-impl Default for VmState {
- fn default() -> Self {
- Self { has_died: false, cid: None }
- }
-}
-
-#[derive(Debug)]
-struct VmStateMonitor {
- mutex: Mutex<VmState>,
- state_ready: Condvar,
-}
-
-impl Default for VmStateMonitor {
- fn default() -> Self {
- Self { mutex: Mutex::new(Default::default()), state_ready: Condvar::new() }
- }
-}
-
-impl VmStateMonitor {
- fn set_died(&self) {
- let mut state = self.mutex.lock().unwrap();
- state.has_died = true;
- state.cid = None;
- drop(state); // Unlock the mutex prior to notifying
- self.state_ready.notify_all();
- }
-
- fn set_started(&self, cid: i32) {
- let mut state = self.mutex.lock().unwrap();
- if state.has_died {
- return;
- }
- state.cid = Some(cid);
- drop(state); // Unlock the mutex prior to notifying
- self.state_ready.notify_all();
- }
-
- fn wait_for_start(&self) -> Result<i32> {
- let (state, result) = self
- .state_ready
- .wait_timeout_while(self.mutex.lock().unwrap(), Duration::from_secs(10), |state| {
- state.cid.is_none() && !state.has_died
- })
- .unwrap();
- if result.timed_out() {
- bail!("Timed out waiting for VM")
- }
- state.cid.ok_or_else(|| anyhow!("VM died"))
- }
-}
-
-struct VmInstance {
- #[allow(dead_code)] // Keeps the vm alive even if we don`t touch it
- vm: Strong<dyn IVirtualMachine>,
- cid: i32,
-}
-
-impl VmInstance {
- fn start(instance_file: File) -> Result<VmInstance> {
- let instance_fd = ParcelFileDescriptor::new(instance_file);
-
- let apex_dir = Path::new(COMPOS_APEX_ROOT);
- let data_dir = Path::new(COMPOS_DATA_ROOT);
-
- let apk_fd = File::open(apex_dir.join("app/CompOSPayloadApp/CompOSPayloadApp.apk"))
- .context("Failed to open config APK file")?;
- let apk_fd = ParcelFileDescriptor::new(apk_fd);
-
- let idsig_fd = File::open(apex_dir.join("etc/CompOSPayloadApp.apk.idsig"))
- .context("Failed to open config APK idsig file")?;
- let idsig_fd = ParcelFileDescriptor::new(idsig_fd);
-
- // TODO: Send this to stdout instead? Or specify None?
- let log_fd = File::create(data_dir.join("vm.log")).context("Failed to create log file")?;
- let log_fd = ParcelFileDescriptor::new(log_fd);
-
- let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
- apk: Some(apk_fd),
- idsig: Some(idsig_fd),
- instanceImage: Some(instance_fd),
- configPath: "assets/vm_config.json".to_owned(),
- ..Default::default()
- });
-
- let service = wait_for_interface::<dyn IVirtualizationService>(
- "android.system.virtualizationservice",
- )
- .context("Failed to find VirtualizationService")?;
-
- let vm = service.startVm(&config, Some(&log_fd)).context("Failed to start VM")?;
- let vm_state = Arc::new(VmStateMonitor::default());
-
- let vm_state_clone = Arc::clone(&vm_state);
- vm.as_binder().link_to_death(&mut DeathRecipient::new(move || {
- vm_state_clone.set_died();
- eprintln!("VirtualizationService died");
- }))?;
-
- let vm_state_clone = Arc::clone(&vm_state);
- let callback = BnVirtualMachineCallback::new_binder(
- VmCallback(vm_state_clone),
- BinderFeatures::default(),
- );
- vm.registerCallback(&callback)?;
-
- let cid = vm_state.wait_for_start()?;
-
- // TODO: Use onPayloadReady to avoid this
- thread::sleep(Duration::from_secs(3));
-
- Ok(VmInstance { vm, cid })
- }
-}
-
-#[derive(Debug)]
-struct VmCallback(Arc<VmStateMonitor>);
-
-impl Interface for VmCallback {}
-
-impl IVirtualMachineCallback for VmCallback {
- fn onDied(&self, cid: i32) -> BinderResult<()> {
- self.0.set_died();
- println!("VM died, cid = {}", cid);
- Ok(())
- }
-
- fn onPayloadStarted(
- &self,
- cid: i32,
- _stream: Option<&binder::parcel::ParcelFileDescriptor>,
- ) -> BinderResult<()> {
- self.0.set_started(cid);
- // TODO: Use the stream?
- println!("VM payload started, cid = {}", cid);
- Ok(())
- }
-
- fn onPayloadReady(&self, cid: i32) -> BinderResult<()> {
- // TODO: Use this to trigger vsock connection
- println!("VM payload ready, cid = {}", cid);
- Ok(())
- }
-
- fn onPayloadFinished(&self, cid: i32, exit_code: i32) -> BinderResult<()> {
- // This should probably never happen in our case, but if it does we means our VM is no
- // longer running
- self.0.set_died();
- println!("VM payload finished, cid = {}, exit code = {}", cid, exit_code);
- Ok(())
- }
-}
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index 1638f6f..e4334cb 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -101,7 +101,10 @@
multilib: {
common: {
deps: [
+ // non-updatable & mandatory apexes
+ "com.android.i18n",
"com.android.runtime",
+
"microdroid_plat_sepolicy.cil",
"microdroid_plat_mapping_file",
],
diff --git a/microdroid/init.rc b/microdroid/init.rc
index f6a7ecc..347f514 100644
--- a/microdroid/init.rc
+++ b/microdroid/init.rc
@@ -19,7 +19,6 @@
mkdir /mnt/apk 0755 system system
start microdroid_manager
- # TODO(b/190343842) verify apexes/apk before mounting them.
# Exec apexd in the VM mode to avoid unnecessary overhead of normal mode.
# (e.g. session management)
diff --git a/microdroid_manager/Android.bp b/microdroid_manager/Android.bp
index 104c04a..9957689 100644
--- a/microdroid_manager/Android.bp
+++ b/microdroid_manager/Android.bp
@@ -32,6 +32,7 @@
"libuuid",
"libvsock",
"librand",
+ "libzip",
],
shared_libs: [
"libbinder_rpc_unstable",
diff --git a/microdroid_manager/src/instance.rs b/microdroid_manager/src/instance.rs
index 51d74b0..73983a7 100644
--- a/microdroid_manager/src/instance.rs
+++ b/microdroid_manager/src/instance.rs
@@ -311,16 +311,22 @@
ret
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct MicrodroidData {
pub apk_data: ApkData,
- // TODO(b/197053593) add data for APEXes
+ pub apex_data: Vec<ApexData>,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct ApkData {
pub root_hash: Box<RootHash>,
// TODO(b/199143508) add cert
}
pub type RootHash = [u8];
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+pub struct ApexData {
+ pub name: String,
+ pub pubkey: Vec<u8>,
+}
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index 4f192dc..2e80b90 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -16,7 +16,7 @@
mod instance;
mod ioutil;
-mod metadata;
+mod payload;
use crate::instance::{ApkData, InstanceDisk, MicrodroidData, RootHash};
use anyhow::{anyhow, bail, Context, Result};
@@ -25,8 +25,10 @@
use binder::{FromIBinder, Strong};
use idsig::V4Signature;
use log::{error, info, warn};
+use microdroid_metadata::Metadata;
use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
use nix::ioctl_read_bad;
+use payload::{get_apex_data_from_payload, load_metadata};
use rustutils::system_properties;
use rustutils::system_properties::PropertyWatcher;
use std::fs::{self, File, OpenOptions};
@@ -90,26 +92,23 @@
kernlog::init()?;
info!("started.");
- let metadata = metadata::load()?;
+ let metadata = load_metadata()?;
let mut instance = InstanceDisk::new()?;
- let data = instance.read_microdroid_data().context("Failed to read identity data")?;
- let saved_root_hash: Option<&[u8]> =
- if let Some(data) = data.as_ref() { Some(&data.apk_data.root_hash) } else { None };
+ let saved_data = instance.read_microdroid_data().context("Failed to read identity data")?;
// Verify the payload before using it.
- let verified_root_hash =
- verify_payload(saved_root_hash).context("Payload verification failed")?;
- if let Some(saved_root_hash) = saved_root_hash {
- if saved_root_hash == verified_root_hash.as_ref() {
- info!("Saved root_hash is verified.");
+ let verified_data =
+ verify_payload(&metadata, saved_data.as_ref()).context("Payload verification failed")?;
+ if let Some(saved_data) = saved_data {
+ if saved_data == verified_data {
+ info!("Saved data is verified.");
} else {
- bail!("Detected an update of the APK which isn't supported yet.");
+ bail!("Detected an update of the payload which isn't supported yet.");
}
} else {
- info!("Saving APK root_hash: {}", to_hex_string(verified_root_hash.as_ref()));
- let data = MicrodroidData { apk_data: ApkData { root_hash: verified_root_hash } };
- instance.write_microdroid_data(&data).context("Failed to write identity data")?;
+ info!("Saving verified data.");
+ instance.write_microdroid_data(&verified_data).context("Failed to write identity data")?;
}
wait_for_apex_config_done()?;
@@ -138,12 +137,17 @@
Ok(())
}
-// Verify payload before executing it. Full verification (which is slow) is done when the root_hash
-// values from the idsig file and the instance disk are different. This function returns the
-// verified root hash that can be saved to the instance disk.
-fn verify_payload(root_hash: Option<&RootHash>) -> Result<Box<RootHash>> {
+// Verify payload before executing it. For APK payload, Full verification (which is slow) is done
+// when the root_hash values from the idsig file and the instance disk are different. This function
+// returns the verified root hash (for APK payload) and pubkeys (for APEX payloads) that can be
+// saved to the instance disk.
+fn verify_payload(
+ metadata: &Metadata,
+ saved_data: Option<&MicrodroidData>,
+) -> Result<MicrodroidData> {
let start_time = SystemTime::now();
+ let root_hash = saved_data.map(|d| &d.apk_data.root_hash);
let root_hash_from_idsig = get_apk_root_hash_from_idsig()?;
let root_hash_trustful = root_hash == Some(&root_hash_from_idsig);
@@ -156,6 +160,11 @@
// Start apkdmverity and wait for the dm-verify block
system_properties::write("ctl.start", "apkdmverity")?;
+
+ // While waiting for apkdmverity to mount APK, gathers APEX pubkeys used by APEXd.
+ // These will be compared ones from instance.img.
+ let apex_data_from_payload = get_apex_data_from_payload(metadata)?;
+
ioutil::wait_for_file(DM_MOUNTED_APK_PATH, WAIT_TIMEOUT)?;
// Do the full verification if the root_hash is un-trustful. This requires the full scanning of
@@ -171,7 +180,10 @@
// At this point, we can ensure that the root_hash from the idsig file is trusted, either by
// fully verifying the APK or by comparing it with the saved root_hash.
- Ok(root_hash_from_idsig)
+ Ok(MicrodroidData {
+ apk_data: ApkData { root_hash: root_hash_from_idsig },
+ apex_data: apex_data_from_payload,
+ })
}
// Waits until linker config is generated
diff --git a/microdroid_manager/src/metadata.rs b/microdroid_manager/src/metadata.rs
deleted file mode 100644
index 432a134..0000000
--- a/microdroid_manager/src/metadata.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2021, 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.
-
-//! Payload metadata from /dev/block/by-name/payload-metadata
-
-use crate::ioutil;
-
-use anyhow::Result;
-use log::info;
-use microdroid_metadata::{read_metadata, Metadata};
-use std::time::Duration;
-
-const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
-const PAYLOAD_METADATA_PATH: &str = "/dev/block/by-name/payload-metadata";
-
-/// loads payload metadata from /dev/block/by-name/paylaod-metadata
-pub fn load() -> Result<Metadata> {
- info!("loading payload metadata...");
- let file = ioutil::wait_for_file(PAYLOAD_METADATA_PATH, WAIT_TIMEOUT)?;
- read_metadata(file)
-}
diff --git a/microdroid_manager/src/payload.rs b/microdroid_manager/src/payload.rs
new file mode 100644
index 0000000..bfc6c09
--- /dev/null
+++ b/microdroid_manager/src/payload.rs
@@ -0,0 +1,61 @@
+// Copyright 2021, 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.
+
+//! Routines for handling payload
+
+use crate::instance::ApexData;
+use crate::ioutil::wait_for_file;
+use anyhow::Result;
+use log::info;
+use microdroid_metadata::{read_metadata, Metadata};
+use std::fs::File;
+use std::io::Read;
+use std::time::Duration;
+use zip::ZipArchive;
+
+const APEX_PUBKEY_ENTRY: &str = "apex_pubkey";
+const PAYLOAD_METADATA_PATH: &str = "/dev/block/by-name/payload-metadata";
+const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
+
+/// Loads payload metadata from /dev/block/by-name/payload-metadata
+pub fn load_metadata() -> Result<Metadata> {
+ info!("loading payload metadata...");
+ let file = wait_for_file(PAYLOAD_METADATA_PATH, WAIT_TIMEOUT)?;
+ read_metadata(file)
+}
+
+/// Loads (name, pubkey) from payload apexes and returns them as sorted by name.
+pub fn get_apex_data_from_payload(metadata: &Metadata) -> Result<Vec<ApexData>> {
+ let mut apex_data: Vec<ApexData> = metadata
+ .apexes
+ .iter()
+ .map(|apex| {
+ let name = apex.name.clone();
+ let partition = format!("/dev/block/by-name/{}", apex.partition_name);
+ let pubkey = get_pubkey_from_apex(&partition)?;
+ Ok(ApexData { name, pubkey })
+ })
+ .collect::<Result<Vec<_>>>()?;
+ apex_data.sort_by(|a, b| a.name.cmp(&b.name));
+ Ok(apex_data)
+}
+
+fn get_pubkey_from_apex(path: &str) -> Result<Vec<u8>> {
+ let f = File::open(path)?;
+ let mut z = ZipArchive::new(f)?;
+ let mut pubkey_file = z.by_name(APEX_PUBKEY_ENTRY)?;
+ let mut pubkey = Vec::new();
+ pubkey_file.read_to_end(&mut pubkey)?;
+ Ok(pubkey)
+}
diff --git a/virtualizationservice/src/payload.rs b/virtualizationservice/src/payload.rs
index 75ba6c7..9662fa3 100644
--- a/virtualizationservice/src/payload.rs
+++ b/virtualizationservice/src/payload.rs
@@ -31,8 +31,7 @@
/// The list of APEXes which microdroid requires.
// TODO(b/192200378) move this to microdroid.json?
-const MICRODROID_REQUIRED_APEXES: [&str; 3] =
- ["com.android.adbd", "com.android.i18n", "com.android.os.statsd"];
+const MICRODROID_REQUIRED_APEXES: [&str; 2] = ["com.android.adbd", "com.android.os.statsd"];
const APEX_INFO_LIST_PATH: &str = "/apex/apex-info-list.xml";