Merge changes from topic "pvmfw-libc-bssl"
* changes:
pvmfw: Pass BCC to next stage through DT
pvmfw: Perform DICE derivation
diff --git a/TEST_MAPPING b/TEST_MAPPING
index c37fd19..5a422df 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -13,7 +13,16 @@
"name": "art_standalone_dexpreopt_tests"
},
{
+ "name": "composd_cmd.test"
+ },
+ {
"name": "compos_key_tests"
+ },
+ {
+ "name": "composd_verify.test"
+ },
+ {
+ "name": "initrd_bootconfig.test"
}
],
"avf-postsubmit": [
@@ -43,6 +52,9 @@
"path": "packages/modules/Virtualization/avmd"
},
{
+ "path": "packages/modules/Virtualization/encryptedstore"
+ },
+ {
"path": "packages/modules/Virtualization/virtualizationservice"
},
{
diff --git a/apkdmverity/src/main.rs b/apkdmverity/src/main.rs
index 6e12e38..50b6069 100644
--- a/apkdmverity/src/main.rs
+++ b/apkdmverity/src/main.rs
@@ -23,7 +23,7 @@
use anyhow::{bail, Context, Result};
use apkverify::{HashAlgorithm, V4Signature};
-use clap::{App, Arg};
+use clap::{arg, Arg, ArgAction, Command};
use dm::loopdevice;
use dm::util;
use dm::verity::{DmVerityHashAlgorithm, DmVerityTargetBuilder};
@@ -34,22 +34,12 @@
use std::path::{Path, PathBuf};
fn main() -> Result<()> {
- let matches = App::new("apkdmverity")
- .about("Creates a dm-verity block device out of APK signed with APK signature scheme V4.")
- .arg(Arg::from_usage(
- "--apk... <apk_path> <idsig_path> <name> <root_hash> \
- 'Input APK file, idsig file, name of the block device, and root hash. \
- The APK file must be signed using the APK signature scheme 4. The \
- block device is created at \"/dev/mapper/<name>\".' root_hash is \
- optional; idsig file's root hash will be used if specified as \"none\"."
- ))
- .arg(Arg::with_name("verbose").short('v').long("verbose").help("Shows verbose output"))
- .get_matches();
+ let matches = clap_command().get_matches();
- let apks = matches.values_of("apk").unwrap();
+ let apks = matches.get_many::<String>("apk").unwrap();
assert!(apks.len() % 4 == 0);
- let verbose = matches.is_present("verbose");
+ let verbose = matches.get_flag("verbose");
for (apk, idsig, name, roothash) in apks.tuples() {
let roothash = if roothash != "none" {
@@ -68,6 +58,28 @@
Ok(())
}
+fn clap_command() -> Command {
+ Command::new("apkdmverity")
+ .about("Creates a dm-verity block device out of APK signed with APK signature scheme V4.")
+ .arg(
+ arg!(--apk ...
+ "Input APK file, idsig file, name of the block device, and root hash. \
+ The APK file must be signed using the APK signature scheme 4. The \
+ block device is created at \"/dev/mapper/<name>\".' root_hash is \
+ optional; idsig file's root hash will be used if specified as \"none\"."
+ )
+ .action(ArgAction::Append)
+ .value_names(&["apk_path", "idsig_path", "name", "root_hash"]),
+ )
+ .arg(
+ Arg::new("verbose")
+ .short('v')
+ .long("verbose")
+ .action(ArgAction::SetTrue)
+ .help("Shows verbose output"),
+ )
+}
+
struct VerityResult {
data_device: PathBuf,
hash_device: PathBuf,
@@ -380,4 +392,10 @@
},
);
}
+
+ #[test]
+ fn verify_command() {
+ // Check that the command parsing has been configured in a valid way.
+ clap_command().debug_assert();
+ }
}
diff --git a/authfs/TEST_MAPPING b/authfs/TEST_MAPPING
index ab6111b..450f133 100644
--- a/authfs/TEST_MAPPING
+++ b/authfs/TEST_MAPPING
@@ -4,6 +4,12 @@
"name": "authfs_device_test_src_lib"
},
{
+ "name": "fd_server.test"
+ },
+ {
+ "name": "open_then_run.test"
+ },
+ {
"name": "AuthFsHostTest"
}
],
diff --git a/authfs/fd_server/Android.bp b/authfs/fd_server/Android.bp
index 44407a2..f7cb5e3 100644
--- a/authfs/fd_server/Android.bp
+++ b/authfs/fd_server/Android.bp
@@ -23,3 +23,25 @@
],
apex_available: ["com.android.virt"],
}
+
+rust_test {
+ name: "fd_server.test",
+ srcs: ["src/main.rs"],
+ rustlibs: [
+ "authfs_aidl_interface-rust",
+ "libandroid_logger",
+ "libanyhow",
+ "libauthfs_fsverity_metadata",
+ "libbinder_rs",
+ "libclap",
+ "liblibc",
+ "liblog_rust",
+ "libnix",
+ "librpcbinder_rs",
+ ],
+ prefer_rlib: true,
+ shared_libs: [
+ "libbinder_rpc_unstable",
+ ],
+ test_suites: ["general-tests"],
+}
diff --git a/authfs/fd_server/src/main.rs b/authfs/fd_server/src/main.rs
index 9d97423..f91ebec 100644
--- a/authfs/fd_server/src/main.rs
+++ b/authfs/fd_server/src/main.rs
@@ -148,3 +148,15 @@
server.join();
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use clap::CommandFactory;
+
+ #[test]
+ fn verify_args() {
+ // Check that the command parsing has been configured in a valid way.
+ Args::command().debug_assert();
+ }
+}
diff --git a/authfs/tests/common/Android.bp b/authfs/tests/common/Android.bp
index ec426c7..01ebcfd 100644
--- a/authfs/tests/common/Android.bp
+++ b/authfs/tests/common/Android.bp
@@ -31,3 +31,19 @@
test_suites: ["general-tests"],
test_harness: false,
}
+
+rust_test {
+ name: "open_then_run.test",
+ crate_name: "open_then_run",
+ srcs: ["src/open_then_run.rs"],
+ edition: "2021",
+ rustlibs: [
+ "libandroid_logger",
+ "libanyhow",
+ "libclap",
+ "libcommand_fds",
+ "liblibc",
+ "liblog_rust",
+ ],
+ test_suites: ["general-tests"],
+}
diff --git a/authfs/tests/common/src/open_then_run.rs b/authfs/tests/common/src/open_then_run.rs
index 110d838..6d828e4 100644
--- a/authfs/tests/common/src/open_then_run.rs
+++ b/authfs/tests/common/src/open_then_run.rs
@@ -19,7 +19,7 @@
//! specified numbers in the child process.
use anyhow::{bail, Context, Result};
-use clap::{App, Arg, Values};
+use clap::{parser::ValuesRef, Arg, ArgAction};
use command_fds::{CommandFdExt, FdMapping};
use log::{debug, error};
use std::fs::OpenOptions;
@@ -51,7 +51,7 @@
}
fn parse_and_create_file_mapping<F>(
- values: Option<Values<'_>>,
+ values: Option<ValuesRef<'_, String>>,
opener: F,
) -> Result<Vec<OwnedFdMapping>>
where
@@ -75,35 +75,35 @@
}
}
-fn parse_args() -> Result<Args> {
- #[rustfmt::skip]
- let matches = App::new("open_then_run")
- .arg(Arg::with_name("open-ro")
+#[rustfmt::skip]
+fn args_command() -> clap::Command {
+ clap::Command::new("open_then_run")
+ .arg(Arg::new("open-ro")
.long("open-ro")
.value_name("FD:PATH")
.help("Open <PATH> read-only to pass as fd <FD>")
- .multiple(true)
- .number_of_values(1))
- .arg(Arg::with_name("open-rw")
+ .action(ArgAction::Append))
+ .arg(Arg::new("open-rw")
.long("open-rw")
.value_name("FD:PATH")
.help("Open/create <PATH> read-write to pass as fd <FD>")
- .multiple(true)
- .number_of_values(1))
- .arg(Arg::with_name("open-dir")
+ .action(ArgAction::Append))
+ .arg(Arg::new("open-dir")
.long("open-dir")
.value_name("FD:DIR")
.help("Open <DIR> to pass as fd <FD>")
- .multiple(true)
- .number_of_values(1))
- .arg(Arg::with_name("args")
+ .action(ArgAction::Append))
+ .arg(Arg::new("args")
.help("Command line to execute with pre-opened FD inherited")
.last(true)
.required(true)
- .multiple(true))
- .get_matches();
+ .num_args(0..))
+}
- let ro_file_fds = parse_and_create_file_mapping(matches.values_of("open-ro"), |path| {
+fn parse_args() -> Result<Args> {
+ let matches = args_command().get_matches();
+
+ let ro_file_fds = parse_and_create_file_mapping(matches.get_many("open-ro"), |path| {
Ok(OwnedFd::from(
OpenOptions::new()
.read(true)
@@ -112,7 +112,7 @@
))
})?;
- let rw_file_fds = parse_and_create_file_mapping(matches.values_of("open-rw"), |path| {
+ let rw_file_fds = parse_and_create_file_mapping(matches.get_many("open-rw"), |path| {
Ok(OwnedFd::from(
OpenOptions::new()
.read(true)
@@ -123,7 +123,7 @@
))
})?;
- let dir_fds = parse_and_create_file_mapping(matches.values_of("open-dir"), |path| {
+ let dir_fds = parse_and_create_file_mapping(matches.get_many("open-dir"), |path| {
Ok(OwnedFd::from(
OpenOptions::new()
.custom_flags(libc::O_DIRECTORY)
@@ -133,7 +133,8 @@
))
})?;
- let cmdline_args: Vec<_> = matches.values_of("args").unwrap().map(|s| s.to_string()).collect();
+ let cmdline_args: Vec<_> =
+ matches.get_many::<String>("args").unwrap().map(|s| s.to_string()).collect();
Ok(Args { ro_file_fds, rw_file_fds, dir_fds, cmdline_args })
}
@@ -168,3 +169,14 @@
std::process::exit(1);
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn verify_command() {
+ // Check that the command parsing has been configured in a valid way.
+ args_command().debug_assert();
+ }
+}
diff --git a/avmd/Android.bp b/avmd/Android.bp
index 0b87a7b..e5e0553 100644
--- a/avmd/Android.bp
+++ b/avmd/Android.bp
@@ -20,8 +20,8 @@
defaults: ["libavmd_defaults"],
}
-rust_binary {
- name: "avmdtool",
+rust_defaults {
+ name: "avmdtool.defaults",
srcs: ["src/main.rs"],
host_supported: true,
prefer_rlib: true,
@@ -37,6 +37,17 @@
],
}
+rust_binary {
+ name: "avmdtool",
+ defaults: ["avmdtool.defaults"],
+}
+
+rust_test {
+ name: "avmdtool.test",
+ defaults: ["avmdtool.defaults"],
+ test_suites: ["general-tests"],
+}
+
rust_test {
name: "avmdtool_tests",
srcs: ["tests/*_test.rs"],
diff --git a/avmd/TEST_MAPPING b/avmd/TEST_MAPPING
index ea58edb..892eb2c 100644
--- a/avmd/TEST_MAPPING
+++ b/avmd/TEST_MAPPING
@@ -1,7 +1,10 @@
{
- "avf-presubmit" : [
+ "avf-presubmit": [
{
- "name" : "avmdtool_tests"
+ "name": "avmdtool.test"
+ },
+ {
+ "name": "avmdtool_tests"
}
]
}
diff --git a/avmd/src/main.rs b/avmd/src/main.rs
index fc18225..740e9aa 100644
--- a/avmd/src/main.rs
+++ b/avmd/src/main.rs
@@ -18,9 +18,13 @@
use apexutil::get_payload_vbmeta_image_hash;
use apkverify::get_apk_digest;
use avmd::{ApkDescriptor, Avmd, Descriptor, ResourceIdentifier, VbMetaDescriptor};
-use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
+use clap::{
+ builder::ValueParser,
+ parser::{Indices, ValuesRef},
+ Arg, ArgAction, ArgMatches, Command,
+};
use serde::ser::Serialize;
-use std::fs::File;
+use std::{fs::File, path::PathBuf};
use vbmeta::VbMetaImage;
fn get_vbmeta_image_hash(file: &str) -> Result<Vec<u8>> {
@@ -31,13 +35,13 @@
/// Iterate over a set of argument values, that could be empty or come in
/// (<index>, <namespace>, <name>, <file>) tuple.
struct NamespaceNameFileIterator<'a> {
- indices: Option<clap::Indices<'a>>,
- values: Option<clap::Values<'a>>,
+ indices: Option<Indices<'a>>,
+ values: Option<ValuesRef<'a, String>>,
}
impl<'a> NamespaceNameFileIterator<'a> {
fn new(args: &'a ArgMatches, name: &'a str) -> Self {
- NamespaceNameFileIterator { indices: args.indices_of(name), values: args.values_of(name) }
+ NamespaceNameFileIterator { indices: args.indices_of(name), values: args.get_many(name) }
}
}
@@ -100,54 +104,58 @@
.packed_format()
.legacy_enums(),
)?;
- std::fs::write(args.value_of("file").unwrap(), &bytes)?;
+ std::fs::write(args.get_one::<PathBuf>("file").unwrap(), &bytes)?;
Ok(())
}
fn dump(args: &ArgMatches) -> Result<()> {
- let file = std::fs::read(args.value_of("file").unwrap())?;
+ let file = std::fs::read(args.get_one::<PathBuf>("file").unwrap())?;
let avmd: Avmd = serde_cbor::from_slice(&file)?;
println!("{}", avmd);
Ok(())
}
-fn main() -> Result<()> {
+fn clap_command() -> Command {
let namespace_name_file = ["namespace", "name", "file"];
- let app = App::new("avmdtool")
- .setting(AppSettings::SubcommandRequiredElseHelp)
+
+ Command::new("avmdtool")
+ .subcommand_required(true)
+ .arg_required_else_help(true)
.subcommand(
- SubCommand::with_name("create")
- .setting(AppSettings::ArgRequiredElseHelp)
- .arg(Arg::with_name("file").required(true).takes_value(true))
+ Command::new("create")
+ .arg_required_else_help(true)
+ .arg(Arg::new("file").value_parser(ValueParser::path_buf()).required(true))
.arg(
- Arg::with_name("vbmeta")
+ Arg::new("vbmeta")
.long("vbmeta")
- .takes_value(true)
.value_names(&namespace_name_file)
- .multiple(true),
+ .num_args(3)
+ .action(ArgAction::Append),
)
.arg(
- Arg::with_name("apk")
+ Arg::new("apk")
.long("apk")
- .takes_value(true)
.value_names(&namespace_name_file)
- .multiple(true),
+ .num_args(3)
+ .action(ArgAction::Append),
)
.arg(
- Arg::with_name("apex-payload")
+ Arg::new("apex-payload")
.long("apex-payload")
- .takes_value(true)
.value_names(&namespace_name_file)
- .multiple(true),
+ .num_args(3)
+ .action(ArgAction::Append),
),
)
.subcommand(
- SubCommand::with_name("dump")
- .setting(AppSettings::ArgRequiredElseHelp)
- .arg(Arg::with_name("file").required(true).takes_value(true)),
- );
+ Command::new("dump")
+ .arg_required_else_help(true)
+ .arg(Arg::new("file").value_parser(ValueParser::path_buf()).required(true)),
+ )
+}
- let args = app.get_matches();
+fn main() -> Result<()> {
+ let args = clap_command().get_matches();
match args.subcommand() {
Some(("create", sub_args)) => create(sub_args)?,
Some(("dump", sub_args)) => dump(sub_args)?,
@@ -155,3 +163,14 @@
}
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn verify_command() {
+ // Check that the command parsing has been configured in a valid way.
+ clap_command().debug_assert();
+ }
+}
diff --git a/compos/common/compos_client.rs b/compos/common/compos_client.rs
index 34be1d5..f6811cb 100644
--- a/compos/common/compos_client.rs
+++ b/compos/common/compos_client.rs
@@ -222,10 +222,10 @@
bail!("Protected VM not supported, unable to start VM");
}
- let have_unprotected_vm =
+ let have_non_protected_vm =
system_properties::read_bool("ro.boot.hypervisor.vm.supported", false)?;
- if have_unprotected_vm {
- warn!("Protected VM not supported, falling back to unprotected on debuggable build");
+ if have_non_protected_vm {
+ warn!("Protected VM not supported, falling back to non-protected on debuggable build");
return Ok(false);
}
diff --git a/compos/composd_cmd/Android.bp b/compos/composd_cmd/Android.bp
index 61df328..54b0bad 100644
--- a/compos/composd_cmd/Android.bp
+++ b/compos/composd_cmd/Android.bp
@@ -18,3 +18,18 @@
"com.android.compos",
],
}
+
+rust_test {
+ name: "composd_cmd.test",
+ srcs: ["composd_cmd.rs"],
+ edition: "2021",
+ rustlibs: [
+ "android.system.composd-rust",
+ "libanyhow",
+ "libbinder_rs",
+ "libclap",
+ "libcompos_common",
+ ],
+ prefer_rlib: true,
+ test_suites: ["general-tests"],
+}
diff --git a/compos/composd_cmd/composd_cmd.rs b/compos/composd_cmd/composd_cmd.rs
index b6d82aa..19c3720 100644
--- a/compos/composd_cmd/composd_cmd.rs
+++ b/compos/composd_cmd/composd_cmd.rs
@@ -163,3 +163,15 @@
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use clap::CommandFactory;
+
+ #[test]
+ fn verify_actions() {
+ // Check that the command parsing has been configured in a valid way.
+ Actions::command().debug_assert();
+ }
+}
diff --git a/compos/verify/Android.bp b/compos/verify/Android.bp
index f68cc1b..9e30b0d 100644
--- a/compos/verify/Android.bp
+++ b/compos/verify/Android.bp
@@ -22,3 +22,22 @@
"com.android.compos",
],
}
+
+rust_test {
+ name: "compos_verify.test",
+ srcs: ["verify.rs"],
+ edition: "2021",
+ rustlibs: [
+ "compos_aidl_interface-rust",
+ "libandroid_logger",
+ "libanyhow",
+ "libbinder_rs",
+ "libclap",
+ "libcompos_common",
+ "libcompos_verify_native_rust",
+ "liblog_rust",
+ "libvmclient",
+ ],
+ prefer_rlib: true,
+ test_suites: ["general-tests"],
+}
diff --git a/compos/verify/verify.rs b/compos/verify/verify.rs
index 745d5e9..71d8bcc 100644
--- a/compos/verify/verify.rs
+++ b/compos/verify/verify.rs
@@ -138,3 +138,15 @@
file.read_to_end(&mut data)?;
Ok(data)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use clap::CommandFactory;
+
+ #[test]
+ fn verify_args() {
+ // Check that the command parsing has been configured in a valid way.
+ Args::command().debug_assert();
+ }
+}
diff --git a/encryptedstore/Android.bp b/encryptedstore/Android.bp
index 13ef1b9..94ebcfc 100644
--- a/encryptedstore/Android.bp
+++ b/encryptedstore/Android.bp
@@ -29,3 +29,9 @@
defaults: ["encryptedstore.defaults"],
bootstrap: true,
}
+
+rust_test {
+ name: "encryptedstore.test",
+ defaults: ["encryptedstore.defaults"],
+ test_suites: ["general-tests"],
+}
diff --git a/encryptedstore/TEST_MAPPING b/encryptedstore/TEST_MAPPING
new file mode 100644
index 0000000..a9e1d87
--- /dev/null
+++ b/encryptedstore/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "avf-presubmit": [
+ {
+ "name": "encryptedstore.test"
+ }
+ ]
+}
diff --git a/encryptedstore/src/main.rs b/encryptedstore/src/main.rs
index 7140ae2..888485b 100644
--- a/encryptedstore/src/main.rs
+++ b/encryptedstore/src/main.rs
@@ -19,9 +19,8 @@
//! It uses dm_rust lib.
use anyhow::{ensure, Context, Result};
-use clap::{arg, App};
-use dm::crypt::CipherType;
-use dm::util;
+use clap::arg;
+use dm::{crypt::CipherType, util};
use log::info;
use std::ffi::CString;
use std::fs::{create_dir_all, OpenOptions};
@@ -42,18 +41,11 @@
);
info!("Starting encryptedstore binary");
- let matches = App::new("encryptedstore")
- .args(&[
- arg!(--blkdevice <FILE> "the block device backing the encrypted storage")
- .required(true),
- arg!(--key <KEY> "key (in hex) equivalent to 32 bytes)").required(true),
- arg!(--mountpoint <MOUNTPOINT> "mount point for the storage").required(true),
- ])
- .get_matches();
+ let matches = clap_command().get_matches();
- let blkdevice = Path::new(matches.value_of("blkdevice").unwrap());
- let key = matches.value_of("key").unwrap();
- let mountpoint = Path::new(matches.value_of("mountpoint").unwrap());
+ let blkdevice = Path::new(matches.get_one::<String>("blkdevice").unwrap());
+ let key = matches.get_one::<String>("key").unwrap();
+ let mountpoint = Path::new(matches.get_one::<String>("mountpoint").unwrap());
encryptedstore_init(blkdevice, key, mountpoint).context(format!(
"Unable to initialize encryptedstore on {:?} & mount at {:?}",
blkdevice, mountpoint
@@ -61,6 +53,14 @@
Ok(())
}
+fn clap_command() -> clap::Command {
+ clap::Command::new("encryptedstore").args(&[
+ arg!(--blkdevice <FILE> "the block device backing the encrypted storage").required(true),
+ arg!(--key <KEY> "key (in hex) equivalent to 32 bytes)").required(true),
+ arg!(--mountpoint <MOUNTPOINT> "mount point for the storage").required(true),
+ ])
+}
+
fn encryptedstore_init(blkdevice: &Path, key: &str, mountpoint: &Path) -> Result<()> {
ensure!(
std::fs::metadata(&blkdevice)
@@ -160,3 +160,14 @@
Ok(())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn verify_command() {
+ // Check that the command parsing has been configured in a valid way.
+ clap_command().debug_assert();
+ }
+}
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachine.java b/javalib/src/android/system/virtualmachine/VirtualMachine.java
index e319aa3..b57cb5e 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachine.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachine.java
@@ -192,9 +192,6 @@
/** Name of the idsig files for extra APKs. */
private static final String EXTRA_IDSIG_FILE_PREFIX = "extra_idsig_";
- /** Name of the virtualization service. */
- private static final String SERVICE_NAME = "android.system.virtualizationservice";
-
/** Size of the instance image. 10 MB. */
private static final long INSTANCE_FILE_SIZE = 10 * 1024 * 1024;
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
index 0e9e86b..d9fc70c 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -352,6 +352,7 @@
* that would alter the identity of the VM (e.g. using a different payload or changing the debug
* mode) are considered incompatible.
*
+ * @see VirtualMachine#setConfig
* @hide
*/
@SystemApi
@@ -536,6 +537,14 @@
/**
* Sets the debug level. Defaults to {@link #DEBUG_LEVEL_NONE}.
*
+ * <p>If {@link #DEBUG_LEVEL_FULL} is set then logs from inside the VM are exported to the
+ * host and adb connections from the host are possible. This is convenient for debugging but
+ * may compromise the integrity of the VM - including bypassing the protections offered by a
+ * {@linkplain #setProtectedVm protected VM}.
+ *
+ * <p>Note that it isn't possible to {@linkplain #isCompatibleWith change} the debug level
+ * of a VM instance; debug and non-debug VMs always have different secrets.
+ *
* @hide
*/
@SystemApi
@@ -552,6 +561,13 @@
* Sets whether to protect the VM memory from the host. No default is provided, this must be
* set explicitly.
*
+ * <p>Note that if debugging is {@linkplain #setDebugLevel enabled} for a protected VM, the
+ * VM is not truly protected - direct memory access by the host is prevented, but e.g. the
+ * debugger can be used to access the VM's internals.
+ *
+ * <p>It isn't possible to {@linkplain #isCompatibleWith change} the protected status of a
+ * VM instance; protected and non-protected VMs always have different secrets.
+ *
* @see VirtualMachineManager#getCapabilities
* @hide
*/
@@ -566,7 +582,7 @@
} else {
if (!HypervisorProperties.hypervisor_vm_supported().orElse(false)) {
throw new UnsupportedOperationException(
- "Unprotected VMs are not supported on this device.");
+ "Non-protected VMs are not supported on this device.");
}
}
mProtectedVm = protectedVm;
diff --git a/javalib/src/android/system/virtualmachine/VirtualizationService.java b/javalib/src/android/system/virtualmachine/VirtualizationService.java
index 75e359f..c3f2ba3 100644
--- a/javalib/src/android/system/virtualmachine/VirtualizationService.java
+++ b/javalib/src/android/system/virtualmachine/VirtualizationService.java
@@ -39,7 +39,7 @@
* Client FD for UDS connection to virtmgr's RpcBinder server. Closing it
* will make virtmgr shut down.
*/
- private ParcelFileDescriptor mClientFd;
+ private final ParcelFileDescriptor mClientFd;
private static native int nativeSpawn();
@@ -86,7 +86,7 @@
VirtualizationService service = (sInstance == null) ? null : sInstance.get();
if (service == null || !service.isOk()) {
service = new VirtualizationService();
- sInstance = new WeakReference(service);
+ sInstance = new WeakReference<>(service);
}
return service;
}
diff --git a/microdroid/Android.bp b/microdroid/Android.bp
index ecaadf8..1fc44a2 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -538,11 +538,51 @@
srcs: ["bootconfig.normal"],
}
+// python -c "import hashlib; print(hashlib.sha256(b'initrd_normal').hexdigest())"
+initrd_normal_salt = "8041a07d54ac82290f6d90bac1fa8d7fdbc4db974d101d60faf294749d1ebaf8"
+
+avb_gen_vbmeta_image {
+ name: "microdroid_initrd_normal_hashdesc",
+ src: ":microdroid_initrd_normal",
+ partition_name: "initrd_normal",
+ salt: initrd_normal_salt,
+ enabled: false,
+ arch: {
+ // Microdroid kernel is only available in these architectures.
+ arm64: {
+ enabled: true,
+ },
+ x86_64: {
+ enabled: true,
+ },
+ },
+}
+
+// python -c "import hashlib; print(hashlib.sha256(b'initrd_debug').hexdigest())"
+initrd_debug_salt = "8ab9dc9cb7e6456700ff6ef18c6b4c3acc24c5fa5381b829563f8d7a415d869a"
+
+avb_gen_vbmeta_image {
+ name: "microdroid_initrd_debug_hashdesc",
+ src: ":microdroid_initrd_debuggable",
+ partition_name: "initrd_debug",
+ salt: initrd_debug_salt,
+ enabled: false,
+ arch: {
+ // Microdroid kernel is only available in these architectures.
+ arm64: {
+ enabled: true,
+ },
+ x86_64: {
+ enabled: true,
+ },
+ },
+}
+
avb_add_hash_footer {
name: "microdroid_kernel_signed",
src: "empty_kernel",
filename: "microdroid_kernel",
- partition_name: "bootloader",
+ partition_name: "boot",
private_key: ":microdroid_sign_key",
salt: bootloader_salt,
enabled: false,
@@ -556,11 +596,9 @@
enabled: true,
},
},
- props: [
- {
- name: "trusted_ramdisk",
- file: ":microdroid_initrd_hashes",
- },
+ include_descriptors_from_images: [
+ ":microdroid_initrd_normal_hashdesc",
+ ":microdroid_initrd_debug_hashdesc",
],
}
diff --git a/microdroid/init.rc b/microdroid/init.rc
index 7402481..bc42791 100644
--- a/microdroid/init.rc
+++ b/microdroid/init.rc
@@ -165,7 +165,6 @@
class core
critical
seclabel u:r:ueventd:s0
- shutdown critical
capabilities CHOWN DAC_OVERRIDE DAC_READ_SEARCH FOWNER FSETID MKNOD NET_ADMIN SETGID SETUID SYS_MODULE SYS_RAWIO
service console /system/bin/sh
diff --git a/microdroid/initrd/Android.bp b/microdroid/initrd/Android.bp
index d05ea86..7a95ce6 100644
--- a/microdroid/initrd/Android.bp
+++ b/microdroid/initrd/Android.bp
@@ -12,6 +12,17 @@
prefer_rlib: true,
}
+rust_test_host {
+ name: "initrd_bootconfig.test",
+ srcs: ["src/main.rs"],
+ rustlibs: [
+ "libanyhow",
+ "libclap",
+ ],
+ prefer_rlib: true,
+ test_suites: ["general-tests"],
+}
+
python_binary_host {
name: "gen_vbmeta_bootconfig",
srcs: ["gen_vbmeta_bootconfig.py"],
@@ -122,28 +133,3 @@
},
filename: "microdroid_initrd_normal.img",
}
-
-genrule {
- name: "microdroid_initrd_normal.sha256",
- srcs: [":microdroid_initrd_normal"],
- cmd: "cat $(in) | sha256sum | cut -d' ' -f1 > $(out)",
- out: ["hash"],
-}
-
-genrule {
- name: "microdroid_initrd_debuggable.sha256",
- srcs: [":microdroid_initrd_debuggable"],
- cmd: "cat $(in) | sha256sum | cut -d' ' -f1 > $(out)",
- out: ["hash"],
-}
-
-genrule {
- name: "microdroid_initrd_hashes",
- srcs: [
- ":microdroid_initrd_normal.sha256",
- ":microdroid_initrd_debuggable.sha256",
- ],
- // join the hashes with commas
- cmd: "cat $(in) | tr '\n' ',' > $(out) && truncate -s -1 $(out)",
- out: ["output"],
-}
diff --git a/microdroid/initrd/src/main.rs b/microdroid/initrd/src/main.rs
index 69c6ae4..74e4ba6 100644
--- a/microdroid/initrd/src/main.rs
+++ b/microdroid/initrd/src/main.rs
@@ -54,7 +54,8 @@
checksum += get_checksum(&bootconfig)?;
}
- let padding_size: usize = FOOTER_ALIGNMENT - (initrd_size + bootconfig_size) % FOOTER_ALIGNMENT;
+ let padding_size: usize =
+ (FOOTER_ALIGNMENT - (initrd_size + bootconfig_size) % FOOTER_ALIGNMENT) % FOOTER_ALIGNMENT;
output_file.write_all(&ZEROS[..padding_size])?;
output_file.write_all(&((padding_size + bootconfig_size) as u32).to_le_bytes())?;
output_file.write_all(&checksum.to_le_bytes())?;
@@ -72,3 +73,15 @@
fn main() {
try_main().unwrap()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use clap::CommandFactory;
+
+ #[test]
+ fn verify_args() {
+ // Check that the command parsing has been configured in a valid way.
+ Args::command().debug_assert();
+ }
+}
diff --git a/pvmfw/avb/Android.bp b/pvmfw/avb/Android.bp
index 3026d20..d3a5e4e 100644
--- a/pvmfw/avb/Android.bp
+++ b/pvmfw/avb/Android.bp
@@ -32,6 +32,8 @@
":avb_testkey_rsa2048_pub_bin",
":avb_testkey_rsa4096_pub_bin",
":microdroid_kernel_signed",
+ ":microdroid_initrd_normal",
+ ":test_image_with_one_hashdesc",
":unsigned_test_image",
],
rustlibs: [
@@ -56,3 +58,11 @@
out: ["unsigned_test.img"],
cmd: "$(location avbtool) generate_test_image --image_size 16384 --output $(out)",
}
+
+avb_add_hash_footer {
+ name: "test_image_with_one_hashdesc",
+ src: ":unsigned_test_image",
+ partition_name: "boot",
+ private_key: ":pvmfw_sign_key",
+ salt: "1111",
+}
diff --git a/pvmfw/avb/src/error.rs b/pvmfw/avb/src/error.rs
new file mode 100644
index 0000000..8b06150
--- /dev/null
+++ b/pvmfw/avb/src/error.rs
@@ -0,0 +1,87 @@
+// Copyright 2022, 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.
+
+//! This module contains the error thrown by the payload verification API.
+
+use avb_bindgen::AvbSlotVerifyResult;
+
+use core::fmt;
+
+/// This error is the error part of `AvbSlotVerifyResult`.
+/// It is the error thrown by the payload verification API `verify_payload()`.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum AvbSlotVerifyError {
+ /// AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT
+ InvalidArgument,
+ /// AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA
+ InvalidMetadata,
+ /// AVB_SLOT_VERIFY_RESULT_ERROR_IO
+ Io,
+ /// AVB_SLOT_VERIFY_RESULT_ERROR_OOM
+ Oom,
+ /// AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED
+ PublicKeyRejected,
+ /// AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX
+ RollbackIndex,
+ /// AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION
+ UnsupportedVersion,
+ /// AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION
+ Verification,
+}
+
+impl fmt::Display for AvbSlotVerifyError {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self {
+ Self::InvalidArgument => write!(f, "Invalid parameters."),
+ Self::InvalidMetadata => write!(f, "Invalid metadata."),
+ Self::Io => write!(f, "I/O error while trying to load data or get a rollback index."),
+ Self::Oom => write!(f, "Unable to allocate memory."),
+ Self::PublicKeyRejected => write!(f, "Public key rejected or data not signed."),
+ Self::RollbackIndex => write!(f, "Rollback index is less than its stored value."),
+ Self::UnsupportedVersion => write!(
+ f,
+ "Some of the metadata requires a newer version of libavb than what is in use."
+ ),
+ Self::Verification => write!(f, "Data does not verify."),
+ }
+ }
+}
+
+pub(crate) fn slot_verify_result_to_verify_payload_result(
+ result: AvbSlotVerifyResult,
+) -> Result<(), AvbSlotVerifyError> {
+ match result {
+ AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_OK => Ok(()),
+ AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT => {
+ Err(AvbSlotVerifyError::InvalidArgument)
+ }
+ AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA => {
+ Err(AvbSlotVerifyError::InvalidMetadata)
+ }
+ AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_IO => Err(AvbSlotVerifyError::Io),
+ AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_OOM => Err(AvbSlotVerifyError::Oom),
+ AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED => {
+ Err(AvbSlotVerifyError::PublicKeyRejected)
+ }
+ AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX => {
+ Err(AvbSlotVerifyError::RollbackIndex)
+ }
+ AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION => {
+ Err(AvbSlotVerifyError::UnsupportedVersion)
+ }
+ AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION => {
+ Err(AvbSlotVerifyError::Verification)
+ }
+ }
+}
diff --git a/pvmfw/avb/src/lib.rs b/pvmfw/avb/src/lib.rs
index 1f39076..6a5b16d 100644
--- a/pvmfw/avb/src/lib.rs
+++ b/pvmfw/avb/src/lib.rs
@@ -18,6 +18,8 @@
// For usize.checked_add_signed(isize), available in Rust 1.66.0
#![feature(mixed_integer_ops)]
+mod error;
mod verify;
-pub use verify::{verify_payload, AvbImageVerifyError};
+pub use error::AvbSlotVerifyError;
+pub use verify::verify_payload;
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index f01c6b8..fb18626 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -14,81 +14,15 @@
//! This module handles the pvmfw payload verification.
-use avb_bindgen::{
- avb_slot_verify, AvbHashtreeErrorMode, AvbIOResult, AvbOps, AvbSlotVerifyFlags,
- AvbSlotVerifyResult,
-};
+use crate::error::{slot_verify_result_to_verify_payload_result, AvbSlotVerifyError};
+use avb_bindgen::{avb_slot_verify, AvbHashtreeErrorMode, AvbIOResult, AvbOps, AvbSlotVerifyFlags};
use core::{
ffi::{c_char, c_void, CStr},
- fmt,
ptr::{self, NonNull},
slice,
};
-/// Error code from AVB image verification.
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub enum AvbImageVerifyError {
- /// AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT
- InvalidArgument,
- /// AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA
- InvalidMetadata,
- /// AVB_SLOT_VERIFY_RESULT_ERROR_IO
- Io,
- /// AVB_SLOT_VERIFY_RESULT_ERROR_OOM
- Oom,
- /// AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED
- PublicKeyRejected,
- /// AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX
- RollbackIndex,
- /// AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION
- UnsupportedVersion,
- /// AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION
- Verification,
-}
-
-impl fmt::Display for AvbImageVerifyError {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- Self::InvalidArgument => write!(f, "Invalid parameters."),
- Self::InvalidMetadata => write!(f, "Invalid metadata."),
- Self::Io => write!(f, "I/O error while trying to load data or get a rollback index."),
- Self::Oom => write!(f, "Unable to allocate memory."),
- Self::PublicKeyRejected => write!(f, "Public key rejected or data not signed."),
- Self::RollbackIndex => write!(f, "Rollback index is less than its stored value."),
- Self::UnsupportedVersion => write!(
- f,
- "Some of the metadata requires a newer version of libavb than what is in use."
- ),
- Self::Verification => write!(f, "Data does not verify."),
- }
- }
-}
-
-fn to_avb_verify_result(result: AvbSlotVerifyResult) -> Result<(), AvbImageVerifyError> {
- match result {
- AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_OK => Ok(()),
- AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT => {
- Err(AvbImageVerifyError::InvalidArgument)
- }
- AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA => {
- Err(AvbImageVerifyError::InvalidMetadata)
- }
- AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_IO => Err(AvbImageVerifyError::Io),
- AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_OOM => Err(AvbImageVerifyError::Oom),
- AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED => {
- Err(AvbImageVerifyError::PublicKeyRejected)
- }
- AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX => {
- Err(AvbImageVerifyError::RollbackIndex)
- }
- AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION => {
- Err(AvbImageVerifyError::UnsupportedVersion)
- }
- AvbSlotVerifyResult::AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION => {
- Err(AvbImageVerifyError::Verification)
- }
- }
-}
+static NULL_BYTE: &[u8] = b"\0";
enum AvbIOError {
/// AVB_IO_RESULT_ERROR_OOM,
@@ -167,7 +101,7 @@
out_pointer: *mut *mut u8,
out_num_bytes_preloaded: *mut usize,
) -> Result<(), AvbIOError> {
- let ops = as_avbops_ref(ops)?;
+ let ops = as_ref(ops)?;
let partition = ops.as_ref().get_partition(partition)?;
let out_pointer = to_nonnull(out_pointer)?;
// SAFETY: It is safe as the raw pointer `out_pointer` is a nonnull pointer.
@@ -209,7 +143,7 @@
buffer: *mut c_void,
out_num_read: *mut usize,
) -> Result<(), AvbIOError> {
- let ops = as_avbops_ref(ops)?;
+ let ops = as_ref(ops)?;
let partition = ops.as_ref().get_partition(partition)?;
let buffer = to_nonnull(buffer)?;
// SAFETY: It is safe to copy the requested number of bytes to `buffer` as `buffer`
@@ -251,7 +185,7 @@
partition: *const c_char,
out_size_num_bytes: *mut u64,
) -> Result<(), AvbIOError> {
- let ops = as_avbops_ref(ops)?;
+ let ops = as_ref(ops)?;
let partition = ops.as_ref().get_partition(partition)?;
let partition_size =
u64::try_from(partition.len()).map_err(|_| AvbIOError::InvalidValueSize)?;
@@ -322,7 +256,7 @@
// `public_key_data` is a valid pointer and it points to an array of length
// `public_key_length`.
let public_key = unsafe { slice::from_raw_parts(public_key_data, public_key_length) };
- let ops = as_avbops_ref(ops)?;
+ let ops = as_ref(ops)?;
// Verifies the public key for the known partitions only.
ops.as_ref().get_partition(partition)?;
let trusted_public_key = ops.as_ref().trusted_public_key;
@@ -334,14 +268,14 @@
Ok(())
}
-fn as_avbops_ref<'a>(ops: *mut AvbOps) -> Result<&'a AvbOps, AvbIOError> {
- let ops = to_nonnull(ops)?;
- // SAFETY: It is safe as the raw pointer `ops` is a nonnull pointer.
- unsafe { Ok(ops.as_ref()) }
+fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
+ let ptr = to_nonnull(ptr)?;
+ // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
+ unsafe { Ok(ptr.as_ref()) }
}
-fn to_nonnull<T>(p: *mut T) -> Result<NonNull<T>, AvbIOError> {
- NonNull::new(p).ok_or(AvbIOError::NoSuchValue)
+fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
+ NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
}
fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
@@ -352,8 +286,44 @@
}
}
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum PartitionName {
+ Kernel,
+ InitrdNormal,
+ InitrdDebug,
+}
+
+impl PartitionName {
+ const KERNEL_PARTITION_NAME: &[u8] = b"boot\0";
+ const INITRD_NORMAL_PARTITION_NAME: &[u8] = b"initrd_normal\0";
+ const INITRD_DEBUG_PARTITION_NAME: &[u8] = b"initrd_debug\0";
+
+ fn as_cstr(&self) -> &CStr {
+ let partition_name = match self {
+ Self::Kernel => Self::KERNEL_PARTITION_NAME,
+ Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME,
+ Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME,
+ };
+ CStr::from_bytes_with_nul(partition_name).unwrap()
+ }
+}
+
+impl TryFrom<&CStr> for PartitionName {
+ type Error = AvbIOError;
+
+ fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> {
+ match partition_name.to_bytes_with_nul() {
+ Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel),
+ Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal),
+ Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug),
+ _ => Err(AvbIOError::NoSuchPartition),
+ }
+ }
+}
+
struct Payload<'a> {
kernel: &'a [u8],
+ initrd: Option<&'a [u8]>,
trusted_public_key: &'a [u8],
}
@@ -369,63 +339,76 @@
}
impl<'a> Payload<'a> {
- const KERNEL_PARTITION_NAME: &[u8] = b"bootloader\0";
-
- fn kernel_partition_name(&self) -> &CStr {
- CStr::from_bytes_with_nul(Self::KERNEL_PARTITION_NAME).unwrap()
- }
+ const MAX_NUM_OF_HASH_DESCRIPTORS: usize = 3;
fn get_partition(&self, partition_name: *const c_char) -> Result<&[u8], AvbIOError> {
is_not_null(partition_name)?;
// SAFETY: It is safe as the raw pointer `partition_name` is a nonnull pointer.
let partition_name = unsafe { CStr::from_ptr(partition_name) };
- match partition_name.to_bytes_with_nul() {
- Self::KERNEL_PARTITION_NAME => Ok(self.kernel),
- _ => Err(AvbIOError::NoSuchPartition),
+ match partition_name.try_into()? {
+ PartitionName::Kernel => Ok(self.kernel),
+ PartitionName::InitrdNormal | PartitionName::InitrdDebug => {
+ self.initrd.ok_or(AvbIOError::NoSuchPartition)
+ }
}
}
+
+ fn verify_partitions(&mut self, partition_names: &[&CStr]) -> Result<(), AvbSlotVerifyError> {
+ if partition_names.len() > Self::MAX_NUM_OF_HASH_DESCRIPTORS {
+ return Err(AvbSlotVerifyError::InvalidArgument);
+ }
+ let mut requested_partitions = [ptr::null(); Self::MAX_NUM_OF_HASH_DESCRIPTORS + 1];
+ partition_names
+ .iter()
+ .enumerate()
+ .for_each(|(i, name)| requested_partitions[i] = name.as_ptr());
+
+ let mut avb_ops = AvbOps {
+ user_data: self as *mut _ as *mut c_void,
+ ab_ops: ptr::null_mut(),
+ atx_ops: ptr::null_mut(),
+ read_from_partition: Some(read_from_partition),
+ get_preloaded_partition: Some(get_preloaded_partition),
+ write_to_partition: None,
+ validate_vbmeta_public_key: None,
+ read_rollback_index: Some(read_rollback_index),
+ write_rollback_index: None,
+ read_is_device_unlocked: Some(read_is_device_unlocked),
+ get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
+ get_size_of_partition: Some(get_size_of_partition),
+ read_persistent_value: None,
+ write_persistent_value: None,
+ validate_public_key_for_partition: Some(validate_public_key_for_partition),
+ };
+ let ab_suffix = CStr::from_bytes_with_nul(NULL_BYTE).unwrap();
+ let out_data = ptr::null_mut();
+ // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
+ // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
+ // initialized. The last argument `out_data` is allowed to be null so that nothing
+ // will be written to it.
+ let result = unsafe {
+ avb_slot_verify(
+ &mut avb_ops,
+ requested_partitions.as_ptr(),
+ ab_suffix.as_ptr(),
+ AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
+ AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
+ out_data,
+ )
+ };
+ slot_verify_result_to_verify_payload_result(result)
+ }
}
/// Verifies the payload (signed kernel + initrd) against the trusted public key.
-pub fn verify_payload(kernel: &[u8], trusted_public_key: &[u8]) -> Result<(), AvbImageVerifyError> {
- let mut payload = Payload { kernel, trusted_public_key };
- let mut avb_ops = AvbOps {
- user_data: &mut payload as *mut _ as *mut c_void,
- ab_ops: ptr::null_mut(),
- atx_ops: ptr::null_mut(),
- read_from_partition: Some(read_from_partition),
- get_preloaded_partition: Some(get_preloaded_partition),
- write_to_partition: None,
- validate_vbmeta_public_key: None,
- read_rollback_index: Some(read_rollback_index),
- write_rollback_index: None,
- read_is_device_unlocked: Some(read_is_device_unlocked),
- get_unique_guid_for_partition: Some(get_unique_guid_for_partition),
- get_size_of_partition: Some(get_size_of_partition),
- read_persistent_value: None,
- write_persistent_value: None,
- validate_public_key_for_partition: Some(validate_public_key_for_partition),
- };
- // NULL is needed to mark the end of the array.
- let requested_partitions: [*const c_char; 2] =
- [payload.kernel_partition_name().as_ptr(), ptr::null()];
- let ab_suffix = CStr::from_bytes_with_nul(b"\0").unwrap();
-
- // SAFETY: It is safe to call `avb_slot_verify()` as the pointer arguments (`ops`,
- // `requested_partitions` and `ab_suffix`) passed to the method are all valid and
- // initialized. The last argument `out_data` is allowed to be null so that nothing
- // will be written to it.
- let result = unsafe {
- avb_slot_verify(
- &mut avb_ops,
- requested_partitions.as_ptr(),
- ab_suffix.as_ptr(),
- AvbSlotVerifyFlags::AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION,
- AvbHashtreeErrorMode::AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
- /*out_data=*/ ptr::null_mut(),
- )
- };
- to_avb_verify_result(result)
+pub fn verify_payload(
+ kernel: &[u8],
+ initrd: Option<&[u8]>,
+ trusted_public_key: &[u8],
+) -> Result<(), AvbSlotVerifyError> {
+ let mut payload = Payload { kernel, initrd, trusted_public_key };
+ let requested_partitions = [PartitionName::Kernel.as_cstr()];
+ payload.verify_partitions(&requested_partitions)
}
#[cfg(test)]
@@ -435,6 +418,11 @@
use avb_bindgen::AvbFooter;
use std::{fs, mem::size_of};
+ const MICRODROID_KERNEL_IMG_PATH: &str = "microdroid_kernel";
+ const INITRD_NORMAL_IMG_PATH: &str = "microdroid_initrd_normal.img";
+ const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
+ const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
+
const PUBLIC_KEY_RSA2048_PATH: &str = "data/testkey_rsa2048_pub.bin";
const PUBLIC_KEY_RSA4096_PATH: &str = "data/testkey_rsa4096_pub.bin";
const RANDOM_FOOTER_POS: usize = 30;
@@ -442,20 +430,34 @@
/// This test uses the Microdroid payload compiled on the fly to check that
/// the latest payload can be verified successfully.
#[test]
- fn latest_valid_payload_is_verified_successfully() -> Result<()> {
+ fn latest_valid_payload_passes_verification() -> Result<()> {
let kernel = load_latest_signed_kernel()?;
+ let initrd_normal = fs::read(INITRD_NORMAL_IMG_PATH)?;
let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
- assert_eq!(Ok(()), verify_payload(&kernel, &public_key));
+ assert_eq!(Ok(()), verify_payload(&kernel, Some(&initrd_normal[..]), &public_key));
Ok(())
}
#[test]
+ fn payload_expecting_no_initrd_passes_verification_with_no_initrd() -> Result<()> {
+ let kernel = fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?;
+ let public_key = fs::read(PUBLIC_KEY_RSA4096_PATH)?;
+
+ assert_eq!(Ok(()), verify_payload(&kernel, None, &public_key));
+ Ok(())
+ }
+
+ // TODO(b/256148034): Test that kernel with two hashdesc and no initrd fails verification.
+ // e.g. payload_expecting_initrd_fails_verification_with_no_initrd
+
+ #[test]
fn payload_with_empty_public_key_fails_verification() -> Result<()> {
assert_payload_verification_fails(
&load_latest_signed_kernel()?,
+ &load_latest_initrd_normal()?,
/*trusted_public_key=*/ &[0u8; 0],
- AvbImageVerifyError::PublicKeyRejected,
+ AvbSlotVerifyError::PublicKeyRejected,
)
}
@@ -463,8 +465,9 @@
fn payload_with_an_invalid_public_key_fails_verification() -> Result<()> {
assert_payload_verification_fails(
&load_latest_signed_kernel()?,
+ &load_latest_initrd_normal()?,
/*trusted_public_key=*/ &[0u8; 512],
- AvbImageVerifyError::PublicKeyRejected,
+ AvbSlotVerifyError::PublicKeyRejected,
)
}
@@ -472,17 +475,19 @@
fn payload_with_a_different_valid_public_key_fails_verification() -> Result<()> {
assert_payload_verification_fails(
&load_latest_signed_kernel()?,
+ &load_latest_initrd_normal()?,
&fs::read(PUBLIC_KEY_RSA2048_PATH)?,
- AvbImageVerifyError::PublicKeyRejected,
+ AvbSlotVerifyError::PublicKeyRejected,
)
}
#[test]
fn unsigned_kernel_fails_verification() -> Result<()> {
assert_payload_verification_fails(
- &fs::read("unsigned_test.img")?,
+ &fs::read(UNSIGNED_TEST_IMG_PATH)?,
+ &load_latest_initrd_normal()?,
&fs::read(PUBLIC_KEY_RSA4096_PATH)?,
- AvbImageVerifyError::Io,
+ AvbSlotVerifyError::Io,
)
}
@@ -493,8 +498,9 @@
assert_payload_verification_fails(
&kernel,
+ &load_latest_initrd_normal()?,
&fs::read(PUBLIC_KEY_RSA4096_PATH)?,
- AvbImageVerifyError::Verification,
+ AvbSlotVerifyError::Verification,
)
}
@@ -506,21 +512,27 @@
assert_payload_verification_fails(
&kernel,
+ &load_latest_initrd_normal()?,
&fs::read(PUBLIC_KEY_RSA4096_PATH)?,
- AvbImageVerifyError::InvalidMetadata,
+ AvbSlotVerifyError::InvalidMetadata,
)
}
fn assert_payload_verification_fails(
kernel: &[u8],
+ initrd: &[u8],
trusted_public_key: &[u8],
- expected_error: AvbImageVerifyError,
+ expected_error: AvbSlotVerifyError,
) -> Result<()> {
- assert_eq!(Err(expected_error), verify_payload(kernel, trusted_public_key));
+ assert_eq!(Err(expected_error), verify_payload(kernel, Some(initrd), trusted_public_key));
Ok(())
}
fn load_latest_signed_kernel() -> Result<Vec<u8>> {
- Ok(fs::read("microdroid_kernel")?)
+ Ok(fs::read(MICRODROID_KERNEL_IMG_PATH)?)
+ }
+
+ fn load_latest_initrd_normal() -> Result<Vec<u8>> {
+ Ok(fs::read(INITRD_NORMAL_IMG_PATH)?)
}
}
diff --git a/pvmfw/src/main.rs b/pvmfw/src/main.rs
index 9c62e03..d0fdd5a 100644
--- a/pvmfw/src/main.rs
+++ b/pvmfw/src/main.rs
@@ -83,7 +83,7 @@
let mut pci_root = unsafe { pci_info.make_pci_root() };
find_virtio_devices(&mut pci_root).map_err(handle_pci_error)?;
- verify_payload(signed_kernel, PUBLIC_KEY).map_err(|e| {
+ verify_payload(signed_kernel, ramdisk, PUBLIC_KEY).map_err(|e| {
error!("Failed to verify the payload: {e}");
RebootReason::PayloadVerificationError
})?;
diff --git a/rialto/tests/test.rs b/rialto/tests/test.rs
index 0447cd3..b25034f 100644
--- a/rialto/tests/test.rs
+++ b/rialto/tests/test.rs
@@ -33,7 +33,7 @@
const RIALTO_PATH: &str = "/data/local/tmp/rialto_test/arm64/rialto.bin";
-/// Runs the Rialto VM as an unprotected VM via VirtualizationService.
+/// Runs the Rialto VM as a non-protected VM via VirtualizationService.
#[test]
fn test_boots() -> Result<(), Error> {
android_logger::init_once(
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index 617c300..2ee33e6 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -652,6 +652,8 @@
@Test
@CddTest(requirements = {"9.17/C-1-1", "9.17/C-1-2", "9.17/C/1-3"})
public void testMicrodroidBoots() throws Exception {
+ CommandRunner android = new CommandRunner(getDevice());
+
final String configPath = "assets/vm_config.json"; // path inside the APK
mMicrodroidDevice =
MicrodroidBuilder.fromDevicePath(getPathForPackage(PACKAGE_NAME), configPath)
@@ -662,6 +664,9 @@
mMicrodroidDevice.waitForBootComplete(BOOT_COMPLETE_TIMEOUT);
CommandRunner microdroid = new CommandRunner(mMicrodroidDevice);
+ String vmList = android.run("/apex/com.android.virt/bin/vm list");
+ assertThat(vmList).contains("requesterUid: " + android.run("id -u"));
+
// Test writing to /data partition
microdroid.run("echo MicrodroidTest > /data/local/tmp/test.txt");
assertThat(microdroid.run("cat /data/local/tmp/test.txt")).isEqualTo("MicrodroidTest");
@@ -680,7 +685,6 @@
assertThat(abis).hasLength(1);
// Check that no denials have happened so far
- CommandRunner android = new CommandRunner(getDevice());
assertThat(android.tryRun("egrep", "'avc:[[:space:]]{1,2}denied'", LOG_PATH)).isNull();
assertThat(android.tryRun("egrep", "'avc:[[:space:]]{1,2}denied'", CONSOLE_PATH)).isNull();
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 43d822b..d8e74f7 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -394,37 +394,43 @@
assertThat(e).hasMessageThat().contains("setProtectedVm must be called");
}
+ private VirtualMachineConfig.Builder newBaselineBuilder() {
+ return newVmConfigBuilder().setPayloadBinaryName("binary.so").setApkPath("/apk/path");
+ }
+
@Test
@CddTest(requirements = {"9.17/C-1-1"})
public void compatibleConfigTests() throws Exception {
int maxCpus = Runtime.getRuntime().availableProcessors();
- VirtualMachineConfig.Builder builder =
- newVmConfigBuilder().setPayloadBinaryName("binary.so").setApkPath("/apk/path");
- VirtualMachineConfig baseline = builder.build();
+ VirtualMachineConfig baseline = newBaselineBuilder().build();
// A config must be compatible with itself
- assertConfigCompatible(baseline, builder).isTrue();
+ assertConfigCompatible(baseline, newBaselineBuilder()).isTrue();
// Changes that must always be compatible
- assertConfigCompatible(baseline, builder.setMemoryMib(99)).isTrue();
+ assertConfigCompatible(baseline, newBaselineBuilder().setMemoryMib(99)).isTrue();
if (maxCpus > 1) {
- assertConfigCompatible(baseline, builder.setNumCpus(2)).isTrue();
+ assertConfigCompatible(baseline, newBaselineBuilder().setNumCpus(2)).isTrue();
}
// Changes that must be incompatible, since they must change the VM identity.
- assertConfigCompatible(baseline, builder.setDebugLevel(DEBUG_LEVEL_FULL)).isFalse();
- assertConfigCompatible(baseline, builder.setPayloadBinaryName("different")).isFalse();
+ assertConfigCompatible(baseline, newBaselineBuilder().setDebugLevel(DEBUG_LEVEL_FULL))
+ .isFalse();
+ assertConfigCompatible(baseline, newBaselineBuilder().setPayloadBinaryName("different"))
+ .isFalse();
int capabilities = getVirtualMachineManager().getCapabilities();
if ((capabilities & CAPABILITY_PROTECTED_VM) != 0
&& (capabilities & CAPABILITY_NON_PROTECTED_VM) != 0) {
- assertConfigCompatible(baseline, builder.setProtectedVm(!isProtectedVm())).isFalse();
+ assertConfigCompatible(baseline, newBaselineBuilder().setProtectedVm(!isProtectedVm()))
+ .isFalse();
}
// Changes that are currently incompatible for ease of implementation, but this might change
// in the future.
- assertConfigCompatible(baseline, builder.setApkPath("/different")).isFalse();
- assertConfigCompatible(baseline, builder.setEncryptedStorageKib(100)).isFalse();
+ assertConfigCompatible(baseline, newBaselineBuilder().setApkPath("/different")).isFalse();
+ assertConfigCompatible(baseline, newBaselineBuilder().setEncryptedStorageKib(100))
+ .isFalse();
}
private BooleanSubject assertConfigCompatible(
diff --git a/virtualizationservice/aidl/Android.bp b/virtualizationservice/aidl/Android.bp
index f028c0f..91d91aa 100644
--- a/virtualizationservice/aidl/Android.bp
+++ b/virtualizationservice/aidl/Android.bp
@@ -36,7 +36,10 @@
aidl_interface {
name: "android.system.virtualizationservice_internal",
srcs: ["android/system/virtualizationservice_internal/**/*.aidl"],
- imports: ["android.system.virtualizationcommon"],
+ imports: [
+ "android.system.virtualizationcommon",
+ "android.system.virtualizationservice",
+ ],
unstable: true,
backend: {
java: {
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineDebugInfo.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineDebugInfo.aidl
index 424eec1..870a342 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineDebugInfo.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineDebugInfo.aidl
@@ -33,7 +33,4 @@
* the PID may have been reused for a different process, so this should not be trusted.
*/
int requesterPid;
-
- /** The current lifecycle state of the VM. */
- VirtualMachineState state = VirtualMachineState.NOT_STARTED;
}
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVirtualizationServiceInternal.aidl b/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVirtualizationServiceInternal.aidl
index d6b3536..5422a48 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVirtualizationServiceInternal.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice_internal/IVirtualizationServiceInternal.aidl
@@ -15,6 +15,7 @@
*/
package android.system.virtualizationservice_internal;
+import android.system.virtualizationservice.VirtualMachineDebugInfo;
import android.system.virtualizationservice_internal.AtomVmBooted;
import android.system.virtualizationservice_internal.AtomVmCreationRequested;
import android.system.virtualizationservice_internal.AtomVmExited;
@@ -35,7 +36,7 @@
* The resources will not be recycled as long as there is a strong reference
* to the returned object.
*/
- IGlobalVmContext allocateGlobalVmContext();
+ IGlobalVmContext allocateGlobalVmContext(int requesterDebugPid);
/** Forwards a VmBooted atom to statsd. */
void atomVmBooted(in AtomVmBooted atom);
@@ -45,4 +46,7 @@
/** Forwards a VmExited atom to statsd. */
void atomVmExited(in AtomVmExited atom);
+
+ /** Get a list of all currently running VMs. */
+ VirtualMachineDebugInfo[] debugListVms();
}
diff --git a/virtualizationservice/src/aidl.rs b/virtualizationservice/src/aidl.rs
index 0859a76..1c82155 100644
--- a/virtualizationservice/src/aidl.rs
+++ b/virtualizationservice/src/aidl.rs
@@ -74,6 +74,7 @@
use std::num::NonZeroU32;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::io::{FromRawFd, IntoRawFd};
+use std::os::unix::raw::{pid_t, uid_t};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, Weak};
use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
@@ -123,15 +124,6 @@
(GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
}
-fn next_guest_cid(cid: Cid) -> Cid {
- assert!(is_valid_guest_cid(cid));
- if cid == GUEST_CID_MAX {
- GUEST_CID_MIN
- } else {
- cid + 1
- }
-}
-
fn create_or_update_idsig_file(
input_fd: &ParcelFileDescriptor,
idsig_fd: &ParcelFileDescriptor,
@@ -197,10 +189,14 @@
}
}
- fn allocateGlobalVmContext(&self) -> binder::Result<Strong<dyn IGlobalVmContext>> {
- let client_uid = Uid::from_raw(get_calling_uid());
+ fn allocateGlobalVmContext(
+ &self,
+ requester_debug_pid: i32,
+ ) -> binder::Result<Strong<dyn IGlobalVmContext>> {
+ let requester_uid = get_calling_uid();
+ let requester_debug_pid = requester_debug_pid as pid_t;
let state = &mut *self.state.lock().unwrap();
- state.allocate_vm_context(client_uid).map_err(|e| {
+ state.allocate_vm_context(requester_uid, requester_debug_pid).map_err(|e| {
Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
})
}
@@ -219,25 +215,55 @@
forward_vm_exited_atom(atom);
Ok(())
}
+
+ fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
+ let state = &mut *self.state.lock().unwrap();
+ let cids = state
+ .held_contexts
+ .iter()
+ .filter_map(|(_, inst)| Weak::upgrade(inst))
+ .map(|vm| VirtualMachineDebugInfo {
+ cid: vm.cid as i32,
+ temporaryDirectory: vm.get_temp_dir().to_string_lossy().to_string(),
+ requesterUid: vm.requester_uid as i32,
+ requesterPid: vm.requester_debug_pid as i32,
+ })
+ .collect();
+ Ok(cids)
+ }
+}
+
+#[derive(Debug, Default)]
+struct GlobalVmInstance {
+ /// The unique CID assigned to the VM for vsock communication.
+ cid: Cid,
+ /// UID of the client who requested this VM instance.
+ requester_uid: uid_t,
+ /// PID of the client who requested this VM instance.
+ requester_debug_pid: pid_t,
+}
+
+impl GlobalVmInstance {
+ fn get_temp_dir(&self) -> PathBuf {
+ let cid = self.cid;
+ format!("{TEMPORARY_DIRECTORY}/{cid}").into()
+ }
}
/// The mutable state of the VirtualizationServiceInternal. There should only be one instance
/// of this struct.
#[derive(Debug, Default)]
struct GlobalState {
- /// CIDs currently allocated to running VMs. A CID is never recycled as long
+ /// VM contexts currently allocated to running VMs. A CID is never recycled as long
/// as there is a strong reference held by a GlobalVmContext.
- held_cids: HashMap<Cid, Weak<Cid>>,
+ held_contexts: HashMap<Cid, Weak<GlobalVmInstance>>,
}
impl GlobalState {
/// Get the next available CID, or an error if we have run out. The last CID used is stored in
/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
/// Android is up.
- fn allocate_cid(&mut self) -> Result<Arc<Cid>> {
- // Garbage collect unused CIDs.
- self.held_cids.retain(|_, cid| cid.strong_count() > 0);
-
+ fn get_next_available_cid(&mut self) -> Result<Cid> {
// Start trying to find a CID from the last used CID + 1. This ensures
// that we do not eagerly recycle CIDs. It makes debugging easier but
// also means that retrying to allocate a CID, eg. because it is
@@ -259,55 +285,62 @@
});
let first_cid = if let Some(last_cid) = last_cid_prop {
- next_guest_cid(last_cid)
+ if last_cid == GUEST_CID_MAX {
+ GUEST_CID_MIN
+ } else {
+ last_cid + 1
+ }
} else {
GUEST_CID_MIN
};
let cid = self
.find_available_cid(first_cid..=GUEST_CID_MAX)
- .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid));
+ .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid))
+ .ok_or_else(|| anyhow!("Could not find an available CID."))?;
- if let Some(cid) = cid {
- let cid_arc = Arc::new(cid);
- self.held_cids.insert(cid, Arc::downgrade(&cid_arc));
- system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
- Ok(cid_arc)
- } else {
- Err(anyhow!("Could not find an available CID."))
- }
+ system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
+ Ok(cid)
}
fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
where
I: Iterator<Item = Cid>,
{
- range.find(|cid| !self.held_cids.contains_key(cid))
+ range.find(|cid| !self.held_contexts.contains_key(cid))
}
- fn allocate_vm_context(&mut self, client_uid: Uid) -> Result<Strong<dyn IGlobalVmContext>> {
- let cid = self.allocate_cid()?;
- let temp_dir = create_vm_directory(client_uid, *cid)?;
- let binder = GlobalVmContext { cid, temp_dir, ..Default::default() };
+ fn allocate_vm_context(
+ &mut self,
+ requester_uid: uid_t,
+ requester_debug_pid: pid_t,
+ ) -> Result<Strong<dyn IGlobalVmContext>> {
+ // Garbage collect unused VM contexts.
+ self.held_contexts.retain(|_, instance| instance.strong_count() > 0);
+
+ let cid = self.get_next_available_cid()?;
+ let instance = Arc::new(GlobalVmInstance { cid, requester_uid, requester_debug_pid });
+ create_temporary_directory(&instance.get_temp_dir(), requester_uid)?;
+
+ self.held_contexts.insert(cid, Arc::downgrade(&instance));
+ let binder = GlobalVmContext { instance, ..Default::default() };
Ok(BnGlobalVmContext::new_binder(binder, BinderFeatures::default()))
}
}
-fn create_vm_directory(client_uid: Uid, cid: Cid) -> Result<PathBuf> {
- let path: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
+fn create_temporary_directory(path: &PathBuf, requester_uid: uid_t) -> Result<()> {
if path.as_path().exists() {
- remove_temporary_dir(&path).unwrap_or_else(|e| {
+ remove_temporary_dir(path).unwrap_or_else(|e| {
warn!("Could not delete temporary directory {:?}: {}", path, e);
});
}
// Create a directory that is owned by client's UID but system's GID, and permissions 0700.
// If the chown() fails, this will leave behind an empty directory that will get removed
// at the next attempt, or if virtualizationservice is restarted.
- create_dir(&path)
- .with_context(|| format!("Could not create temporary directory {:?}", path))?;
- chown(&path, Some(client_uid), None)
+ create_dir(path).with_context(|| format!("Could not create temporary directory {:?}", path))?;
+ chown(path, Some(Uid::from_raw(requester_uid)), None)
.with_context(|| format!("Could not set ownership of temporary directory {:?}", path))?;
- Ok(path)
+ Ok(())
}
/// Removes a directory owned by a different user by first changing its owner back
@@ -333,10 +366,8 @@
/// Implementation of the AIDL `IGlobalVmContext` interface.
#[derive(Debug, Default)]
struct GlobalVmContext {
- /// The unique CID assigned to the VM for vsock communication.
- cid: Arc<Cid>,
- /// The temporary folder created for the VM and owned by the creator's UID.
- temp_dir: PathBuf,
+ /// Strong reference to the context's instance data structure.
+ instance: Arc<GlobalVmInstance>,
/// Keeps our service process running as long as this VM context exists.
#[allow(dead_code)]
lazy_service_guard: LazyServiceGuard,
@@ -346,11 +377,11 @@
impl IGlobalVmContext for GlobalVmContext {
fn getCid(&self) -> binder::Result<i32> {
- Ok(*self.cid as i32)
+ Ok(self.instance.cid as i32)
}
fn getTemporaryDirectory(&self) -> binder::Result<String> {
- Ok(self.temp_dir.to_string_lossy().to_string())
+ Ok(self.instance.get_temp_dir().to_string_lossy().to_string())
}
}
@@ -469,20 +500,7 @@
/// and as such is only permitted from the shell user.
fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
check_debug_access()?;
-
- let state = &mut *self.state.lock().unwrap();
- let vms = state.vms();
- let cids = vms
- .into_iter()
- .map(|vm| VirtualMachineDebugInfo {
- cid: vm.cid as i32,
- temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
- requesterUid: vm.requester_uid as i32,
- requesterPid: vm.requester_debug_pid,
- state: get_state(&vm),
- })
- .collect();
- Ok(cids)
+ GLOBAL_SERVICE.debugListVms()
}
/// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
@@ -564,13 +582,13 @@
VirtualizationService::default()
}
- fn create_vm_context(&self) -> Result<(VmContext, Cid, PathBuf)> {
+ fn create_vm_context(&self, requester_debug_pid: pid_t) -> Result<(VmContext, Cid, PathBuf)> {
const NUM_ATTEMPTS: usize = 5;
for _ in 0..NUM_ATTEMPTS {
- let global_context = GLOBAL_SERVICE.allocateGlobalVmContext()?;
- let cid = global_context.getCid()? as Cid;
- let temp_dir: PathBuf = global_context.getTemporaryDirectory()?.into();
+ let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid as i32)?;
+ let cid = vm_context.getCid()? as Cid;
+ let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
// Start VM service listening for connections from the new CID on port=CID.
@@ -578,7 +596,7 @@
match RpcServer::new_vsock(service, cid, port) {
Ok(vm_server) => {
vm_server.start();
- return Ok((VmContext::new(global_context, vm_server), cid, temp_dir));
+ return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
}
Err(err) => {
warn!("Could not start RpcServer on port {}: {}", port, err);
@@ -611,19 +629,21 @@
check_use_custom_virtual_machine()?;
}
- let (vm_context, cid, temporary_directory) = self.create_vm_context().map_err(|e| {
- error!("Failed to create VmContext: {:?}", e);
- Status::new_service_specific_error_str(
- -1,
- Some(format!("Failed to create VmContext: {:?}", e)),
- )
- })?;
+ let requester_uid = get_calling_uid();
+ let requester_debug_pid = get_calling_pid();
+
+ let (vm_context, cid, temporary_directory) =
+ self.create_vm_context(requester_debug_pid).map_err(|e| {
+ error!("Failed to create VmContext: {:?}", e);
+ Status::new_service_specific_error_str(
+ -1,
+ Some(format!("Failed to create VmContext: {:?}", e)),
+ )
+ })?;
let state = &mut *self.state.lock().unwrap();
let console_fd = console_fd.map(clone_file).transpose()?;
let log_fd = log_fd.map(clone_file).transpose()?;
- let requester_uid = get_calling_uid();
- let requester_debug_pid = get_calling_pid();
// Counter to generate unique IDs for temporary image files.
let mut next_temporary_image_id = 0;
@@ -664,6 +684,16 @@
.try_for_each(check_label_for_partition)
.map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
+ let kernel = maybe_clone_file(&config.kernel)?;
+ let initrd = maybe_clone_file(&config.initrd)?;
+
+ // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
+ if config.protectedVm {
+ check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
+ Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
+ })?;
+ }
+
let zero_filler_path = temporary_directory.join("zero.img");
write_zero_filler(&zero_filler_path).map_err(|e| {
error!("Failed to make composite image: {:?}", e);
@@ -706,8 +736,8 @@
cid,
name: config.name.clone(),
bootloader: maybe_clone_file(&config.bootloader)?,
- kernel: maybe_clone_file(&config.kernel)?,
- initrd: maybe_clone_file(&config.initrd)?,
+ kernel,
+ initrd,
disks,
params: config.params.to_owned(),
protected: *is_protected,
@@ -971,14 +1001,8 @@
check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
}
-/// Check if a partition has selinux labels that are not allowed
-fn check_label_for_partition(partition: &Partition) -> Result<()> {
- let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
- check_label_is_allowed(&ctx).with_context(|| format!("Partition {} invalid", &partition.label))
-}
-
-// Return whether a partition is exempt from selinux label checks, because we know that it does
-// not contain code and is likely to be generated in an app-writable directory.
+/// Return whether a partition is exempt from selinux label checks, because we know that it does
+/// not contain code and is likely to be generated in an app-writable directory.
fn is_safe_app_partition(label: &str) -> bool {
// See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
label == "vm-instance"
@@ -988,23 +1012,46 @@
|| label.starts_with("extra-idsig-")
}
-fn check_label_is_allowed(ctx: &SeContext) -> Result<()> {
- // We only want to allow code in a VM payload to be sourced from places that apps, and the
- // system, do not have write access to.
- // (Note that sepolicy must also grant read access for these types to both virtualization
- // service and crosvm.)
- // App private data files are deliberately excluded, to avoid arbitrary payloads being run on
- // user devices (W^X).
- match ctx.selinux_type()? {
+/// Check that a file SELinux label is acceptable.
+///
+/// We only want to allow code in a VM to be sourced from places that apps, and the
+/// system, do not have write access to.
+///
+/// Note that sepolicy must also grant read access for these types to both virtualization
+/// service and crosvm.
+///
+/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
+/// user devices (W^X).
+fn check_label_is_allowed(context: &SeContext) -> Result<()> {
+ match context.selinux_type()? {
| "system_file" // immutable dm-verity protected partition
| "apk_data_file" // APKs of an installed app
| "staging_data_file" // updated/staged APEX images
| "shell_data_file" // test files created via adb shell
=> Ok(()),
- _ => bail!("Label {} is not allowed", ctx),
+ _ => bail!("Label {} is not allowed", context),
}
}
+fn check_label_for_partition(partition: &Partition) -> Result<()> {
+ let file = partition.image.as_ref().unwrap().as_ref();
+ check_label_is_allowed(&getfilecon(file)?)
+ .with_context(|| format!("Partition {} invalid", &partition.label))
+}
+
+fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
+ if let Some(f) = kernel {
+ check_label_for_file(f, "kernel")?;
+ }
+ if let Some(f) = initrd {
+ check_label_for_file(f, "initrd")?;
+ }
+ Ok(())
+}
+fn check_label_for_file(file: &File, name: &str) -> Result<()> {
+ check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
+}
+
/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
#[derive(Debug)]
struct VirtualMachine {
diff --git a/virtualizationservice/src/virtmgr.rs b/virtualizationservice/src/virtmgr.rs
index 5616097..dca64cb 100644
--- a/virtualizationservice/src/virtmgr.rs
+++ b/virtualizationservice/src/virtmgr.rs
@@ -33,6 +33,7 @@
use nix::fcntl::{fcntl, F_GETFD, F_SETFD, FdFlag};
use nix::unistd::{Pid, Uid};
use std::os::unix::raw::{pid_t, uid_t};
+use rustutils::system_properties;
const LOG_TAG: &str = "virtmgr";
@@ -91,6 +92,11 @@
Ok(unsafe { OwnedFd::from_raw_fd(raw_fd) })
}
+fn is_property_set(name: &str) -> bool {
+ system_properties::read_bool(name, false)
+ .unwrap_or_else(|e| panic!("Failed to read {name}: {e:?}"))
+}
+
fn main() {
android_logger::init_once(
android_logger::Config::default()
@@ -99,6 +105,15 @@
.with_log_id(android_logger::LogId::System),
);
+ let non_protected_vm_supported = is_property_set("ro.boot.hypervisor.vm.supported");
+ let protected_vm_supported = is_property_set("ro.boot.hypervisor.protected_vm.supported");
+ if !non_protected_vm_supported && !protected_vm_supported {
+ // This should never happen, it indicates a misconfigured device where the virt APEX
+ // is present but VMs are not supported. If it does happen, fail fast to avoid wasting
+ // resources trying.
+ panic!("Device doesn't support protected or unprotected VMs");
+ }
+
let args = Args::parse();
let mut owned_fds = vec![];
diff --git a/vm/TEST_MAPPING b/vm/TEST_MAPPING
index a8d1fa6..485c3af 100644
--- a/vm/TEST_MAPPING
+++ b/vm/TEST_MAPPING
@@ -1,7 +1,7 @@
{
- "avf-presubmit" : [
+ "avf-presubmit": [
{
- "name" : "vm.test"
+ "name": "vm.test"
}
]
}
diff --git a/vm/src/main.rs b/vm/src/main.rs
index 9fa805e..bfc7920 100644
--- a/vm/src/main.rs
+++ b/vm/src/main.rs
@@ -358,15 +358,15 @@
/// Print information about supported VM types.
fn command_info() -> Result<(), Error> {
- let unprotected_vm_supported =
+ let non_protected_vm_supported =
system_properties::read_bool("ro.boot.hypervisor.vm.supported", false)?;
let protected_vm_supported =
system_properties::read_bool("ro.boot.hypervisor.protected_vm.supported", false)?;
- match (unprotected_vm_supported, protected_vm_supported) {
+ match (non_protected_vm_supported, protected_vm_supported) {
(false, false) => println!("VMs are not supported."),
(false, true) => println!("Only protected VMs are supported."),
- (true, false) => println!("Only unprotected VMs are supported."),
- (true, true) => println!("Both protected and unprotected VMs are supported."),
+ (true, false) => println!("Only non-protected VMs are supported."),
+ (true, true) => println!("Both protected and non-protected VMs are supported."),
}
if let Some(version) = system_properties::read("ro.boot.hypervisor.version")? {
@@ -387,10 +387,11 @@
#[cfg(test)]
mod tests {
use super::*;
- use clap::IntoApp;
+ use clap::CommandFactory;
#[test]
fn verify_app() {
- Opt::into_app().debug_assert();
+ // Check that the command parsing has been configured in a valid way.
+ Opt::command().debug_assert();
}
}
diff --git a/vm/vm_shell.sh b/vm/vm_shell.sh
index 29cc7da..3db7003 100755
--- a/vm/vm_shell.sh
+++ b/vm/vm_shell.sh
@@ -92,7 +92,8 @@
shift
done
if [[ "${auto_connect}" == true ]]; then
- adb shell /apex/com.android.virt/bin/vm run-microdroid -d "${passthrough_args}"
+ adb shell /apex/com.android.virt/bin/vm run-microdroid "${passthrough_args}" &
+ trap "kill $!" EXIT
sleep 2
handle_connect_cmd
else
diff --git a/zipfuse/src/main.rs b/zipfuse/src/main.rs
index 365d236..5e9e160 100644
--- a/zipfuse/src/main.rs
+++ b/zipfuse/src/main.rs
@@ -21,7 +21,7 @@
mod inode;
use anyhow::{Context as AnyhowContext, Result};
-use clap::{App, Arg};
+use clap::{builder::ValueParser, Arg, ArgAction, Command};
use fuse::filesystem::*;
use fuse::mount::*;
use rustutils::system_properties;
@@ -34,65 +34,58 @@
use std::mem::size_of;
use std::os::unix::io::AsRawFd;
use std::path::Path;
+use std::path::PathBuf;
use std::sync::Mutex;
use crate::inode::{DirectoryEntry, Inode, InodeData, InodeKind, InodeTable};
fn main() -> Result<()> {
- let matches = App::new("zipfuse")
+ let matches = clap_command().get_matches();
+
+ let zip_file = matches.get_one::<PathBuf>("ZIPFILE").unwrap();
+ let mount_point = matches.get_one::<PathBuf>("MOUNTPOINT").unwrap();
+ let options = matches.get_one::<String>("options");
+ let noexec = matches.get_flag("noexec");
+ let ready_prop = matches.get_one::<String>("readyprop");
+ let uid: u32 = matches.get_one::<String>("uid").map_or(0, |s| s.parse().unwrap());
+ let gid: u32 = matches.get_one::<String>("gid").map_or(0, |s| s.parse().unwrap());
+ run_fuse(zip_file, mount_point, options, noexec, ready_prop, uid, gid)?;
+
+ Ok(())
+}
+
+fn clap_command() -> Command {
+ Command::new("zipfuse")
.arg(
- Arg::with_name("options")
+ Arg::new("options")
.short('o')
- .takes_value(true)
.required(false)
.help("Comma separated list of mount options"),
)
.arg(
- Arg::with_name("noexec")
+ Arg::new("noexec")
.long("noexec")
- .takes_value(false)
+ .action(ArgAction::SetTrue)
.help("Disallow the execution of binary files"),
)
.arg(
- Arg::with_name("readyprop")
+ Arg::new("readyprop")
.short('p')
- .takes_value(true)
.help("Specify a property to be set when mount is ready"),
)
- .arg(
- Arg::with_name("uid")
- .short('u')
- .takes_value(true)
- .help("numeric UID who's the owner of the files"),
- )
- .arg(
- Arg::with_name("gid")
- .short('g')
- .takes_value(true)
- .help("numeric GID who's the group of the files"),
- )
- .arg(Arg::with_name("ZIPFILE").required(true))
- .arg(Arg::with_name("MOUNTPOINT").required(true))
- .get_matches();
-
- let zip_file = matches.value_of("ZIPFILE").unwrap().as_ref();
- let mount_point = matches.value_of("MOUNTPOINT").unwrap().as_ref();
- let options = matches.value_of("options");
- let noexec = matches.is_present("noexec");
- let ready_prop = matches.value_of("readyprop");
- let uid: u32 = matches.value_of("uid").map_or(0, |s| s.parse().unwrap());
- let gid: u32 = matches.value_of("gid").map_or(0, |s| s.parse().unwrap());
- run_fuse(zip_file, mount_point, options, noexec, ready_prop, uid, gid)?;
- Ok(())
+ .arg(Arg::new("uid").short('u').help("numeric UID who's the owner of the files"))
+ .arg(Arg::new("gid").short('g').help("numeric GID who's the group of the files"))
+ .arg(Arg::new("ZIPFILE").value_parser(ValueParser::path_buf()).required(true))
+ .arg(Arg::new("MOUNTPOINT").value_parser(ValueParser::path_buf()).required(true))
}
/// Runs a fuse filesystem by mounting `zip_file` on `mount_point`.
pub fn run_fuse(
zip_file: &Path,
mount_point: &Path,
- extra_options: Option<&str>,
+ extra_options: Option<&String>,
noexec: bool,
- ready_prop: Option<&str>,
+ ready_prop: Option<&String>,
uid: u32,
gid: u32,
) -> Result<()> {
@@ -471,11 +464,11 @@
#[cfg(test)]
mod tests {
- use anyhow::{bail, Result};
+ use super::*;
+ use anyhow::bail;
use nix::sys::statfs::{statfs, FsType};
use std::collections::BTreeSet;
use std::fs;
- use std::fs::File;
use std::io::Write;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
@@ -873,4 +866,10 @@
// Start zipfuse over to the loop device (not the zip file)
run_fuse_and_check_test_zip(&test_dir.path(), &ld.path().unwrap());
}
+
+ #[test]
+ fn verify_command() {
+ // Check that the command parsing has been configured in a valid way.
+ clap_command().debug_assert();
+ }
}