Merge "Unify and change notification channel to package name" into main
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.java b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.java
index e8fd2d2..10451ec 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.java
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.java
@@ -542,9 +542,8 @@
SharedPreferences.Editor editor = sharedPref.edit();
long currentDiskSize = getFilesystemSize(file);
- // The default partition size is 6G
long newSizeInBytes = sharedPref.getLong(getString(R.string.preference_disk_size_key),
- 6L << 30);
+ roundUpDiskSize(currentDiskSize));
editor.putLong(getString(R.string.preference_disk_size_key), newSizeInBytes);
editor.apply();
diff --git a/android/TerminalApp/res/values/strings.xml b/android/TerminalApp/res/values/strings.xml
index ca803ec..3448388 100644
--- a/android/TerminalApp/res/values/strings.xml
+++ b/android/TerminalApp/res/values/strings.xml
@@ -83,17 +83,17 @@
<string name="settings_recovery_title">Recovery</string>
<!-- Settings menu subtitle for recoverying image [CHAR LIMIT=none] -->
<string name="settings_recovery_sub_title">Partition Recovery options</string>
- <!-- Settings menu title for resetting the virtual machine image [CHAR LIMIT=none] -->
+ <!-- Settings menu title for resetting the terminal [CHAR LIMIT=none] -->
<string name="settings_recovery_reset_title">Change to Initial version</string>
- <!-- Settings menu subtitle for resetting the virtual machine image [CHAR LIMIT=none] -->
+ <!-- Settings menu subtitle for resetting the terminal [CHAR LIMIT=none] -->
<string name="settings_recovery_reset_sub_title">Remove all</string>
- <!-- Dialog title for restarting the terminal [CHAR LIMIT=none] -->
- <string name="settings_recovery_reset_dialog_title">Reset the virtual machine</string>
- <!-- Dialog message for restarting the terminal [CHAR LIMIT=none] -->
- <string name="settings_recovery_reset_dialog_message">Data will be deleted.</string>
- <!-- Dialog button confirm for restarting the terminal [CHAR LIMIT=16] -->
+ <!-- Dialog title for resetting the terminal [CHAR LIMIT=none] -->
+ <string name="settings_recovery_reset_dialog_title">Reset terminal</string>
+ <!-- Dialog message for resetting the terminal [CHAR LIMIT=none] -->
+ <string name="settings_recovery_reset_dialog_message">Data will be deleted</string>
+ <!-- Dialog button confirm for resetting the terminal [CHAR LIMIT=16] -->
<string name="settings_recovery_reset_dialog_confirm">Confirm</string>
- <!-- Dialog button cancel for restarting the terminal [CHAR LIMIT=16] -->
+ <!-- Dialog button cancel for resetting the terminal [CHAR LIMIT=16] -->
<string name="settings_recovery_reset_dialog_cancel">Cancel</string>
<!-- Notification action button for settings [CHAR LIMIT=none] -->
@@ -101,7 +101,7 @@
<!-- Notification title for foreground service notification [CHAR LIMIT=none] -->
<string name="service_notification_title">Terminal is running</string>
<!-- Notification content for foreground service notification [CHAR LIMIT=none] -->
- <string name="service_notification_content">Click to open the terminal.</string>
+ <string name="service_notification_content">Click to open the terminal</string>
<!-- Notification action button for closing the virtual machine [CHAR LIMIT=none] -->
<string name="service_notification_quit_action">Close</string>
</resources>
diff --git a/android/virtmgr/src/aidl.rs b/android/virtmgr/src/aidl.rs
index e2b2804..4538248 100644
--- a/android/virtmgr/src/aidl.rs
+++ b/android/virtmgr/src/aidl.rs
@@ -21,7 +21,7 @@
use crate::debug_config::DebugConfig;
use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
-use crate::selinux::{getfilecon, SeContext};
+use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext};
use android_os_permissions_aidl::aidl::android::os::IPermissionController;
use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Certificate::Certificate,
@@ -502,6 +502,9 @@
check_config_allowed_for_early_vms(config)?;
}
+ let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
+ info!("callers secontext: {}", caller_secontext);
+
// Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
let (vm_context, cid, temporary_directory) = if cfg!(early) {
self.create_early_vm_context(config)?
@@ -534,7 +537,13 @@
clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
let console_in_fd = console_in_fd.map(clone_file).transpose()?;
let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
- let dump_dt_fd = dump_dt_fd.map(clone_file).transpose()?;
+ let dump_dt_fd = if let Some(fd) = dump_dt_fd {
+ Some(clone_file(fd)?)
+ } else if debug_config.dump_device_tree {
+ Some(prepare_dump_dt_file(&temporary_directory)?)
+ } else {
+ None
+ };
// Counter to generate unique IDs for temporary image files.
let mut next_temporary_image_id = 0;
@@ -558,6 +567,10 @@
let config = config.as_ref();
*is_protected = config.protectedVm;
+ check_tee_service_permission(&caller_secontext, &config.teeServices)
+ .with_log()
+ .or_binder_exception(ExceptionCode::SECURITY)?;
+
// Check if partition images are labeled incorrectly. This is to prevent random images
// which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
// being loaded in a pVM. This applies to everything but the instance image in the raw
@@ -1152,6 +1165,8 @@
for param in custom_config.extraKernelCmdlineParams.iter() {
append_kernel_param(param, &mut vm_config);
}
+
+ vm_config.teeServices.clone_from(&custom_config.teeServices);
}
// Unfortunately specifying page_shift = 14 in bootconfig doesn't enable 16k pages emulation,
@@ -1669,6 +1684,16 @@
Ok(ramdump)
}
+/// Create the empty device tree dump file
+fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
+ let path = temporary_directory.join("device_tree.dtb");
+ let file = File::create(path)
+ .context("Failed to prepare device tree dump file")
+ .with_log()
+ .or_service_specific_exception(-1)?;
+ Ok(file)
+}
+
fn is_protected(config: &VirtualMachineConfig) -> bool {
match config {
VirtualMachineConfig::RawConfig(config) => config.protectedVm,
@@ -1759,6 +1784,26 @@
Ok(())
}
+fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
+ match config {
+ VirtualMachineConfig::RawConfig(config) => {
+ if !config.teeServices.is_empty() {
+ return Err(anyhow!("tee_services_allowlist feature is disabled"))
+ .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
+ }
+ }
+ VirtualMachineConfig::AppConfig(config) => {
+ if let Some(custom_config) = &config.customConfig {
+ if !custom_config.teeServices.is_empty() {
+ return Err(anyhow!("tee_services_allowlist feature is disabled"))
+ .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
+ }
+ }
+ }
+ };
+ Ok(())
+}
+
fn check_protected_vm_is_supported() -> binder::Result<()> {
let is_pvm_supported =
hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
@@ -1783,6 +1828,9 @@
if !cfg!(debuggable_vms_improvements) {
check_no_extra_kernel_cmdline_params(config)?;
}
+ if !cfg!(tee_services_allowlist) {
+ check_no_tee_services(config)?;
+ }
Ok(())
}
diff --git a/android/virtmgr/src/debug_config.rs b/android/virtmgr/src/debug_config.rs
index 74559de..6e2bfef 100644
--- a/android/virtmgr/src/debug_config.rs
+++ b/android/virtmgr/src/debug_config.rs
@@ -30,6 +30,7 @@
const CUSTOM_DEBUG_POLICY_OVERLAY_SYSPROP: &str =
"hypervisor.virtualizationmanager.debug_policy.path";
+const DUMP_DT_SYSPROP: &str = "hypervisor.virtualizationmanager.dump_device_tree";
const DEVICE_TREE_EMPTY_TREE_SIZE_BYTES: usize = 100; // rough estimation.
struct DPPath {
@@ -183,6 +184,7 @@
#[derive(Debug, Default)]
pub struct DebugConfig {
pub debug_level: DebugLevel,
+ pub dump_device_tree: bool,
debug_policy: DebugPolicy,
}
@@ -193,8 +195,13 @@
info!("Debug policy is disabled");
Default::default()
});
+ let dump_dt_sysprop = system_properties::read_bool(DUMP_DT_SYSPROP, false);
+ let dump_device_tree = dump_dt_sysprop.unwrap_or_else(|e| {
+ warn!("Failed to read sysprop {DUMP_DT_SYSPROP}: {e}");
+ false
+ });
- Self { debug_level, debug_policy }
+ Self { debug_level, debug_policy, dump_device_tree }
}
fn get_debug_policy() -> Option<DebugPolicy> {
diff --git a/android/virtmgr/src/selinux.rs b/android/virtmgr/src/selinux.rs
index ba62b7f..a8c895f 100644
--- a/android/virtmgr/src/selinux.rs
+++ b/android/virtmgr/src/selinux.rs
@@ -15,13 +15,30 @@
//! Wrapper to libselinux
use anyhow::{anyhow, bail, Context, Result};
-use std::ffi::{CStr, CString};
+use std::ffi::{c_int, CStr, CString};
use std::fmt;
use std::io;
use std::ops::Deref;
use std::os::fd::AsRawFd;
use std::os::raw::c_char;
use std::ptr;
+use std::sync;
+
+static SELINUX_LOG_INIT: sync::Once = sync::Once::new();
+
+fn redirect_selinux_logs_to_logcat() {
+ let cb =
+ selinux_bindgen::selinux_callback { func_log: Some(selinux_bindgen::selinux_log_callback) };
+ // SAFETY: `selinux_set_callback` assigns the static lifetime function pointer
+ // `selinux_log_callback` to a static lifetime variable.
+ unsafe {
+ selinux_bindgen::selinux_set_callback(selinux_bindgen::SELINUX_CB_LOG as c_int, cb);
+ }
+}
+
+fn init_logger_once() {
+ SELINUX_LOG_INIT.call_once(redirect_selinux_logs_to_logcat)
+}
// Partially copied from system/security/keystore2/selinux/src/lib.rs
/// SeContext represents an SELinux context string. It can take ownership of a raw
@@ -101,6 +118,56 @@
}
}
+/// Takes ownership of context handle returned by `selinux_android_tee_service_context_handle`
+/// and closes it via `selabel_close` when dropped.
+struct TeeServiceSelinuxBackend {
+ handle: *mut selinux_bindgen::selabel_handle,
+}
+
+impl TeeServiceSelinuxBackend {
+ const BACKEND_ID: i32 = selinux_bindgen::SELABEL_CTX_ANDROID_SERVICE as i32;
+
+ /// Creates a new instance representing selinux context handle returned from
+ /// `selinux_android_tee_service_context_handle`.
+ fn new() -> Result<Self> {
+ // SAFETY: selinux_android_tee_service_context_handle is always safe to call. The returned
+ // handle is valid until `selabel_close` is called on it (see the safety comment on the drop
+ // trait).
+ let handle = unsafe { selinux_bindgen::selinux_android_tee_service_context_handle() };
+ if handle.is_null() {
+ Err(anyhow!("selinux_android_tee_service_context_handle returned a NULL context"))
+ } else {
+ Ok(TeeServiceSelinuxBackend { handle })
+ }
+ }
+
+ fn lookup(&self, tee_service: &str) -> Result<SeContext> {
+ let mut con: *mut c_char = ptr::null_mut();
+ let c_key = CString::new(tee_service).context("failed to convert to CString")?;
+ // SAFETY: the returned pointer `con` is valid until `freecon` is called on it.
+ match unsafe {
+ selinux_bindgen::selabel_lookup(self.handle, &mut con, c_key.as_ptr(), Self::BACKEND_ID)
+ } {
+ 0 => {
+ if !con.is_null() {
+ Ok(SeContext::Raw(con))
+ } else {
+ Err(anyhow!("selabel_lookup returned a NULL context"))
+ }
+ }
+ _ => Err(anyhow!(io::Error::last_os_error())).context("selabel_lookup failed"),
+ }
+ }
+}
+
+impl Drop for TeeServiceSelinuxBackend {
+ fn drop(&mut self) {
+ // SAFETY: the TeeServiceSelinuxBackend is created only with a pointer is set by
+ // libselinux and has to be freed with `selabel_close`.
+ unsafe { selinux_bindgen::selabel_close(self.handle) };
+ }
+}
+
pub fn getfilecon<F: AsRawFd>(file: &F) -> Result<SeContext> {
let fd = file.as_raw_fd();
let mut con: *mut c_char = ptr::null_mut();
@@ -117,3 +184,90 @@
_ => Err(anyhow!(io::Error::last_os_error())).context("fgetfilecon failed"),
}
}
+
+pub fn getprevcon() -> Result<SeContext> {
+ let mut con: *mut c_char = ptr::null_mut();
+ // SAFETY: the returned pointer `con` is wrapped in SeContext::Raw which is freed with
+ // `freecon` when it is dropped.
+ match unsafe { selinux_bindgen::getprevcon(&mut con) } {
+ 0.. => {
+ if !con.is_null() {
+ Ok(SeContext::Raw(con))
+ } else {
+ Err(anyhow!("getprevcon returned a NULL context"))
+ }
+ }
+ _ => Err(anyhow!(io::Error::last_os_error())).context("getprevcon failed"),
+ }
+}
+
+// Wrapper around selinux_check_access
+fn check_access(source: &CStr, target: &CStr, tclass: &str, perm: &str) -> Result<()> {
+ let c_tclass = CString::new(tclass).context("failed to convert tclass to CString")?;
+ let c_perm = CString::new(perm).context("failed to convert perm to CString")?;
+
+ // SAFETY: lifecycle of pointers passed to the selinux_check_access outlive the duration of the
+ // call.
+ match unsafe {
+ selinux_bindgen::selinux_check_access(
+ source.as_ptr(),
+ target.as_ptr(),
+ c_tclass.as_ptr(),
+ c_perm.as_ptr(),
+ ptr::null_mut(),
+ )
+ } {
+ 0 => Ok(()),
+ _ => Err(anyhow!(io::Error::last_os_error())).with_context(|| {
+ format!(
+ "check_access: Failed with sctx: {:?} tctx: {:?} tclass: {:?} perm {:?}",
+ source, target, tclass, perm
+ )
+ }),
+ }
+}
+
+pub fn check_tee_service_permission(caller_ctx: &SeContext, tee_services: &[String]) -> Result<()> {
+ init_logger_once();
+
+ let backend = TeeServiceSelinuxBackend::new()?;
+
+ for tee_service in tee_services {
+ let tee_service_ctx = backend.lookup(tee_service)?;
+ check_access(caller_ctx, &tee_service_ctx, "tee_service", "use")
+ .with_context(|| format!("permission denied for {:?}", tee_service))?;
+ }
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_check_tee_service_permission_has_permission() -> Result<()> {
+ if cfg!(not(tee_services_allowlist)) {
+ // Skip test on release configurations without tee_services_allowlist feature enabled.
+ return Ok(());
+ }
+
+ let caller_ctx = SeContext::new("u:r:shell:s0")?;
+ let tee_services = [String::from("test_pkvm_tee_service")];
+ check_tee_service_permission(&caller_ctx, &tee_services)
+ }
+
+ #[test]
+ fn test_check_tee_service_permission_invalid_tee_service() -> Result<()> {
+ if cfg!(not(tee_services_allowlist)) {
+ // Skip test on release configurations without tee_services_allowlist feature enabled.
+ return Ok(());
+ }
+
+ let caller_ctx = SeContext::new("u:r:shell:s0")?;
+ let tee_services = [String::from("test_tee_service_does_not_exist")];
+ let ret = check_tee_service_permission(&caller_ctx, &tee_services);
+ assert!(ret.is_err());
+ Ok(())
+ }
+}
diff --git a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl
index 9123742..114a851 100644
--- a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl
+++ b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl
@@ -130,6 +130,9 @@
/** Additional parameters to pass to the VM's kernel cmdline. */
String[] extraKernelCmdlineParams;
+
+ /** List of tee services this VM wants to access */
+ String[] teeServices;
}
/** Configuration parameters guarded by android.permission.USE_CUSTOM_VIRTUAL_MACHINE */
diff --git a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl
index 9f2a23e..5728a68 100644
--- a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl
+++ b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl
@@ -110,4 +110,7 @@
/** Enable or disable USB passthrough support */
@nullable UsbConfig usbConfig;
+
+ /** List of tee services this VM wants to access */
+ String[] teeServices;
}
diff --git a/android/vm/src/main.rs b/android/vm/src/main.rs
index 110e0ca..7bfd957 100644
--- a/android/vm/src/main.rs
+++ b/android/vm/src/main.rs
@@ -72,6 +72,11 @@
/// Boost uclamp to stablise results for benchmarks.
#[arg(short, long)]
boost_uclamp: bool,
+
+ /// Secure services this VM wants to access.
+ #[cfg(tee_services_allowlist)]
+ #[arg(long)]
+ tee_services: Vec<String>,
}
impl CommonConfig {
@@ -84,6 +89,16 @@
}
}
}
+
+ fn tee_services(&self) -> &[String] {
+ cfg_if::cfg_if! {
+ if #[cfg(tee_services_allowlist)] {
+ &self.tee_services
+ } else {
+ &[]
+ }
+ }
+ }
}
#[derive(Args, Default)]
diff --git a/android/vm/src/run.rs b/android/vm/src/run.rs
index b07a472..2157ea8 100644
--- a/android/vm/src/run.rs
+++ b/android/vm/src/run.rs
@@ -156,6 +156,7 @@
})
.collect::<Result<_, _>>()?,
networkSupported: config.common.network_supported(),
+ teeServices: config.common.tee_services().to_vec(),
..Default::default()
};
@@ -263,8 +264,8 @@
if let Some(mem) = config.common.mem {
vm_config.memoryMib = mem as i32;
}
- if let Some(name) = config.common.name {
- vm_config.name = name;
+ if let Some(ref name) = config.common.name {
+ vm_config.name = name.to_string();
} else {
vm_config.name = String::from("VmRun");
}
@@ -274,6 +275,7 @@
vm_config.cpuTopology = config.common.cpu_topology;
vm_config.hugePages = config.common.hugepages;
vm_config.boostUclamp = config.common.boost_uclamp;
+ vm_config.teeServices = config.common.tee_services().to_vec();
run(
get_service()?.as_ref(),
&VirtualMachineConfig::RawConfig(vm_config),
diff --git a/build/Android.bp b/build/Android.bp
index 4c4fbba..2b97927 100644
--- a/build/Android.bp
+++ b/build/Android.bp
@@ -41,6 +41,9 @@
}) + select(release_flag("RELEASE_AVF_ENABLE_VENDOR_MODULES"), {
true: ["vendor_modules"],
default: [],
+ }) + select(release_flag("RELEASE_AVF_ENABLE_VM_TO_TEE_SERVICES_ALLOWLIST"), {
+ true: ["tee_services_allowlist"],
+ default: [],
}) + select(release_flag("RELEASE_AVF_ENABLE_VIRT_CPUFREQ"), {
true: ["virt_cpufreq"],
default: [],
diff --git a/build/debian/fai_config/package_config/AVF b/build/debian/fai_config/package_config/AVF
index 1be57fe..2e55e90 100644
--- a/build/debian/fai_config/package_config/AVF
+++ b/build/debian/fai_config/package_config/AVF
@@ -1,3 +1,5 @@
PACKAGES install
+bpfcc-tools
+linux-headers-generic
procps
diff --git a/docs/debug/README.md b/docs/debug/README.md
index 4b42531..6e51efa 100644
--- a/docs/debug/README.md
+++ b/docs/debug/README.md
@@ -45,6 +45,25 @@
Note: `--debug full` is the default option when omitted. You need to explicitly
use `--debug none` to set the debug level to NONE.
+### Dump device tree
+
+The VMs device tree can be dumped on creation by adding the `--dump_device_tree`
+argument and passing a path where the device tree gets dumped to, as follows:
+
+```shell
+adb shell /apex/com.android.virt/bin/vm run-microdroid --dump-device-tree PATH
+```
+
+Note: you can set the system property
+`hypervisor.virtualizationmanager.dump_device_tree` to true to always dump the
+device tree to `/data/misc/virtualizationservice/$CID/device_tree.dtb` where
+$CID is the CID of the VM. To set the property, run:
+
+```shell
+adb root
+adb shell setprop hypervisor.virtualizationmanager.dump_device_tree true
+```
+
### Debug policy
Debug policy is a per-device property which forcibly enables selected debugging
diff --git a/guest/forwarder_guest_launcher/Cargo.toml b/guest/forwarder_guest_launcher/Cargo.toml
index 03fda56..c875484 100644
--- a/guest/forwarder_guest_launcher/Cargo.toml
+++ b/guest/forwarder_guest_launcher/Cargo.toml
@@ -7,9 +7,13 @@
[dependencies]
anyhow = "1.0.91"
clap = { version = "4.5.20", features = ["derive"] }
+csv-async = { version = "1.3.0", features = ["tokio"] }
env_logger = "0.11.5"
+futures = "0.3.31"
+listeners = "0.2.1"
log = "0.4.22"
prost = "0.13.3"
+serde = { version = "1.0.215", features = ["derive"] }
tokio = { version = "1.40.0", features = ["process", "rt-multi-thread"] }
tonic = "0.12.3"
vsock = "0.5.1"
diff --git a/guest/forwarder_guest_launcher/src/main.rs b/guest/forwarder_guest_launcher/src/main.rs
index abb39f6..0e06c66 100644
--- a/guest/forwarder_guest_launcher/src/main.rs
+++ b/guest/forwarder_guest_launcher/src/main.rs
@@ -14,19 +14,39 @@
//! Launcher of forwarder_guest
-use anyhow::Context;
+use anyhow::{anyhow, Context};
use clap::Parser;
+use csv_async::AsyncReader;
use debian_service::debian_service_client::DebianServiceClient;
-use debian_service::QueueOpeningRequest;
-use log::debug;
+use debian_service::{QueueOpeningRequest, ReportVmActivePortsRequest};
+use futures::stream::StreamExt;
+use log::{debug, error};
+use serde::Deserialize;
+use std::collections::HashSet;
+use std::process::Stdio;
+use tokio::io::BufReader;
use tokio::process::Command;
-use tonic::transport::Endpoint;
+use tokio::try_join;
+use tonic::transport::{Channel, Endpoint};
use tonic::Request;
mod debian_service {
tonic::include_proto!("com.android.virtualization.vmlauncher.proto");
}
+const NON_PREVILEGED_PORT_RANGE_START: i32 = 1024;
+const TCPSTATES_IP_4: i8 = 4;
+const TCPSTATES_STATE_LISTEN: &str = "LISTEN";
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "UPPERCASE")]
+struct TcpStateRow {
+ ip: i8,
+ lport: i32,
+ oldstate: String,
+ newstate: String,
+}
+
#[derive(Parser)]
/// Flags for running command
pub struct Args {
@@ -40,15 +60,9 @@
grpc_port: String,
}
-#[tokio::main]
-async fn main() -> Result<(), Box<dyn std::error::Error>> {
- env_logger::init();
- debug!("Starting forwarder_guest_launcher");
- let args = Args::parse();
- let addr = format!("https://{}:{}", args.host_addr, args.grpc_port);
-
- let channel = Endpoint::from_shared(addr)?.connect().await?;
- let mut client = DebianServiceClient::new(channel);
+async fn process_forwarding_request_queue(
+ mut client: DebianServiceClient<Channel>,
+) -> Result<(), Box<dyn std::error::Error>> {
let cid = vsock::get_local_cid().context("Failed to get CID of VM")?;
let mut res_stream = client
.open_forwarding_request_queue(Request::new(QueueOpeningRequest { cid: cid as i32 }))
@@ -72,5 +86,78 @@
.arg(format!("vsock:2:{}", vsock_port))
.spawn();
}
+ Err(anyhow!("process_forwarding_request_queue is terminated").into())
+}
+
+async fn send_active_ports_report(
+ listening_ports: HashSet<i32>,
+ client: &mut DebianServiceClient<Channel>,
+) -> Result<(), Box<dyn std::error::Error>> {
+ let res = client
+ .report_vm_active_ports(Request::new(ReportVmActivePortsRequest {
+ ports: listening_ports.into_iter().collect(),
+ }))
+ .await?
+ .into_inner();
+ if res.success {
+ debug!("Successfully reported active ports to the host");
+ } else {
+ error!("Failure response received from the host for reporting active ports");
+ }
+ Ok(())
+}
+
+async fn report_active_ports(
+ mut client: DebianServiceClient<Channel>,
+) -> Result<(), Box<dyn std::error::Error>> {
+ let mut cmd =
+ Command::new("/usr/sbin/tcpstates-bpfcc").arg("-s").stdout(Stdio::piped()).spawn()?;
+ let stdout = cmd.stdout.take().context("Failed to get stdout of tcpstates")?;
+ let mut csv_reader = AsyncReader::from_reader(BufReader::new(stdout));
+ let header = csv_reader.headers().await?.clone();
+
+ // TODO(b/340126051): Consider using NETLINK_SOCK_DIAG for the optimization.
+ let listeners = listeners::get_all()?;
+ // TODO(b/340126051): Support distinguished port forwarding for ipv6 as well.
+ let mut listening_ports: HashSet<_> = listeners
+ .iter()
+ .map(|x| x.socket)
+ .filter(|x| x.is_ipv4())
+ .map(|x| x.port().into())
+ .filter(|x| *x >= NON_PREVILEGED_PORT_RANGE_START) // Ignore privileged ports
+ .collect();
+ send_active_ports_report(listening_ports.clone(), &mut client).await?;
+
+ let mut records = csv_reader.records();
+ while let Some(record) = records.next().await {
+ let row: TcpStateRow = record?.deserialize(Some(&header))?;
+ if row.ip != TCPSTATES_IP_4 {
+ continue;
+ }
+ match (row.oldstate.as_str(), row.newstate.as_str()) {
+ (_, TCPSTATES_STATE_LISTEN) => {
+ listening_ports.insert(row.lport);
+ }
+ (TCPSTATES_STATE_LISTEN, _) => {
+ listening_ports.remove(&row.lport);
+ }
+ (_, _) => continue,
+ }
+ send_active_ports_report(listening_ports.clone(), &mut client).await?;
+ }
+
+ Err(anyhow!("report_active_ports is terminated").into())
+}
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ env_logger::init();
+ debug!("Starting forwarder_guest_launcher");
+ let args = Args::parse();
+ let addr = format!("https://{}:{}", args.host_addr, args.grpc_port);
+ let channel = Endpoint::from_shared(addr)?.connect().await?;
+ let client = DebianServiceClient::new(channel);
+
+ try_join!(process_forwarding_request_queue(client.clone()), report_active_ports(client))?;
Ok(())
}
diff --git a/guest/trusty/security_vm/launcher/src/main.rs b/guest/trusty/security_vm/launcher/src/main.rs
index 4298181..9611f26 100644
--- a/guest/trusty/security_vm/launcher/src/main.rs
+++ b/guest/trusty/security_vm/launcher/src/main.rs
@@ -44,8 +44,8 @@
#[arg(long, default_value_t = 128)]
memory_size_mib: i32,
- /// CPU Topology exposed to the VM <one-cpu|match_host>
- #[arg(long, default_value = "one_cpu", value_parser = parse_cpu_topology)]
+ /// CPU Topology exposed to the VM <one-cpu|match-host>
+ #[arg(long, default_value = "one-cpu", value_parser = parse_cpu_topology)]
cpu_topology: CpuTopology,
}
diff --git a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachineConfig.java b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachineConfig.java
index 3d1964d..8230166 100644
--- a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachineConfig.java
+++ b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachineConfig.java
@@ -744,6 +744,7 @@
return usbConfig;
})
.orElse(null);
+ config.teeServices = EMPTY_STRING_ARRAY;
return config;
}
@@ -798,6 +799,7 @@
new VirtualMachineAppConfig.CustomConfig();
customConfig.devices = EMPTY_STRING_ARRAY;
customConfig.extraKernelCmdlineParams = EMPTY_STRING_ARRAY;
+ customConfig.teeServices = EMPTY_STRING_ARRAY;
try {
customConfig.vendorImage =
ParcelFileDescriptor.open(mVendorDiskImage, MODE_READ_ONLY);
diff --git a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
index adab521..03d7fef 100644
--- a/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
+++ b/tests/hostside/java/com/android/microdroid/test/MicrodroidHostTests.java
@@ -1345,9 +1345,8 @@
}
@Test
- @Parameters(method = "gkiVersions")
+ @Parameters(method = "osVersions")
@TestCaseName("{method}_os_{0}")
- @Ignore("b/360388014") // TODO(b/360388014): fix & re-enable
public void microdroidDeviceTreeCompat(String os) throws Exception {
assumeArm64Supported();
final String configPath = "assets/vm_config.json";
@@ -1374,9 +1373,8 @@
}
@Test
- @Parameters(method = "gkiVersions")
+ @Parameters(method = "osVersions")
@TestCaseName("{method}_os_{0}")
- @Ignore("b/360388014") // TODO(b/360388014): fix & re-enable
public void microdroidProtectedDeviceTreeCompat(String os) throws Exception {
assumeArm64Supported();
final String configPath = "assets/vm_config.json";