Merge "Use com.android.compos.certificate."
diff --git a/compos/Android.bp b/compos/Android.bp
index 2c864e7..ec3f67f 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -58,7 +58,6 @@
"liblog_rust",
"libminijail_rust",
"libnix",
- "libscopeguard",
],
prefer_rlib: true,
apex_available: [
diff --git a/compos/apk/AndroidManifest.xml b/compos/apk/AndroidManifest.xml
index 1e9352b..2f8cbcf 100644
--- a/compos/apk/AndroidManifest.xml
+++ b/compos/apk/AndroidManifest.xml
@@ -14,5 +14,5 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.compos.payload">
- <application android:label="CompOS" />
+ <application android:label="CompOS" android:hasCode="false"/>
</manifest>
diff --git a/compos/src/authfs.rs b/compos/src/authfs.rs
new file mode 100644
index 0000000..ce9aaf8
--- /dev/null
+++ b/compos/src/authfs.rs
@@ -0,0 +1,144 @@
+/*
+ * 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.
+ */
+
+use anyhow::{bail, Context, Result};
+use log::warn;
+use minijail::Minijail;
+use nix::sys::statfs::{statfs, FsType};
+use std::fs::{File, OpenOptions};
+use std::path::Path;
+use std::thread::sleep;
+use std::time::{Duration, Instant};
+
+const AUTHFS_BIN: &str = "/system/bin/authfs";
+const AUTHFS_SETUP_POLL_INTERVAL_MS: Duration = Duration::from_millis(50);
+const AUTHFS_SETUP_TIMEOUT_SEC: Duration = Duration::from_secs(10);
+const FUSE_SUPER_MAGIC: FsType = FsType(0x65735546);
+
+/// The number that hints the future file descriptor. These are not really file descriptor, but
+/// represents the file descriptor number to pass to the task.
+pub type PseudoRawFd = i32;
+
+/// Annotation of input file descriptor.
+#[derive(Debug)]
+pub struct InFdAnnotation {
+ /// A number/file descriptor that is supposed to represent a remote file.
+ pub fd: PseudoRawFd,
+
+ /// The file size of the remote file. Remote input files are supposed to be immutable and
+ /// to be verified with fs-verity by authfs.
+ pub file_size: u64,
+}
+
+/// Annotation of output file descriptor.
+#[derive(Debug)]
+pub struct OutFdAnnotation {
+ /// A number/file descriptor that is supposed to represent a remote file.
+ pub fd: PseudoRawFd,
+}
+
+/// An `AuthFs` instance is supposed to be backed by the `authfs` process. When the lifetime of the
+/// instance is over, the process is terminated and the FUSE is unmounted.
+pub struct AuthFs {
+ mountpoint: String,
+ jail: Minijail,
+}
+
+impl AuthFs {
+ /// Mount an authfs at `mountpoint` with specified FD annotations.
+ pub fn mount_and_wait(
+ mountpoint: &str,
+ in_fds: &[InFdAnnotation],
+ out_fds: &[OutFdAnnotation],
+ debuggable: bool,
+ ) -> Result<AuthFs> {
+ let jail = jail_authfs(mountpoint, in_fds, out_fds, debuggable)?;
+ wait_until_authfs_ready(mountpoint)?;
+ Ok(AuthFs { mountpoint: mountpoint.to_string(), jail })
+ }
+
+ /// Open a file at authfs' root directory.
+ pub fn open_file(&self, basename: PseudoRawFd, writable: bool) -> Result<File> {
+ OpenOptions::new()
+ .read(true)
+ .write(writable)
+ .open(format!("{}/{}", self.mountpoint, basename))
+ .with_context(|| format!("open authfs file {}", basename))
+ }
+}
+
+impl Drop for AuthFs {
+ fn drop(&mut self) {
+ if let Err(e) = self.jail.kill() {
+ if !matches!(e, minijail::Error::Killed(_)) {
+ warn!("Failed to kill authfs: {}", e);
+ }
+ }
+ }
+}
+
+fn jail_authfs(
+ mountpoint: &str,
+ in_fds: &[InFdAnnotation],
+ out_fds: &[OutFdAnnotation],
+ debuggable: bool,
+) -> Result<Minijail> {
+ // TODO(b/185175567): Run in a more restricted sandbox.
+ let jail = Minijail::new()?;
+
+ let mut args = vec![
+ AUTHFS_BIN.to_string(),
+ mountpoint.to_string(),
+ "--cid=2".to_string(), // Always use host unless we need to support other cases
+ ];
+ for conf in in_fds {
+ // TODO(b/185178698): Many input files need to be signed and verified.
+ // or can we use debug cert for now, which is better than nothing?
+ args.push("--remote-ro-file-unverified".to_string());
+ args.push(format!("{}:{}:{}", conf.fd, conf.fd, conf.file_size));
+ }
+ for conf in out_fds {
+ args.push("--remote-new-rw-file".to_string());
+ args.push(format!("{}:{}", conf.fd, conf.fd));
+ }
+
+ let preserve_fds = if debuggable {
+ vec![1, 2] // inherit/redirect stdout/stderr for debugging
+ } else {
+ vec![]
+ };
+
+ let _pid = jail.run(Path::new(AUTHFS_BIN), &preserve_fds, &args)?;
+ Ok(jail)
+}
+
+fn wait_until_authfs_ready(mountpoint: &str) -> Result<()> {
+ let start_time = Instant::now();
+ loop {
+ if is_fuse(mountpoint)? {
+ break;
+ }
+ if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
+ bail!("Time out mounting authfs");
+ }
+ sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
+ }
+ Ok(())
+}
+
+fn is_fuse(path: &str) -> Result<bool> {
+ Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
+}
diff --git a/compos/src/compsvc_worker.rs b/compos/src/compsvc_worker.rs
index 0456d58..f33659e 100644
--- a/compos/src/compsvc_worker.rs
+++ b/compos/src/compsvc_worker.rs
@@ -18,94 +18,29 @@
//! responsible for setting up the execution environment, e.g. to create file descriptors for
//! remote file access via an authfs mount.
+mod authfs;
+
use anyhow::{bail, Result};
-use log::warn;
use minijail::Minijail;
-use nix::sys::statfs::{statfs, FsType};
-use std::fs::{File, OpenOptions};
-use std::io;
+use std::fs::File;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use std::process::exit;
-use std::thread::sleep;
-use std::time::{Duration, Instant};
-const AUTHFS_BIN: &str = "/system/bin/authfs";
-const AUTHFS_SETUP_POLL_INTERVAL_MS: Duration = Duration::from_millis(50);
-const AUTHFS_SETUP_TIMEOUT_SEC: Duration = Duration::from_secs(10);
-const FUSE_SUPER_MAGIC: FsType = FsType(0x65735546);
+use crate::authfs::{AuthFs, InFdAnnotation, OutFdAnnotation, PseudoRawFd};
-/// The number that hints the future file descriptor. These are not really file descriptor, but
-/// represents the file descriptor number to pass to the task.
-type PseudoRawFd = i32;
-
-fn is_fuse(path: &str) -> Result<bool> {
- Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
-}
-
-fn spawn_authfs(config: &Config) -> Result<Minijail> {
- // TODO(b/185175567): Run in a more restricted sandbox.
- let jail = Minijail::new()?;
-
- let mut args = vec![
- AUTHFS_BIN.to_string(),
- config.authfs_root.clone(),
- "--cid=2".to_string(), // Always use host unless we need to support other cases
- ];
- for conf in &config.in_fds {
- // TODO(b/185178698): Many input files need to be signed and verified.
- // or can we use debug cert for now, which is better than nothing?
- args.push("--remote-ro-file-unverified".to_string());
- args.push(format!("{}:{}:{}", conf.fd, conf.fd, conf.file_size));
- }
- for conf in &config.out_fds {
- args.push("--remote-new-rw-file".to_string());
- args.push(format!("{}:{}", conf.fd, conf.fd));
- }
-
- let preserve_fds = if config.debuggable {
- vec![1, 2] // inherit/redirect stdout/stderr for debugging
- } else {
- vec![]
- };
-
- let _pid = jail.run(Path::new(AUTHFS_BIN), &preserve_fds, &args)?;
- Ok(jail)
-}
-
-fn wait_until_authfs_ready(authfs_root: &str) -> Result<()> {
- let start_time = Instant::now();
- loop {
- if is_fuse(authfs_root)? {
- break;
- }
- if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
- bail!("Time out mounting authfs");
- }
- sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
- }
- Ok(())
-}
-
-fn open_authfs_file(authfs_root: &str, basename: PseudoRawFd, writable: bool) -> io::Result<File> {
- OpenOptions::new().read(true).write(writable).open(format!("{}/{}", authfs_root, basename))
-}
-
-fn open_authfs_files_for_mapping(config: &Config) -> io::Result<Vec<(File, PseudoRawFd)>> {
+fn open_authfs_files_for_mapping(
+ authfs: &AuthFs,
+ config: &Config,
+) -> Result<Vec<(File, PseudoRawFd)>> {
let mut fd_mapping = Vec::with_capacity(config.in_fds.len() + config.out_fds.len());
- let results: io::Result<Vec<_>> = config
- .in_fds
- .iter()
- .map(|conf| Ok((open_authfs_file(&config.authfs_root, conf.fd, false)?, conf.fd)))
- .collect();
+ let results: Result<Vec<_>> =
+ config.in_fds.iter().map(|conf| Ok((authfs.open_file(conf.fd, false)?, conf.fd))).collect();
fd_mapping.append(&mut results?);
- let results: io::Result<Vec<_>> = config
- .out_fds
- .iter()
- .map(|conf| Ok((open_authfs_file(&config.authfs_root, conf.fd, true)?, conf.fd)))
- .collect();
+ let results: Result<Vec<_>> =
+ config.out_fds.iter().map(|conf| Ok((authfs.open_file(conf.fd, true)?, conf.fd))).collect();
fd_mapping.append(&mut results?);
Ok(fd_mapping)
@@ -125,15 +60,6 @@
Ok(jail)
}
-struct InFdAnnotation {
- fd: PseudoRawFd,
- file_size: u64,
-}
-
-struct OutFdAnnotation {
- fd: PseudoRawFd,
-}
-
struct Config {
authfs_root: String,
in_fds: Vec<InFdAnnotation>,
@@ -209,23 +135,19 @@
let config = parse_args()?;
- let authfs_jail = spawn_authfs(&config)?;
- let authfs_lifetime = scopeguard::guard(authfs_jail, |authfs_jail| {
- if let Err(e) = authfs_jail.kill() {
- if !matches!(e, minijail::Error::Killed(_)) {
- warn!("Failed to kill authfs: {}", e);
- }
- }
- });
-
- wait_until_authfs_ready(&config.authfs_root)?;
- let fd_mapping = open_authfs_files_for_mapping(&config)?;
+ let authfs = AuthFs::mount_and_wait(
+ &config.authfs_root,
+ &config.in_fds,
+ &config.out_fds,
+ config.debuggable,
+ )?;
+ let fd_mapping = open_authfs_files_for_mapping(&authfs, &config)?;
let jail = spawn_jailed_task(&config, fd_mapping)?;
let jail_result = jail.wait();
// Be explicit about the lifetime, which should last at least until the task is finished.
- drop(authfs_lifetime);
+ drop(authfs);
match jail_result {
Ok(_) => Ok(()),
diff --git a/tests/hostside/AndroidTest.xml b/tests/hostside/AndroidTest.xml
index eda733a..e8aced6 100644
--- a/tests/hostside/AndroidTest.xml
+++ b/tests/hostside/AndroidTest.xml
@@ -14,14 +14,6 @@
limitations under the License.
-->
<configuration description="Tests for microdroid">
- <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer">
- <option name="force-root" value="true" />
- </target_preparer>
-
- <!-- virtualizationservice doesn't have access to shell_data_file. Instead of giving it
- a test-only permission, run it without selinux -->
- <target_preparer class="com.android.tradefed.targetprep.DisableSELinuxTargetPreparer"/>
-
<test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
<option name="jar" value="MicrodroidHostTestCases.jar" />
</test>
diff --git a/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java b/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java
index 988b1ad..40debba 100644
--- a/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java
+++ b/tests/hostside/helper/java/android/virt/test/VirtualizationTestCaseBase.java
@@ -84,7 +84,7 @@
// don't run the test (instead of failing)
android.assumeSuccess("ls /dev/kvm");
android.assumeSuccess("ls /dev/vhost-vsock");
- android.assumeSuccess("ls /apex/com.android.virt/bin/crosvm");
+ android.assumeSuccess("ls /apex/com.android.virt");
}
// Run an arbitrary command in the host side and returns the result
@@ -181,7 +181,6 @@
final String debugFlag = debug ? "--debug " : "";
// Run the VM
- android.run("start", "virtualizationservice");
String ret =
android.run(
VIRT_APEX + "bin/vm",
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 12c46ee..1d99c2d 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -16,7 +16,7 @@
use crate::composite::make_composite_image;
use crate::crosvm::{CrosvmConfig, DiskFile, VmInstance};
-use crate::payload::make_payload_disk;
+use crate::payload::add_microdroid_images;
use crate::{Cid, FIRST_GUEST_CID};
use android_os_permissions_aidl::aidl::android::os::IPermissionController;
@@ -38,7 +38,7 @@
use anyhow::{bail, Context, Result};
use disk::QcowFile;
use log::{debug, error, warn, info};
-use microdroid_payload_config::{ApexConfig, VmPayloadConfig};
+use microdroid_payload_config::VmPayloadConfig;
use std::convert::TryInto;
use std::ffi::CString;
use std::fs::{File, OpenOptions, create_dir};
@@ -46,7 +46,7 @@
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, Weak};
-use vmconfig::{VmConfig, Partition};
+use vmconfig::VmConfig;
use vsock::{VsockListener, SockAddr, VsockStream};
use zip::ZipArchive;
@@ -55,11 +55,6 @@
/// Directory in which to write disk image files used while running VMs.
pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
-/// 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"];
-
/// The CID representing the host VM
const VMADDR_CID_HOST: u32 = 2;
@@ -365,53 +360,43 @@
config: &VirtualMachineAppConfig,
temporary_directory: &Path,
) -> Result<VirtualMachineRawConfig> {
- let apk_file = config.apk.as_ref().unwrap().as_ref();
- let idsig_file = config.idsig.as_ref().unwrap().as_ref();
+ let apk_file = clone_file(config.apk.as_ref().unwrap())?;
+ let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
// TODO(b/193504400) pass this to crosvm
- let _instance_file = config.instanceImage.as_ref().unwrap().as_ref();
+ let _instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
let config_path = &config.configPath;
- let mut apk_zip = ZipArchive::new(apk_file)?;
+ let mut apk_zip = ZipArchive::new(&apk_file)?;
let config_file = apk_zip.by_name(config_path)?;
let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
let os_name = &vm_payload_config.os.name;
+
// For now, the only supported "os" value is "microdroid"
if os_name != "microdroid" {
- bail!("unknown os: {}", os_name);
+ bail!("Unknown OS \"{}\"", os_name);
}
+
+ // It is safe to construct a filename based on the os_name because we've already checked that it
+ // is one of the allowed values.
let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
let vm_config_file = File::open(vm_config_path)?;
- let mut vm_config = VmConfig::load(&vm_config_file)?;
+ let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
- // Microdroid requires additional payload disk image and the bootconfig partition
+ // Microdroid requires an additional payload disk image and the bootconfig partition.
if os_name == "microdroid" {
- let mut apexes = vm_payload_config.apexes.clone();
- apexes.extend(
- MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
- );
- apexes.dedup_by(|a, b| a.name == b.name);
-
- vm_config.disks.push(make_payload_disk(
- format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(),
- format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(),
- config_path,
- &apexes,
+ let apexes = vm_payload_config.apexes.clone();
+ add_microdroid_images(
+ config,
temporary_directory,
- )?);
-
- if config.debug {
- vm_config.disks[1].partitions.push(Partition {
- label: "bootconfig".to_owned(),
- paths: vec![PathBuf::from(
- "/apex/com.android.virt/etc/microdroid_bootconfig.debug",
- )],
- writable: false,
- });
- }
+ apk_file,
+ idsig_file,
+ apexes,
+ &mut vm_config,
+ )?;
}
- vm_config.to_parcelable()
+ Ok(vm_config)
}
/// Generates a unique filename to use for a composite disk image.
diff --git a/virtualizationservice/src/payload.rs b/virtualizationservice/src/payload.rs
index 9c6deae..28ef502 100644
--- a/virtualizationservice/src/payload.rs
+++ b/virtualizationservice/src/payload.rs
@@ -14,6 +14,11 @@
//! Payload disk image
+use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
+ DiskImage::DiskImage, Partition::Partition, VirtualMachineAppConfig::VirtualMachineAppConfig,
+ VirtualMachineRawConfig::VirtualMachineRawConfig,
+};
+use android_system_virtualizationservice::binder::ParcelFileDescriptor;
use anyhow::{anyhow, Context, Result};
use microdroid_metadata::{ApexPayload, ApkPayload, Metadata};
use microdroid_payload_config::ApexConfig;
@@ -22,7 +27,12 @@
use serde_xml_rs::from_reader;
use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
-use vmconfig::{DiskImage, Partition};
+use vmconfig::open_parcel_file;
+
+/// 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 APEX_INFO_LIST_PATH: &str = "/apex/apex-info-list.xml";
@@ -65,23 +75,14 @@
}
}
-/// Creates a DiskImage with partitions:
-/// metadata: metadata
-/// microdroid-apex-0: apex 0
-/// microdroid-apex-1: apex 1
-/// ..
-/// microdroid-apk: apk
-/// microdroid-apk-idsig: idsig
-pub fn make_payload_disk(
- apk_file: PathBuf,
- idsig_file: PathBuf,
+fn make_metadata_file(
config_path: &str,
apexes: &[ApexConfig],
temporary_directory: &Path,
-) -> Result<DiskImage> {
+) -> Result<ParcelFileDescriptor> {
let metadata_path = temporary_directory.join("metadata");
let metadata = Metadata {
- version: 1u32,
+ version: 1,
apexes: apexes
.iter()
.map(|apex| ApexPayload { name: apex.name.clone(), ..Default::default() })
@@ -96,35 +97,97 @@
payload_config_path: format!("/mnt/apk/{}", config_path),
..Default::default()
};
- let mut metadata_file =
- OpenOptions::new().create_new(true).read(true).write(true).open(&metadata_path)?;
+
+ // Write metadata to file.
+ let mut metadata_file = OpenOptions::new()
+ .create_new(true)
+ .read(true)
+ .write(true)
+ .open(&metadata_path)
+ .with_context(|| format!("Failed to open metadata file {:?}", metadata_path))?;
microdroid_metadata::write_metadata(&metadata, &mut metadata_file)?;
+ // Re-open the metadata file as read-only.
+ open_parcel_file(&metadata_path, false)
+}
+
+/// Creates a DiskImage with partitions:
+/// metadata: metadata
+/// microdroid-apex-0: apex 0
+/// microdroid-apex-1: apex 1
+/// ..
+/// microdroid-apk: apk
+/// microdroid-apk-idsig: idsig
+fn make_payload_disk(
+ apk_file: File,
+ idsig_file: File,
+ config_path: &str,
+ apexes: &[ApexConfig],
+ temporary_directory: &Path,
+) -> Result<DiskImage> {
+ let metadata_file = make_metadata_file(config_path, apexes, temporary_directory)?;
// put metadata at the first partition
let mut partitions = vec![Partition {
label: "payload-metadata".to_owned(),
- paths: vec![metadata_path],
+ images: vec![metadata_file],
writable: false,
}];
let apex_info_list = ApexInfoList::load()?;
for (i, apex) in apexes.iter().enumerate() {
+ let apex_path = apex_info_list.get_path_for(&apex.name)?;
+ let apex_file = open_parcel_file(&apex_path, false)?;
partitions.push(Partition {
label: format!("microdroid-apex-{}", i),
- paths: vec![apex_info_list.get_path_for(&apex.name)?],
+ images: vec![apex_file],
writable: false,
});
}
partitions.push(Partition {
label: "microdroid-apk".to_owned(),
- paths: vec![apk_file],
+ images: vec![ParcelFileDescriptor::new(apk_file)],
writable: false,
});
partitions.push(Partition {
label: "microdroid-apk-idsig".to_owned(),
- paths: vec![idsig_file],
+ images: vec![ParcelFileDescriptor::new(idsig_file)],
writable: false,
});
Ok(DiskImage { image: None, partitions, writable: false })
}
+
+pub fn add_microdroid_images(
+ config: &VirtualMachineAppConfig,
+ temporary_directory: &Path,
+ apk_file: File,
+ idsig_file: File,
+ mut apexes: Vec<ApexConfig>,
+ vm_config: &mut VirtualMachineRawConfig,
+) -> Result<()> {
+ apexes.extend(
+ MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
+ );
+ apexes.dedup_by(|a, b| a.name == b.name);
+
+ vm_config.disks.push(make_payload_disk(
+ apk_file,
+ idsig_file,
+ &config.configPath,
+ &apexes,
+ temporary_directory,
+ )?);
+
+ if config.debug {
+ vm_config.disks[1].partitions.push(Partition {
+ label: "bootconfig".to_owned(),
+ images: vec![open_parcel_file(
+ Path::new("/apex/com.android.virt/etc/microdroid_bootconfig.debug"),
+ false,
+ )?],
+ writable: false,
+ });
+ }
+
+ Ok(())
+}