blob: e98ab5ce3bb68994b6ba76e35d2e624a4fd3e10b [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Seungjae Yoo13af0b62024-05-20 14:15:13 +090017use crate::{get_calling_pid, get_calling_uid, get_this_pid};
Alan Stokesfda70842023-12-20 17:50:14 +000018use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use crate::composite::make_composite_image;
Akilesh Kailash05515dc2024-10-22 21:42:52 -070020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, SharedPathConfig, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
Jaewan Kimabd328b2024-12-10 15:59:33 +090021use crate::debug_config::{DebugConfig, DebugPolicy};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Inseob Kimf79c5722024-12-16 17:29:57 +090023use crate::payload::{ApexInfoList, add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Nikita Ioffe13748d22024-10-23 15:10:39 +000024use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Jaewan Kimf43372b2024-12-13 18:33:58 +090032 AssignedDevices::AssignedDevices,
Inseob Kim53d0b212023-07-20 16:58:37 +090033 AssignableDevice::AssignableDevice,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Akilesh Kailash05515dc2024-10-22 21:42:52 -070035 SharedPath::SharedPath,
Jeongik Chac181be72024-03-27 00:18:30 +090036 InputDevice::InputDevice,
Devin Moore407df8f2024-08-27 19:39:16 +000037 IVirtualMachine::{self, BnVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000038 IVirtualMachineCallback::IVirtualMachineCallback,
39 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090040 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000041 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090042 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090043 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000044 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010045 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090046 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000047 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090048};
Inseob Kimecde8c02024-09-03 13:11:08 +090049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000052 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053};
Shikha Panware45e9422024-02-28 21:18:10 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +000056use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000057use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
58 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
59 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
60 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
61 SessionInitiationInfo::SessionInitiationInfo,
62};
Inseob Kim7e1877b2024-11-07 17:28:56 +090063use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090065use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010066use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000067 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
68 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000069};
Inseob Kim46257382024-01-03 15:41:22 +090070use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000071use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000072use log::{debug, error, info, warn};
Nikita Ioffe901083f2025-01-20 01:54:28 +000073use microdroid_payload_config::{ApexConfig, ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090074use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000075use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000076use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090077use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090078use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090079use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000080use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000081use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090082use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090083use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000084use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090085use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000086use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090087use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090088use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000089use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010091use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090092use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010093use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000094use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090095use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096
David Brazdil41d1a872022-10-05 14:44:19 +010097/// The unique ID of a VM used (together with a port number) for vsock communication.
98pub type Cid = u32;
99
David Brazdil4b4c5102022-12-19 22:56:20 +0000100pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
101
Devin Moore407df8f2024-08-27 19:39:16 +0000102/// Vsock privileged ports are below this number.
103const VSOCK_PRIV_PORT_MAX: u32 = 1024;
104
Jooyung Han95884632021-07-06 22:27:54 +0900105/// The size of zero.img.
106/// Gaps in composite disk images are filled with a shared zero.img.
107const ZERO_FILLER_SIZE: u64 = 4096;
108
David Brazdilf50c7a62023-04-19 14:22:42 +0000109/// Magic string for the instance image
110const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
111
112/// Version of the instance image format
113const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
114
Alan Stokes0d1ef782022-09-27 13:46:35 +0100115const MICRODROID_OS_NAME: &str = "microdroid";
116
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000117const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000118 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000119
David Brazdilf50c7a62023-04-19 14:22:42 +0000120const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
121
122/// crosvm requires all partitions to be a multiple of 4KiB.
123const PARTITION_GRANULARITY_BYTES: u64 = 4096;
124
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000125const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
126
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100127pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
128 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900129 if cfg!(early) {
130 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
131 } else {
132 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
133 .expect("Could not connect to VirtualizationServiceInternal")
134 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100135 });
136static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
137 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000138
Inseob Kime3e932d2024-12-16 20:06:57 +0900139static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
140 let calling_exe_link = format!("/proc/{}/exe", get_calling_pid());
141 match fs::read_link(&calling_exe_link) {
142 Ok(calling_exe_path) => Some(calling_exe_path),
143 Err(e) => {
144 // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we
145 // discourage vendor apps, regarding such cases as system is safer.
146 // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of
147 // apps.
148 warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system");
149 None
150 }
151 }
152});
153
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000154fn create_or_update_idsig_file(
155 input_fd: &ParcelFileDescriptor,
156 idsig_fd: &ParcelFileDescriptor,
157) -> Result<()> {
158 let mut input = clone_file(input_fd)?;
159 let metadata = input.metadata().context("failed to get input metadata")?;
160 if !metadata.is_file() {
161 bail!("input is not a regular file");
162 }
Alan Stokes25f69362023-03-06 16:51:54 +0000163 let mut sig =
164 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
165 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000166
167 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900168
169 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
170 // if the idsig file already has the same APK digest.
171 if output.metadata()?.len() > 0 {
172 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
173 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
174 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
175 return Ok(());
176 }
177 }
178 // if we fail to read v4signature from output, that's fine. User can pass a random file.
179 // We will anyway overwrite the file to the v4signature generated from input_fd.
180 }
181
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000182 output
183 .seek(SeekFrom::Start(0))
184 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000185 output.set_len(0).context("failed to set_len on the idsig output")?;
186 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000187 Ok(())
188}
189
Alan Stokes25f69362023-03-06 16:51:54 +0000190fn get_current_sdk() -> Result<u32> {
191 let current_sdk = system_properties::read("ro.build.version.sdk")?;
192 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
193 current_sdk.parse().context("Malformed SDK version")
194}
195
David Brazdil4b4c5102022-12-19 22:56:20 +0000196pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
197 for dir_entry in read_dir(path)? {
198 remove_file(dir_entry?.path())?;
199 }
200 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100201}
202
David Brazdil528e0472022-10-10 15:06:02 +0100203/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000204#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000205pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900206 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000207}
208
Shikha Panward8e35422021-10-11 13:51:27 +0000209impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000210 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000211 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
212 let state = &mut *self.state.lock().unwrap();
213 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000214 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000215 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000216 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
217 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000218 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000219 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000220 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000221 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
222 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000223 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000224 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000225 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000226 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000227 .or(Err(StatusCode::UNKNOWN_ERROR))?;
228 }
229 Ok(())
230 }
231}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000232impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000233 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
234 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000235 ///
236 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000237 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000238 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000239 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900240 console_out_fd: Option<&ParcelFileDescriptor>,
241 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000242 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000243 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000244 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000245 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900246 let ret = self.create_vm_internal(
247 config,
248 console_out_fd,
249 console_in_fd,
250 log_fd,
251 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000252 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900253 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000254 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000255 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000256 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000257
Shikha Panwar61a74b52024-02-16 13:17:01 +0000258 /// Allocate a new instance_id to the VM
259 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000260 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000261 GLOBAL_SERVICE.allocateInstanceId()
262 }
263
Andrew Walbrandff3b942021-06-09 15:20:36 +0000264 /// Initialise an empty partition image of the given size to be used as a writable partition.
265 fn initializeWritablePartition(
266 &self,
267 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000268 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900269 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000270 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900271 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900272 let size_bytes = size_bytes
273 .try_into()
274 .with_context(|| format!("Invalid size: {}", size_bytes))
275 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000276 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000277 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000278 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000279 image
280 .seek(SeekFrom::Start(0))
281 .context("failed to move cursor to start")
282 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900283 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700284 // Set the file length. In most filesystems, this will not allocate any physical disk
285 // space, it will only change the logical size.
286 image
287 .set_len(size_bytes)
288 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900289 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000290
291 match partition_type {
292 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700293 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
294 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000295 _ => Err(Error::new(
296 ErrorKind::Unsupported,
297 format!("Unsupported partition type {:?}", partition_type),
298 )),
299 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900300 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
301 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000302
303 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000304 }
305
Shraddha Basantwania9a9c4f2025-02-25 09:51:48 -0800306 fn setEncryptedStorageSize(
307 &self,
308 image_fd: &ParcelFileDescriptor,
309 size: i64,
310 ) -> binder::Result<()> {
311 check_manage_access()?;
312
313 let size = size
314 .try_into()
315 .with_context(|| format!("Invalid size: {}", size))
316 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
317 let size = round_up(size, PARTITION_GRANULARITY_BYTES);
318
319 let image = clone_file(image_fd)?;
320 let image_size = image.metadata().unwrap().len();
321
322 if image_size > size {
323 return Err(Status::new_exception_str(
324 ExceptionCode::ILLEGAL_ARGUMENT,
325 Some("Can't shrink encrypted storage"),
326 ));
327 }
328 // Reset the file length. In most filesystems, this will not allocate any physical disk
329 // space, it will only change the logical size.
330 image.set_len(size).context("Failed to extend file").or_service_specific_exception(-1)?;
331 Ok(())
332 }
333
Jiyong Park0a248432021-08-20 23:32:39 +0900334 /// Creates or update the idsig file by digesting the input APK file.
335 fn createOrUpdateIdsigFile(
336 &self,
337 input_fd: &ParcelFileDescriptor,
338 idsig_fd: &ParcelFileDescriptor,
339 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900340 check_manage_access()?;
341
Jiyong Park2227eaa2023-08-04 11:59:18 +0900342 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900343 Ok(())
344 }
345
Andrew Walbran320b5602021-03-04 16:11:12 +0000346 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
347 /// and as such is only permitted from the shell user.
348 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000349 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000350 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000351 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900352
353 /// Get a list of assignable device types.
354 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
355 // Delegate to the global service, including checking the permission.
356 GLOBAL_SERVICE.getAssignableDevices()
357 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100358
Inseob Kim46257382024-01-03 15:41:22 +0900359 /// Get a list of supported OSes.
360 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
361 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
362 }
363
Jaewan Kimabd328b2024-12-10 15:59:33 +0900364 /// Get printable debug policy for testing and debugging
365 fn getDebugPolicy(&self) -> binder::Result<String> {
366 let debug_policy = DebugPolicy::from_host();
367 Ok(format!("{debug_policy:?}"))
368 }
369
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100370 /// Returns whether given feature is enabled
371 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
372 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000373 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100374 }
Alice Wange64dd182024-01-17 15:57:55 +0000375
376 fn enableTestAttestation(&self) -> binder::Result<()> {
377 GLOBAL_SERVICE.enableTestAttestation()
378 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000379
380 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
381 check_manage_access()?;
382 GLOBAL_SERVICE.isRemoteAttestationSupported()
383 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000384
385 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
386 // The response is specific to Microdroid. Updatable VMs are only possible if device
387 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
388 // this, however other guest OSes may do things differently.
389 check_manage_access()?;
390 Ok(is_secretkeeper_supported())
391 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000392
Shikha Panwar07d701c2024-03-28 14:43:52 +0000393 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
394 check_manage_access()?;
395 GLOBAL_SERVICE.removeVmInstance(instance_id)
396 }
397
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000398 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
399 check_manage_access()?;
400 GLOBAL_SERVICE.claimVmInstance(instance_id)
401 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000402}
403
Inseob Kimecde8c02024-09-03 13:11:08 +0900404/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
405#[derive(Debug, Default)]
406struct EarlyVmContext {
407 /// The unique CID assigned to the VM for vsock communication.
408 cid: Cid,
409 /// Temporary directory for this VM instance.
410 temp_dir: PathBuf,
411}
412
413impl EarlyVmContext {
414 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
415 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
416 // should trust clients, e.g. they won't run two VMs at the same time
417 let _ = remove_dir_all(&temp_dir);
418 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
419
420 Ok(Self { cid, temp_dir })
421 }
422}
423
424impl Interface for EarlyVmContext {}
425
426impl Drop for EarlyVmContext {
427 fn drop(&mut self) {
428 if let Err(e) = remove_dir_all(&self.temp_dir) {
429 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
430 }
431 }
432}
433
434impl IGlobalVmContext for EarlyVmContext {
435 fn getCid(&self) -> binder::Result<i32> {
436 Ok(self.cid as i32)
437 }
438
439 fn getTemporaryDirectory(&self) -> binder::Result<String> {
440 Ok(self.temp_dir.to_string_lossy().to_string())
441 }
442
443 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
444 Err(Status::new_exception_str(
445 ExceptionCode::UNSUPPORTED_OPERATION,
446 Some("Early VM doesn't support setting host console name"),
447 ))
448 }
449}
450
Frederick Mayle3a46b272025-02-10 21:55:49 -0800451#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
452enum CallingPartition {
453 Odm,
454 Product,
455 System,
456 SystemExt,
457 Vendor,
458 Unknown,
459}
460
461impl CallingPartition {
462 fn as_str(&self) -> &'static str {
463 match self {
464 CallingPartition::Odm => "odm",
465 CallingPartition::Product => "product",
466 CallingPartition::System => "system",
467 CallingPartition::SystemExt => "system_ext",
468 CallingPartition::Vendor => "vendor",
469 CallingPartition::Unknown => "[unknown]",
470 }
471 }
472}
473
474impl std::fmt::Display for CallingPartition {
475 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476 write!(f, "{}", self.as_str())
477 }
478}
479
480fn find_partition(path: Option<&Path>) -> binder::Result<CallingPartition> {
Frederick Maylecc9862f2025-02-10 20:42:59 -0800481 let Some(path) = path else {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800482 return Ok(CallingPartition::System);
Inseob Kime3e932d2024-12-16 20:06:57 +0900483 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000484 if path.starts_with("/system/system_ext/") {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800485 return Ok(CallingPartition::SystemExt);
Armelle Laine1a25d982025-01-31 06:39:54 +0000486 }
Frederick Mayle3a46b272025-02-10 21:55:49 -0800487 if path.starts_with("/system/product/") {
488 return Ok(CallingPartition::Product);
489 }
490 let partition = {
491 let mut components = path.components();
492 let Some(std::path::Component::Normal(partition)) = components.nth(1) else {
493 return Err(anyhow!("Can't find partition in '{}'", path.display()))
Frederick Maylecc9862f2025-02-10 20:42:59 -0800494 .or_service_specific_exception(-1);
495 };
Frederick Maylecc9862f2025-02-10 20:42:59 -0800496
Frederick Mayle3a46b272025-02-10 21:55:49 -0800497 // If path is under /apex, find a partition of the preinstalled .apex path
498 if partition == "apex" {
499 let Some(std::path::Component::Normal(apex_name)) = components.next() else {
500 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
501 .or_service_specific_exception(-1);
502 };
503 let apex_info_list = ApexInfoList::load()
504 .context("Failed to get apex info list")
505 .or_service_specific_exception(-1)?;
506 apex_info_list
507 .list
508 .iter()
509 .find(|apex_info| apex_info.name.as_str() == apex_name)
510 .map(|apex_info| apex_info.partition.to_lowercase())
511 .ok_or(anyhow!("Can't find apex info for {apex_name:?}"))
512 .or_service_specific_exception(-1)?
513 } else {
514 partition.to_string_lossy().into_owned()
515 }
516 };
517 Ok(match partition.as_str() {
518 "odm" => CallingPartition::Odm,
519 "product" => CallingPartition::Product,
520 "system" => CallingPartition::System,
521 "system_ext" => CallingPartition::SystemExt,
522 "vendor" => CallingPartition::Vendor,
523 _ => {
524 warn!("unknown partition for '{}'", path.display());
525 CallingPartition::Unknown
526 }
527 })
Inseob Kimecde8c02024-09-03 13:11:08 +0900528}
529
Jiyong Park8611a6c2021-07-09 18:17:44 +0900530impl VirtualizationService {
531 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000532 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900533 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000534
Inseob Kimecde8c02024-09-03 13:11:08 +0900535 fn create_early_vm_context(
536 &self,
537 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900538 calling_exe_path: Option<&Path>,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800539 calling_partition: CallingPartition,
Inseob Kimecde8c02024-09-03 13:11:08 +0900540 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900541 let name = match config {
542 VirtualMachineConfig::RawConfig(config) => &config.name,
543 VirtualMachineConfig::AppConfig(config) => &config.name,
544 };
Frederick Mayle3a46b272025-02-10 21:55:49 -0800545 let early_vm = find_early_vm_for_partition(calling_partition, name)
Inseob Kime3e932d2024-12-16 20:06:57 +0900546 .or_service_specific_exception(-1)?;
547 let calling_exe_path = match calling_exe_path {
548 Some(path) => path,
549 None => {
550 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
551 .or_service_specific_exception(-1)
552 }
553 };
Alice Wang78dd87a2025-02-13 08:56:07 +0000554 early_vm.check_exe_paths_match(calling_exe_path)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900555
556 let cid = early_vm.cid as Cid;
557 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
558
559 let context = EarlyVmContext::new(cid, temp_dir.clone())
560 .context(format!("Can't create early vm contexts for {cid}"))
561 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900562
Jiyong Park690c1ca2024-11-28 18:06:50 +0900563 if requires_vm_service(config) {
564 // Start VM service listening for connections from the new CID on port=CID.
565 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
566 let port = cid;
567 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
568 .context(format!("Could not start RpcServer on port {port}"))
569 .or_service_specific_exception(-1)?;
570 vm_server.start();
571 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
572 } else {
573 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
574 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900575 }
576
David Brazdil209074a2023-01-12 16:44:51 +0000577 fn create_vm_context(
578 &self,
579 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900580 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000581 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000582 const NUM_ATTEMPTS: usize = 5;
583
584 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000585 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000586 let cid = vm_context.getCid()? as Cid;
587 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900588
589 // We don't need to start the VM service for custom VMs.
590 if !requires_vm_service(config) {
591 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
592 }
593
David Brazdil8cf8f482022-11-23 14:21:26 +0000594 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
595
596 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000597 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000598 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000599 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000600 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900601 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000602 }
603 Err(err) => {
604 warn!("Could not start RpcServer on port {}: {}", port, err);
605 }
606 }
607 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900608 Err(anyhow!("Too many attempts to create VM context failed"))
609 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000610 }
611
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000612 fn create_vm_internal(
613 &self,
614 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900615 console_out_fd: Option<&ParcelFileDescriptor>,
616 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000617 log_fd: Option<&ParcelFileDescriptor>,
618 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000619 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000620 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000621 let requester_uid = get_calling_uid();
622 let requester_debug_pid = get_calling_pid();
623
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800624 let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?;
625
Nikita Ioffe631717e2023-09-05 13:38:07 +0100626 check_config_features(config)?;
627
Inseob Kimecde8c02024-09-03 13:11:08 +0900628 if cfg!(early) {
629 check_config_allowed_for_early_vms(config)?;
630 }
631
Nikita Ioffeb1416122024-10-22 12:18:49 +0000632 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
633 info!("callers secontext: {}", caller_secontext);
634
David Brazdil209074a2023-01-12 16:44:51 +0000635 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900636 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800637 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref(), calling_partition)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900638 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900639 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900640 };
Inseob Kim1119d702022-05-02 18:01:58 +0900641
Alan Stokesfda70842023-12-20 17:50:14 +0000642 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100643 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900644 }
645
Nikita Ioffe5776f082023-02-10 21:38:26 +0000646 let gdb_port = extract_gdb_port(config);
647
648 // Additional permission checks if caller request gdb.
649 if gdb_port.is_some() {
650 check_gdb_allowed(config)?;
651 }
652
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800653 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900654 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800655 if let Some(dt_overlay) =
656 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
657 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900658 device_tree_overlays.push(dt_overlay);
659 }
660 if let Some(dtbo) = get_dtbo(config) {
661 let dtbo = File::from(
662 dtbo.as_ref()
663 .try_clone()
664 .context("Failed to create VM DTBO from ParcelFileDescriptor")
665 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
666 );
667 device_tree_overlays.push(dtbo);
668 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900669
Jaewan Kimf3143242024-03-15 06:56:31 +0000670 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000671 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900672 Some(prepare_ramdump_file(&temporary_directory)?)
673 } else {
674 None
675 };
676
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000677 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900678 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100679 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900680 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100681 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100682 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
683 Some(clone_file(fd)?)
684 } else if debug_config.dump_device_tree {
685 Some(prepare_dump_dt_file(&temporary_directory)?)
686 } else {
687 None
688 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000689
690 // Counter to generate unique IDs for temporary image files.
691 let mut next_temporary_image_id = 0;
692 // Files which are referred to from composite images. These must be mapped to the crosvm
693 // child process, and not closed before it is started.
694 let mut indirect_files = vec![];
695
Alan Stokes7bc146c2022-10-20 17:10:32 +0100696 let (is_app_config, config) = match config {
697 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
698 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900699 let config = load_app_config(config, &debug_config, &temporary_directory)
700 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900701 *is_protected = config.protectedVm;
702 let message = format!("Failed to load app config: {:?}", e);
703 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900704 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900705 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100706 (true, BorrowedOrOwned::Owned(config))
707 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000708 };
709 let config = config.as_ref();
710 *is_protected = config.protectedVm;
711
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000712 if !config.teeServices.is_empty() {
713 check_tee_service_permission(&caller_secontext, &config.teeServices)
714 .with_log()
715 .or_binder_exception(ExceptionCode::SECURITY)?;
716 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000717
Jiyong Park3051ffe2024-11-26 14:41:58 +0900718 let kernel = maybe_clone_file(&config.kernel)?;
719 let initrd = maybe_clone_file(&config.initrd)?;
720
721 if config.protectedVm {
722 // Fail fast with a meaningful error message in case device doesn't support pVMs.
723 check_protected_vm_is_supported()?;
724
725 // In a protected VM, we require custom kernels to come from a trusted source
726 // (b/237054515).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800727 check_label_for_kernel_files(&kernel, &initrd, calling_partition)
728 .or_service_specific_exception(-1)?;
Jiyong Park3051ffe2024-11-26 14:41:58 +0900729
730 // Check if partition images are labeled incorrectly. This is to prevent random images
731 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
732 // from being loaded in a pVM. This applies to everything but the instance image in the
733 // raw config, and everything but the non-executable, generated partitions in the app
734 // config.
735 config
736 .disks
737 .iter()
Frederick Mayle9539fb52025-02-13 13:08:15 -0800738 .flat_map(|disk| disk.image.as_ref())
739 .try_for_each(|image| check_label_for_file(image, "disk image", calling_partition))
740 .or_service_specific_exception(-1)?;
741 config
742 .disks
743 .iter()
Jiyong Park3051ffe2024-11-26 14:41:58 +0900744 .flat_map(|disk| disk.partitions.iter())
745 .filter(|partition| {
746 if is_app_config {
747 !is_safe_app_partition(&partition.label)
748 } else {
749 !is_safe_raw_partition(&partition.label)
750 }
751 })
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800752 .try_for_each(|partition| check_label_for_partition(partition, calling_partition))
Jiyong Park3051ffe2024-11-26 14:41:58 +0900753 .or_service_specific_exception(-1)?;
754 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000755
Inseob Kimff48a7c2024-02-26 22:07:21 +0900756 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
757 // have unstable interfaces.
758 // TODO(b/316431494): remove once Treble interfaces are stabilized.
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800759 check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900760
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000761 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900762 write_zero_filler(&zero_filler_path)
763 .context("Failed to make composite image")
764 .with_log()
765 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000766
767 // Assemble disk images if needed.
768 let disks = config
769 .disks
770 .iter()
771 .map(|disk| {
772 assemble_disk_image(
773 disk,
774 &zero_filler_path,
775 &temporary_directory,
776 &mut next_temporary_image_id,
777 &mut indirect_files,
778 )
779 })
780 .collect::<Result<Vec<DiskFile>, _>>()?;
781
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700782 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
783
Jaewan Kimf43372b2024-12-13 18:33:58 +0900784 let (vfio_devices, dtbo) = match &config.devices {
785 AssignedDevices::Devices(devices) if !devices.is_empty() => {
786 let mut set = HashSet::new();
787 for device in devices.iter() {
788 let path = canonicalize(device)
789 .with_context(|| format!("can't canonicalize {device}"))
790 .or_service_specific_exception(-1)?;
791 if !set.insert(path) {
792 return Err(anyhow!("duplicated device {device}"))
793 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
794 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900795 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900796 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
797 let dtbo_file = File::from(
798 GLOBAL_SERVICE
799 .getDtboFile()?
800 .as_ref()
801 .try_clone()
802 .context("Failed to create VM DTBO from ParcelFileDescriptor")
803 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
804 );
805 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900806 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900807 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900808 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900809 let display_config = if cfg!(paravirtualized_devices) {
810 config
811 .displayConfig
812 .as_ref()
813 .map(DisplayConfig::new)
814 .transpose()
815 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
816 } else {
817 None
818 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700819 let gpu_config = if cfg!(paravirtualized_devices) {
820 config
821 .gpuConfig
822 .as_ref()
823 .map(GpuConfig::new)
824 .transpose()
825 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
826 } else {
827 None
828 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900829
Jeongik Chac181be72024-03-27 00:18:30 +0900830 let input_device_options = if cfg!(paravirtualized_devices) {
831 config
832 .inputDevices
833 .iter()
834 .map(to_input_device_option_from)
835 .collect::<Result<Vec<InputDeviceOption>, _>>()
836 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
837 } else {
838 vec![]
839 };
840
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900841 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900842 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900843 if *is_protected {
844 return Err(anyhow!("Network feature is not supported for pVM yet"))
845 .with_log()
846 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
847 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900848 Some(File::from(
849 GLOBAL_SERVICE
850 .createTapInterface(&get_this_pid().to_string())?
851 .as_ref()
852 .try_clone()
853 .context("Failed to get TAP interface from ParcelFileDescriptor")
854 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
855 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900856 } else {
857 None
858 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800859
860 let audio_config = if cfg!(paravirtualized_devices) {
861 config.audioConfig.as_ref().map(AudioConfig::new)
862 } else {
863 None
864 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900865
Elie Kheirallah29d72912024-08-07 20:17:26 +0000866 let usb_config = config
867 .usbConfig
868 .as_ref()
869 .map(UsbConfig::new)
870 .unwrap_or(Ok(UsbConfig { controller: false }))
871 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
872
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000873 let detect_hangup = is_app_config && gdb_port.is_none();
874
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800875 let custom_memory_backing_files = config
876 .customMemoryBackingFiles
877 .iter()
878 .map(|memory_backing_file| {
879 Ok((
880 clone_file(
881 memory_backing_file
882 .file
883 .as_ref()
884 .context("missing CustomMemoryBackingFile FD")
885 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
886 )?
887 .into(),
888 memory_backing_file.rangeStart as u64,
889 memory_backing_file.size as u64,
890 ))
891 })
892 .collect::<binder::Result<_>>()?;
893
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000894 // Actually start the VM.
895 let crosvm_config = CrosvmConfig {
896 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000897 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000898 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000899 kernel,
900 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000901 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700902 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000903 params: config.params.to_owned(),
904 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900905 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700906 memory_mib: config
907 .memoryMib
908 .try_into()
909 .ok()
910 .and_then(NonZeroU32::new)
911 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800912 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000913 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900914 console_out_fd,
915 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000916 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900917 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000918 indirect_files,
919 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000920 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000921 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900922 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000923 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900924 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900925 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900926 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000927 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900928 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800929 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000930 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700931 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800932 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800933 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000934 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000935 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800936 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
937 instance_id,
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800938 custom_memory_backing_files,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000939 };
940 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100941 VmInstance::new(
942 crosvm_config,
943 temporary_directory,
944 requester_uid,
945 requester_debug_pid,
946 vm_context,
947 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900948 .with_context(|| format!("Failed to create VM with config {:?}", config))
949 .with_log()
950 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000951 );
952 state.add_vm(Arc::downgrade(&instance));
953 Ok(VirtualMachine::create(instance))
954 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900955}
956
Alan Stokesfda70842023-12-20 17:50:14 +0000957/// Returns whether a VM config represents a "custom" virtual machine, which requires the
958/// USE_CUSTOM_VIRTUAL_MACHINE.
959fn is_custom_config(config: &VirtualMachineConfig) -> bool {
960 match config {
961 // Any raw (non-Microdroid) VM is considered custom.
962 VirtualMachineConfig::RawConfig(_) => true,
963 VirtualMachineConfig::AppConfig(config) => {
964 // Some features are reserved for platform apps only, even when using
965 // VirtualMachineAppConfig. Almost all of these features are grouped in the
966 // CustomConfig struct:
967 // - controlling CPUs;
968 // - gdbPort is set, meaning that crosvm will start a gdb server;
969 // - using anything other than the default kernel;
970 // - specifying devices to be assigned.
971 if config.customConfig.is_some() {
972 true
973 } else {
974 // Additional custom features not included in CustomConfig:
975 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000976 // - specifying extra APKs;
977 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900978 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000979 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900980 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
981 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000982 }
983 }
984 }
985}
986
Jiyong Park690c1ca2024-11-28 18:06:50 +0900987/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
988/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
989/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
990/// "microdroid" we run VirtualMachineService
991fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
992 match config {
993 VirtualMachineConfig::AppConfig(_) => true,
994 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
995 }
996}
997
Seungjae Yoo14e60182024-02-21 13:28:31 +0900998fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
999 let VirtualMachineConfig::AppConfig(config) = config else {
1000 return Ok(None);
1001 };
1002 let Some(custom_config) = &config.customConfig else {
1003 return Ok(None);
1004 };
1005 let Some(file) = custom_config.vendorImage.as_ref() else {
1006 return Ok(None);
1007 };
1008
1009 let file = clone_file(file)?;
1010 let size =
1011 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
1012 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
1013 .context("Failed to get vbmeta from microdroid-vendor.img")?;
1014
1015 for descriptor in vbmeta.descriptors()?.iter() {
1016 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
1017 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
1018 return Ok(Some(root_digest.as_bytes().to_vec()));
1019 }
1020 }
1021 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
1022}
1023
Jaewan Kimf43372b2024-12-13 18:33:58 +09001024fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001025 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001026 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001027 temporary_directory: &Path,
1028) -> binder::Result<Option<File>> {
1029 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
1030 // (e.g. instance-id)
1031 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
1032 let host_ref_dt = if host_ref_dt.exists()
1033 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
1034 {
1035 Some(host_ref_dt)
1036 } else {
1037 warn!("VM reference DT doesn't exist in host DT");
1038 None
1039 };
1040
1041 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
1042 .context("Failed to extract vendor hashtree digest")
1043 .or_service_specific_exception(-1)?;
1044
Matt Gilbrideaade4272024-12-05 13:52:42 +00001045 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001046 info!(
1047 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
1048 match the trusted digest in the pvmfw config, causing the VM to fail to start."
1049 );
Alan Stokesf46a17c2025-01-05 15:50:18 +00001050 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001051 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +00001052 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001053 };
1054
Matt Gilbrideaade4272024-12-05 13:52:42 +00001055 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001056 let mut untrusted_props = Vec::with_capacity(2);
1057 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001058 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001059 let want_updatable = extract_want_updatable(config);
1060 if want_updatable && is_secretkeeper_supported() {
1061 // Let guest know that it can defer rollback protection to Secretkeeper by setting
1062 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001063 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001064 let sk: Strong<dyn ISecretkeeper> =
1065 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1066 if sk.getInterfaceVersion()? >= 2 {
1067 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
1068 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001069 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001070 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001071 }
1072 }
1073
1074 let device_tree_overlay = if host_ref_dt.is_some()
1075 || !untrusted_props.is_empty()
1076 || !trusted_props.is_empty()
1077 {
1078 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1079 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1080 let fdt =
1081 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1082 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1083 .or_service_specific_exception(-1)?;
1084 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1085 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1086 } else {
1087 None
1088 };
1089 Ok(device_tree_overlay)
1090}
1091
Jaewan Kimf43372b2024-12-13 18:33:58 +09001092fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1093 let VirtualMachineConfig::RawConfig(config) = config else {
1094 return None;
1095 };
1096 match &config.devices {
1097 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1098 _ => None,
1099 }
1100}
1101
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001102fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001103 let file = OpenOptions::new()
1104 .create_new(true)
1105 .read(true)
1106 .write(true)
1107 .open(zero_filler_path)
1108 .with_context(|| "Failed to create zero.img")?;
1109 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001110 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001111}
1112
David Brazdilf50c7a62023-04-19 14:22:42 +00001113fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1114 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1115 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1116 part.flush()
1117}
1118
1119fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1120 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1121 part.flush()
1122}
1123
1124fn round_up(input: u64, granularity: u64) -> u64 {
1125 if granularity == 0 {
1126 return input;
1127 }
1128 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1129 let result = input.checked_add(granularity - 1).unwrap_or(input);
1130 (result / granularity) * granularity
1131}
1132
Jeongik Chac181be72024-03-27 00:18:30 +09001133fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1134 Ok(match input_device {
1135 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1136 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1137 height: u32::try_from(single_touch.height)?,
1138 width: u32::try_from(single_touch.width)?,
1139 name: if !single_touch.name.is_empty() {
1140 Some(single_touch.name.clone())
1141 } else {
1142 None
1143 },
1144 },
1145 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1146 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1147 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001148 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1149 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1150 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001151 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1152 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1153 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001154 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1155 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1156 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001157 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1158 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1159 height: u32::try_from(trackpad.height)?,
1160 width: u32::try_from(trackpad.width)?,
1161 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1162 },
Jeongik Cha10494912024-07-16 11:19:50 +09001163 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1164 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1165 height: u32::try_from(multi_touch.height)?,
1166 width: u32::try_from(multi_touch.width)?,
1167 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1168 },
Jeongik Chac181be72024-03-27 00:18:30 +09001169 })
1170}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001171
1172fn assemble_shared_paths(
1173 shared_paths: &[SharedPath],
1174 temporary_directory: &Path,
1175) -> Result<Vec<SharedPathConfig>, Status> {
1176 if shared_paths.is_empty() {
1177 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1178 }
1179
1180 shared_paths
1181 .iter()
1182 .map(|path| {
1183 Ok(SharedPathConfig {
1184 path: path.sharedPath.clone(),
1185 host_uid: path.hostUid,
1186 host_gid: path.hostGid,
1187 guest_uid: path.guestUid,
1188 guest_gid: path.guestGid,
1189 mask: path.mask,
1190 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001191 socket_path: temporary_directory
1192 .join(&path.socketPath)
1193 .to_string_lossy()
1194 .to_string(),
1195 socket_fd: maybe_clone_file(&path.socketFd)?,
1196 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001197 })
1198 })
1199 .collect()
1200}
1201
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001202/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1203///
1204/// This may involve assembling a composite disk from a set of partition images.
1205fn assemble_disk_image(
1206 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001207 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001208 temporary_directory: &Path,
1209 next_temporary_image_id: &mut u64,
1210 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001211) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001212 let image = if !disk.partitions.is_empty() {
1213 if disk.image.is_some() {
1214 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001215 return Err(anyhow!("DiskImage contains both image and partitions"))
1216 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001217 }
1218
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001219 let composite_image_filenames =
1220 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1221 let (image, partition_files) = make_composite_image(
1222 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001223 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001224 &composite_image_filenames.composite,
1225 &composite_image_filenames.header,
1226 &composite_image_filenames.footer,
1227 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001228 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1229 .with_log()
1230 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001231
1232 // Pass the file descriptors for the various partition files to crosvm when it
1233 // is run.
1234 indirect_files.extend(partition_files);
1235
1236 image
1237 } else if let Some(image) = &disk.image {
1238 clone_file(image)?
1239 } else {
1240 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001241 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1242 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001243 };
1244
1245 Ok(DiskFile { image, writable: disk.writable })
1246}
1247
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001248fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1249 if let Some(ref mut params) = vm_config.params {
1250 params.push(' ');
1251 params.push_str(param)
1252 } else {
1253 vm_config.params = Some(param.to_owned())
1254 }
1255}
1256
Inseob Kim46257382024-01-03 15:41:22 +09001257fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1258 if config.extension()?.to_str()? != "json" {
1259 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001260 }
Inseob Kim46257382024-01-03 15:41:22 +09001261
1262 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1263}
1264
1265fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1266 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1267 let os_names =
1268 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1269
1270 Ok(os_names)
1271}
1272
1273fn get_supported_os_names() -> Result<HashSet<String>> {
1274 if !cfg!(vendor_modules) {
1275 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1276 }
1277
1278 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1279}
1280
1281fn is_valid_os(os_name: &str) -> bool {
1282 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001283}
1284
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001285fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1286 if !cfg!(vendor_modules) {
1287 return false;
1288 }
1289 match config {
1290 VirtualMachineConfig::RawConfig(_) => false,
1291 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1292 }
1293}
1294
Jooyung Han21e9b922021-06-26 04:14:16 +09001295fn load_app_config(
1296 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001297 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001298 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001299) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001300 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1301 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001302 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001303
Shikha Panwar22e70452022-10-10 18:32:55 +00001304 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1305 Some(clone_file(file)?)
1306 } else {
1307 None
1308 };
1309
Alan Stokesfda70842023-12-20 17:50:14 +00001310 let vm_payload_config;
1311 let extra_apk_files: Vec<_>;
1312 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001313 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001314 vm_payload_config =
1315 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1316 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1317 extra_apk_files = vm_payload_config
1318 .extra_apks
1319 .iter()
1320 .enumerate()
1321 .map(|(i, apk)| {
1322 File::open(PathBuf::from(&apk.path))
1323 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1324 })
1325 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001326 }
Alan Stokesfda70842023-12-20 17:50:14 +00001327 Payload::PayloadConfig(payload_config) => {
1328 vm_payload_config = create_vm_payload_config(payload_config)?;
1329 extra_apk_files =
1330 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1331 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001332 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001333
Inseob Kim89b24592024-02-23 18:59:43 +09001334 let payload_config_os = vm_payload_config.os.name.as_str();
1335 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1336 bail!("'os' in payload config is deprecated");
1337 }
1338
Inseob Kim172f9eb2023-11-06 17:02:08 +09001339 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001340 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001341 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001342 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001343 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001344
1345 // It is safe to construct a filename based on the os_name because we've already checked that it
1346 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001347 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1348 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001349 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001350
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001351 if let Some(custom_config) = &config.customConfig {
1352 if let Some(file) = custom_config.customKernelImage.as_ref() {
1353 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1354 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001355 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001356
1357 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001358 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001359 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001360 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001361
Jaewan Kimf43372b2024-12-13 18:33:58 +09001362 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001363 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001364
1365 for param in custom_config.extraKernelCmdlineParams.iter() {
1366 append_kernel_param(param, &mut vm_config);
1367 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001368
1369 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001370 }
1371
Andrew Walbrancc045902021-07-27 16:06:17 +00001372 if config.memoryMib > 0 {
1373 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001374 }
1375
Chris Wailes6177c662024-05-09 14:37:44 -07001376 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001377 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001378 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001379 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001380 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001381
Shikha Panwar22e70452022-10-10 18:32:55 +00001382 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001383 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001384
1385 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1386 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001387 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001388 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001389 temporary_directory,
1390 apk_file,
1391 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001392 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001393 &vm_payload_config,
1394 &mut vm_config,
1395 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001396
Andrew Walbrancc0db522021-07-12 17:03:42 +00001397 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001398}
1399
Frederick Mayle3a46b272025-02-10 21:55:49 -08001400fn check_partition_for_file(
1401 fd: &ParcelFileDescriptor,
1402 calling_partition: CallingPartition,
1403) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001404 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1405 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1406
1407 // microdroid vendor image is OK
1408 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1409 {
1410 return Ok(());
1411 }
1412
Inseob Kime3e932d2024-12-16 20:06:57 +09001413 let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm");
Frederick Mayle3a46b272025-02-10 21:55:49 -08001414 let is_caller_vendor =
1415 calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm;
Inseob Kime3e932d2024-12-16 20:06:57 +09001416
1417 if is_fd_vendor != is_caller_vendor {
1418 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001419 }
1420
1421 Ok(())
1422}
1423
Inseob Kime3e932d2024-12-16 20:06:57 +09001424fn check_partitions_for_files(
1425 config: &VirtualMachineRawConfig,
Frederick Mayle3a46b272025-02-10 21:55:49 -08001426 calling_partition: CallingPartition,
Inseob Kime3e932d2024-12-16 20:06:57 +09001427) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001428 config
1429 .disks
1430 .iter()
1431 .flat_map(|disk| disk.partitions.iter())
1432 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001433 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001434
Inseob Kime3e932d2024-12-16 20:06:57 +09001435 config
1436 .disks
1437 .iter()
1438 .filter_map(|disk| disk.image.as_ref())
1439 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1440
1441 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1442 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1443 config
1444 .bootloader
1445 .as_ref()
1446 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001447
1448 Ok(())
1449}
1450
Alan Stokes0d1ef782022-09-27 13:46:35 +01001451fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1452 let mut apk_zip = ZipArchive::new(apk_file)?;
1453 let config_file = apk_zip.by_name(config_path)?;
1454 Ok(serde_json::from_reader(config_file)?)
1455}
1456
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001457fn create_vm_payload_config(
1458 payload_config: &VirtualMachinePayloadConfig,
1459) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001460 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1461 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1462 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001463
1464 let payload_binary_name = &payload_config.payloadBinaryName;
1465 if payload_binary_name.contains('/') {
1466 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1467 }
1468
1469 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001470
1471 // The VM only cares about how many there are, these names are actually ignored.
1472 let extra_apk_count = payload_config.extraApks.len();
1473 let extra_apks =
1474 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1475
Nikita Ioffe901083f2025-01-20 01:54:28 +00001476 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1477 // The only payload delivered via Mainline module in this release requires
1478 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1479 // APIs, so we use the fact that the payload is granted
1480 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1481 // com.android.i18n APEX.
1482 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1483 // Microdroid pVMs.
1484 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1485 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1486 } else {
1487 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1488 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001489}
1490
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001491/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001492fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001493 temporary_directory: &Path,
1494 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001495) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001496 let id = *next_temporary_image_id;
1497 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001498 CompositeImageFilenames {
1499 composite: temporary_directory.join(format!("composite-{}.img", id)),
1500 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1501 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1502 }
1503}
1504
1505/// Filenames for a composite disk image, including header and footer partitions.
1506#[derive(Clone, Debug, Eq, PartialEq)]
1507struct CompositeImageFilenames {
1508 /// The composite disk image itself.
1509 composite: PathBuf,
1510 /// The header partition image.
1511 header: PathBuf,
1512 /// The footer partition image.
1513 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001514}
1515
Jiyong Park753553b2021-07-12 21:21:09 +09001516/// Checks whether the caller has a specific permission
1517fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001518 if cfg!(early) {
1519 // Skip permission check for early VMs, in favor of SELinux
1520 return Ok(());
1521 }
David Brazdil1f530702022-10-03 12:18:10 +01001522 let calling_pid = get_calling_pid();
1523 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001524 // Root can do anything
1525 if calling_uid == 0 {
1526 return Ok(());
1527 }
1528 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001529 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001530 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001531 Ok(())
1532 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001533 Err(anyhow!("does not have the {} permission", perm))
1534 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001535 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001536}
1537
Jiyong Park753553b2021-07-12 21:21:09 +09001538/// Check whether the caller of the current Binder method is allowed to manage VMs
1539fn check_manage_access() -> binder::Result<()> {
1540 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1541}
1542
Inseob Kim1119d702022-05-02 18:01:58 +09001543/// Check whether the caller of the current Binder method is allowed to create custom VMs
1544fn check_use_custom_virtual_machine() -> binder::Result<()> {
1545 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1546}
1547
Nikita Ioffe901083f2025-01-20 01:54:28 +00001548/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1549/// rollback protection schema.
1550fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1551 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1552}
1553
Alan Stokes185fe112023-01-10 16:20:55 +00001554/// Return whether a partition is exempt from selinux label checks, because we know that it does
1555/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001556fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001557 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001558 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001559 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001560 || label == "microdroid-apk-idsig"
1561 || label == "payload-metadata"
1562 || label.starts_with("extra-idsig-")
1563}
1564
Alice Wangc206b9b2023-08-28 14:13:51 +00001565/// Returns whether a partition with the given label is safe for a raw config VM.
1566fn is_safe_raw_partition(label: &str) -> bool {
1567 label == "vm-instance"
1568}
1569
Alan Stokes185fe112023-01-10 16:20:55 +00001570/// Check that a file SELinux label is acceptable.
1571///
1572/// We only want to allow code in a VM to be sourced from places that apps, and the
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001573/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001574///
1575/// Note that sepolicy must also grant read access for these types to both virtualization
1576/// service and crosvm.
1577///
1578/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1579/// user devices (W^X).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001580fn check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001581 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001582 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001583 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001584 | "staging_data_file" // updated/staged APEX images
1585 | "system_file" // immutable dm-verity protected partition
1586 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001587 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001588 => Ok(()),
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001589 // It is difficult to require specific label types for vendor initiated VM's files, so we
1590 // allow anything with a vendor prefix.
1591 t if calling_partition == CallingPartition::Vendor && t.starts_with("vendor_") => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001592 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001593 }
1594}
1595
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001596fn check_label_for_partition(
1597 partition: &Partition,
1598 calling_partition: CallingPartition,
1599) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001600 let file = partition.image.as_ref().unwrap().as_ref();
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001601 check_label_is_allowed(&getfilecon(file)?, calling_partition)
Alan Stokes185fe112023-01-10 16:20:55 +00001602 .with_context(|| format!("Partition {} invalid", &partition.label))
1603}
1604
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001605fn check_label_for_kernel_files(
1606 kernel: &Option<File>,
1607 initrd: &Option<File>,
1608 calling_partition: CallingPartition,
1609) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001610 if let Some(f) = kernel {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001611 check_label_for_file(f, "kernel", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001612 }
1613 if let Some(f) = initrd {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001614 check_label_for_file(f, "initrd", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001615 }
1616 Ok(())
1617}
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001618fn check_label_for_file(
Frederick Mayle9539fb52025-02-13 13:08:15 -08001619 file: &impl AsRawFd,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001620 name: &str,
1621 calling_partition: CallingPartition,
1622) -> Result<()> {
1623 check_label_is_allowed(&getfilecon(file)?, calling_partition)
1624 .with_context(|| format!("{} file invalid", name))
Alan Stokes185fe112023-01-10 16:20:55 +00001625}
1626
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001627/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1628#[derive(Debug)]
1629struct VirtualMachine {
1630 instance: Arc<VmInstance>,
1631}
1632
1633impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001634 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001635 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001636 }
1637}
1638
1639impl Interface for VirtualMachine {}
1640
Devin Moore407df8f2024-08-27 19:39:16 +00001641impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001642 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001643 // Don't check permission. The owner of the VM might have passed this binder object to
1644 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001645 Ok(self.instance.cid as i32)
1646 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001647
Andrew Walbran6b650662021-09-07 13:13:23 +00001648 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001649 // Don't check permission. The owner of the VM might have passed this binder object to
1650 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001651 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001652 }
1653
1654 fn registerCallback(
1655 &self,
1656 callback: &Strong<dyn IVirtualMachineCallback>,
1657 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001658 // Don't check permission. The owner of the VM might have passed this binder object to
1659 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001660
1661 // Only register callback if it may be notified.
1662 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1663 let vm_state = self.instance.vm_state.lock().unwrap();
1664 if matches!(*vm_state, VmState::Dead) {
1665 warn!("Ignoring registerCallback() after VM is died");
1666 } else {
1667 self.instance.callbacks.add(callback.clone());
1668 }
1669 drop(vm_state);
1670
Andrew Walbrandae07162021-03-12 17:05:20 +00001671 Ok(())
1672 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001673
Andrew Walbranf8d94112021-09-07 11:45:36 +00001674 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001675 self.instance
1676 .start()
1677 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1678 .with_log()
1679 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001680 }
1681
Inseob Kima446f802022-07-11 19:46:37 +09001682 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001683 self.instance
1684 .kill()
1685 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1686 .with_log()
1687 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001688 }
1689
Keir Fraser48221ba2024-07-12 14:05:02 +00001690 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1691 let balloon = self
1692 .instance
1693 .get_memory_balloon()
1694 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1695 .with_log()
1696 .or_service_specific_exception(-1)?;
1697 Ok(balloon.try_into().unwrap())
1698 }
1699
1700 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001701 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001702 .set_memory_balloon(num_bytes.try_into().unwrap())
1703 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001704 .with_log()
1705 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001706 }
1707
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001708 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001709 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001710 return Err(Status::new_service_specific_error_str(
1711 IVirtualMachine::ERROR_UNEXPECTED,
1712 Some("Virtual Machine is not running"),
1713 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001714 }
Alan Stokes10c47672022-12-13 17:17:08 +00001715 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001716 if port < VSOCK_PRIV_PORT_MAX {
1717 return Err(Status::new_service_specific_error_str(
1718 IVirtualMachine::ERROR_UNEXPECTED,
1719 Some("Can't connect to privileged port {port}"),
1720 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001721 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001722 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1723 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001724 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001725 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001726 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001727
Devin Moore407df8f2024-08-27 19:39:16 +00001728 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1729 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1730 return Err(Status::new_service_specific_error_str(
1731 IVirtualMachine::ERROR_UNEXPECTED,
1732 Some("Virtual Machine is not running"),
1733 ));
1734 }
1735 let port = port as u32;
1736 if port < VSOCK_PRIV_PORT_MAX {
1737 return Err(Status::new_service_specific_error_str(
1738 IVirtualMachine::ERROR_UNEXPECTED,
1739 Some("Can't connect to privileged port {port}"),
1740 ));
1741 }
1742 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001743 let addr = sockaddr_vm {
1744 svm_family: AF_VSOCK as sa_family_t,
1745 svm_reserved1: 0,
1746 svm_port: port,
1747 svm_cid: cid,
1748 svm_zero: [0u8; 4],
1749 };
1750 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001751 let accessor = Accessor::new(name, get_connection_info);
1752 accessor
1753 .as_binder()
1754 .context("The newly created Accessor should always have a binder")
1755 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1756 }
1757
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001758 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1759 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1760 }
Jiyong Park23b67392024-07-04 13:51:42 +09001761
1762 fn suspend(&self) -> binder::Result<()> {
1763 self.instance
1764 .suspend()
1765 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1766 .with_log()
1767 .or_service_specific_exception(-1)
1768 }
1769
1770 fn resume(&self) -> binder::Result<()> {
1771 self.instance
1772 .resume()
1773 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1774 .with_log()
1775 .or_service_specific_exception(-1)
1776 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001777}
1778
1779impl Drop for VirtualMachine {
1780 fn drop(&mut self) {
1781 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001782 if let Err(e) = self.instance.kill() {
1783 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1784 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001785 }
1786}
1787
1788/// A set of Binders to be called back in response to various events on the VM, such as when it
1789/// dies.
1790#[derive(Debug, Default)]
1791pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1792
1793impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001794 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001795 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001796 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001797 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001798 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001799 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001800 }
1801 }
1802 }
1803
Inseob Kim14cb8692021-08-31 21:50:39 +09001804 /// Call all registered callbacks to notify that the payload is ready to serve.
1805 pub fn notify_payload_ready(&self, cid: Cid) {
1806 let callbacks = &*self.0.lock().unwrap();
1807 for callback in callbacks {
1808 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001809 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001810 }
1811 }
1812 }
1813
Inseob Kim2444af92021-08-31 01:22:50 +09001814 /// Call all registered callbacks to notify that the payload has finished.
1815 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1816 let callbacks = &*self.0.lock().unwrap();
1817 for callback in callbacks {
1818 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001819 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001820 }
1821 }
1822 }
1823
Jooyung Handd0a1732021-11-23 15:26:20 +09001824 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001825 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001826 let callbacks = &*self.0.lock().unwrap();
1827 for callback in callbacks {
1828 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001829 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001830 }
1831 }
1832 }
1833
Andrew Walbrandae07162021-03-12 17:05:20 +00001834 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001835 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001836 let mut callbacks = self.0.lock().unwrap();
1837 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001838 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001839 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001840 }
1841 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001842
1843 // Nothing to notify afterward because VM cannot be restarted.
1844 // Explicitly clear callbacks to prevent potential cyclic references
1845 // between callback and VmInstance.
1846 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001847 }
1848
1849 /// Add a new callback to the set.
1850 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1851 self.0.lock().unwrap().push(callback);
1852 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001853}
1854
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001855/// The mutable state of the VirtualizationService. There should only be one instance of this
1856/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001857#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001858struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001859 /// The VMs which have been started. When VMs are started a weak reference is added to this
1860 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1861 /// the Binder client are dropped the weak reference here will become invalid, and will be
1862 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001863 vms: Vec<Weak<VmInstance>>,
1864}
1865
1866impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001867 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001868 fn vms(&self) -> Vec<Arc<VmInstance>> {
1869 // Attempt to upgrade the weak pointers to strong pointers.
1870 self.vms.iter().filter_map(Weak::upgrade).collect()
1871 }
1872
1873 /// Add a new VM to the list.
1874 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1875 // Garbage collect any entries from the stored list which no longer exist.
1876 self.vms.retain(|vm| vm.strong_count() > 0);
1877
1878 // Actually add the new VM.
1879 self.vms.push(vm);
1880 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001881
Jiyong Park8611a6c2021-07-09 18:17:44 +09001882 /// Get a VM that corresponds to the given cid
1883 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1884 self.vms().into_iter().find(|vm| vm.cid == cid)
1885 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001886}
1887
Andrew Walbran6b650662021-09-07 13:13:23 +00001888/// Gets the `VirtualMachineState` of the given `VmInstance`.
1889fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001890 match &*instance.vm_state.lock().unwrap() {
1891 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1892 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001893 PayloadState::Starting => VirtualMachineState::STARTING,
1894 PayloadState::Started => VirtualMachineState::STARTED,
1895 PayloadState::Ready => VirtualMachineState::READY,
1896 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001897 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001898 },
1899 VmState::Dead => VirtualMachineState::DEAD,
1900 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001901 }
1902}
1903
David Brazdilf50c7a62023-04-19 14:22:42 +00001904/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001905pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1906 file.as_ref()
1907 .try_clone()
1908 .context("Failed to clone File from ParcelFileDescriptor")
1909 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001910 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001911}
1912
Andrew Walbrand3a84182021-09-07 14:48:52 +00001913/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001914fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001915 file.as_ref().map(clone_file).transpose()
1916}
1917
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001918/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001919fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1920 // SAFETY: ownership is transferred from stream to f
1921 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1922 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001923}
1924
Jiyong Parkdcf17412022-02-08 15:07:23 +09001925/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001926fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1927 VersionReq::parse(s)
1928 .with_context(|| format!("Invalid platform version requirement {}", s))
1929 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001930}
1931
Jiyong Parked180932023-02-24 19:55:41 +09001932/// Create the empty ramdump file
1933fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1934 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1935 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1936 // owner) for readout.
1937 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001938 let ramdump = File::create(ramdump_path)
1939 .context("Failed to prepare ramdump file")
1940 .with_log()
1941 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001942 Ok(ramdump)
1943}
1944
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001945/// Create the empty device tree dump file
1946fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1947 let path = temporary_directory.join("device_tree.dtb");
1948 let file = File::create(path)
1949 .context("Failed to prepare device tree dump file")
1950 .with_log()
1951 .or_service_specific_exception(-1)?;
1952 Ok(file)
1953}
1954
Nikita Ioffe5776f082023-02-10 21:38:26 +00001955fn is_protected(config: &VirtualMachineConfig) -> bool {
1956 match config {
1957 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1958 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1959 }
1960}
1961
1962fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1963 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001964 return Err(anyhow!("Can't use gdb with protected VMs"))
1965 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001966 }
1967
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001968 if get_debug_level(config) == Some(DebugLevel::NONE) {
1969 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1970 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001971 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001972
1973 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001974}
1975
Shikha Panwar61a74b52024-02-16 13:17:01 +00001976fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1977 match config {
1978 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1979 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1980 }
1981}
1982
Alan Stokesc96b35e2024-05-03 13:21:20 +01001983fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1984 match config {
1985 VirtualMachineConfig::RawConfig(_) => true,
1986 VirtualMachineConfig::AppConfig(config) => {
1987 let Some(custom) = &config.customConfig else { return true };
1988 custom.wantUpdatable
1989 }
1990 }
1991}
1992
Nikita Ioffe5776f082023-02-10 21:38:26 +00001993fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1994 match config {
1995 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001996 VirtualMachineConfig::AppConfig(config) => {
1997 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1998 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001999 }
2000}
2001
Nikita Ioffe631717e2023-09-05 13:38:07 +01002002fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
2003 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2004 if let Some(custom_config) = &config.customConfig {
2005 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
2006 return Err(anyhow!("vendor modules feature is disabled"))
2007 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2008 }
2009 }
2010 Ok(())
2011}
2012
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002013fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
2014 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2015 if let Some(custom_config) = &config.customConfig {
2016 if !custom_config.devices.is_empty() {
2017 return Err(anyhow!("device assignment feature is disabled"))
2018 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2019 }
2020 }
2021 Ok(())
2022}
2023
Alan Stokesfda70842023-12-20 17:50:14 +00002024fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
2025 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2026 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
2027 if !payload_config.extraApks.is_empty() {
2028 return Err(anyhow!("multi-tenant feature is disabled"))
2029 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2030 }
2031 Ok(())
2032}
2033
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002034fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
2035 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2036 if let Some(custom_config) = &config.customConfig {
2037 if !custom_config.extraKernelCmdlineParams.is_empty() {
2038 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
2039 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2040 }
2041 }
2042 Ok(())
2043}
2044
Nikita Ioffe99548382024-10-21 15:54:46 +00002045fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
2046 match config {
2047 VirtualMachineConfig::RawConfig(config) => {
2048 if !config.teeServices.is_empty() {
2049 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2050 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2051 }
2052 }
2053 VirtualMachineConfig::AppConfig(config) => {
2054 if let Some(custom_config) = &config.customConfig {
2055 if !custom_config.teeServices.is_empty() {
2056 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2057 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2058 }
2059 }
2060 }
2061 };
2062 Ok(())
2063}
2064
Nikita Ioffef934e812024-07-05 15:44:41 +00002065fn check_protected_vm_is_supported() -> binder::Result<()> {
2066 let is_pvm_supported =
2067 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
2068 if is_pvm_supported {
2069 Ok(())
2070 } else {
2071 Err(anyhow!("pVM is not supported"))
2072 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
2073 }
2074}
2075
Nikita Ioffe631717e2023-09-05 13:38:07 +01002076fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
2077 if !cfg!(vendor_modules) {
2078 check_no_vendor_modules(config)?;
2079 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002080 if !cfg!(device_assignment) {
2081 check_no_devices(config)?;
2082 }
Alan Stokesfda70842023-12-20 17:50:14 +00002083 if !cfg!(multi_tenant) {
2084 check_no_extra_apks(config)?;
2085 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002086 if !cfg!(debuggable_vms_improvements) {
2087 check_no_extra_kernel_cmdline_params(config)?;
2088 }
Nikita Ioffe99548382024-10-21 15:54:46 +00002089 if !cfg!(tee_services_allowlist) {
2090 check_no_tee_services(config)?;
2091 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002092 Ok(())
2093}
2094
Inseob Kimecde8c02024-09-03 13:11:08 +09002095fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2096 check_no_vendor_modules(config)?;
2097 check_no_devices(config)?;
2098
2099 Ok(())
2100}
2101
Inseob Kim0168b462022-12-27 14:54:35 +09002102fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002103 fd: Option<&ParcelFileDescriptor>,
2104 tag: String,
2105) -> Result<Option<File>, Status> {
2106 if let Some(fd) = fd {
2107 return Ok(Some(clone_file(fd)?));
2108 }
2109
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002110 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002111 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002112
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002113 let mut reader = BufReader::new(File::from(read_fd));
2114 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002115
Frederick Mayle26e41af2025-02-05 18:30:29 -08002116 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002117 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002118 buf.clear();
2119 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002120 match reader.read_until(b'\n', &mut buf) {
2121 Ok(0) => {
2122 // EOF
2123 return;
2124 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002125 Ok(_size) => {
2126 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002127 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002128 // Logs sent via TTY usually end lines with "\r\n".
2129 if buf.last() == Some(&b'\r') {
2130 buf.pop();
2131 }
Inseob Kim0168b462022-12-27 14:54:35 +09002132 }
2133 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2134 }
2135 Err(e) => {
2136 error!("Could not read console pipe: {:?}", e);
2137 return;
2138 }
2139 };
2140 });
2141
2142 Ok(Some(write_fd))
2143}
2144
Jooyung Han35edb8f2021-07-01 16:17:16 +09002145/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2146/// it doesn't require that T implements Clone.
2147enum BorrowedOrOwned<'a, T> {
2148 Borrowed(&'a T),
2149 Owned(T),
2150}
2151
Chris Wailes73a1eb72025-01-15 11:56:43 -08002152impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002153 fn as_ref(&self) -> &T {
2154 match self {
2155 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002156 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002157 }
2158 }
2159}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002160
2161/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2162#[derive(Debug, Default)]
2163struct VirtualMachineService {
2164 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002165 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002166}
2167
2168impl Interface for VirtualMachineService {}
2169
2170impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002171 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2172 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002173 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002174 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002175 vm.update_payload_state(PayloadState::Started)
2176 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002177 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002178
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002179 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2180 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002181 Ok(())
2182 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002183 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002184 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002185 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002186 }
Inseob Kim2444af92021-08-31 01:22:50 +09002187
Inseob Kimc7d28c72021-10-25 14:28:10 +00002188 fn notifyPayloadReady(&self) -> binder::Result<()> {
2189 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002190 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002191 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002192 vm.update_payload_state(PayloadState::Ready)
2193 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002194 vm.callbacks.notify_payload_ready(cid);
2195 Ok(())
2196 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002197 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002198 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002199 }
2200 }
2201
Inseob Kimc7d28c72021-10-25 14:28:10 +00002202 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2203 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002204 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002205 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002206 vm.update_payload_state(PayloadState::Finished)
2207 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002208 vm.callbacks.notify_payload_finished(cid, exit_code);
2209 Ok(())
2210 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002211 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002212 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002213 }
2214 }
2215
Alan Stokes2bead0d2022-09-05 16:58:34 +01002216 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002217 let cid = self.cid;
2218 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002219 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002220 vm.update_payload_state(PayloadState::Finished)
2221 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002222 vm.callbacks.notify_error(cid, error_code, message);
2223 Ok(())
2224 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002225 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002226 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002227 }
2228 }
Alice Wangc2fec932023-02-23 16:24:02 +00002229
Shikha Panware45e9422024-02-28 21:18:10 +00002230 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2231 if !is_secretkeeper_supported() {
2232 return Err(StatusCode::NAME_NOT_FOUND)?;
2233 }
2234 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2235 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002236 }
2237
Alice Wange64dd182024-01-17 15:57:55 +00002238 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2239 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002240 }
Shikha Panwareeae6402025-02-06 19:05:31 +00002241
2242 fn claimSecretkeeperEntry(&self, id: &[u8; 64]) -> binder::Result<()> {
2243 GLOBAL_SERVICE.claimSecretkeeperEntry(id)
2244 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002245}
2246
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002247fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002248 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2249 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002250}
2251
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002252impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002253 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002254 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002255 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002256 BinderFeatures::default(),
2257 )
2258 }
2259}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002260
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002261struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2262
2263impl Interface for SecretkeeperProxy {}
2264
2265impl ISecretkeeper for SecretkeeperProxy {
2266 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2267 // Pass the request to the channel, and read the response.
2268 self.0.processSecretManagementRequest(req)
2269 }
2270
2271 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2272 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2273 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2274 }
2275
2276 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2277 self.0.deleteIds(ids)
2278 }
2279
2280 fn deleteAll(&self) -> binder::Result<()> {
2281 self.0.deleteAll()
2282 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002283
2284 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2285 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2286 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2287 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2288 // use this API from the proxy.
2289 Err(ExceptionCode::SECURITY.into())
2290 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002291}
2292
2293struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2294
2295impl Interface for AuthGraphKeyExchangeProxy {}
2296
2297impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2298 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2299 self.0.create()
2300 }
2301
2302 fn init(
2303 &self,
2304 peer_pub_key: &PubKey,
2305 peer_id: &Identity,
2306 peer_nonce: &[u8],
2307 peer_version: i32,
2308 ) -> binder::Result<KeInitResult> {
2309 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2310 }
2311
2312 fn finish(
2313 &self,
2314 peer_pub_key: &PubKey,
2315 peer_id: &Identity,
2316 peer_signature: &SessionIdSignature,
2317 peer_nonce: &[u8],
2318 peer_version: i32,
2319 own_key: &Key,
2320 ) -> binder::Result<SessionInfo> {
2321 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2322 }
2323
2324 fn authenticationComplete(
2325 &self,
2326 peer_signature: &SessionIdSignature,
2327 shared_keys: &[AuthgraphArc; 2],
2328 ) -> binder::Result<[AuthgraphArc; 2]> {
2329 self.0.authenticationComplete(peer_signature, shared_keys)
2330 }
2331}
2332
Inseob Kimecde8c02024-09-03 13:11:08 +09002333// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002334#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002335struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002336 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002337 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002338 path: String,
2339}
2340
2341#[derive(Debug, Default, Deserialize)]
2342struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002343 early_vm: Vec<EarlyVm>,
2344}
2345
Alice Wang78dd87a2025-02-13 08:56:07 +00002346impl EarlyVm {
2347 /// Verifies that the provided executable path matches the expected path stored in the XML
2348 /// configuration.
2349 /// If the provided path starts with `/system`, it will be stripped before comparison.
2350 fn check_exe_paths_match<P: AsRef<Path>>(&self, calling_exe_path: P) -> binder::Result<()> {
2351 let actual_path = calling_exe_path.as_ref();
2352 if Path::new(&self.path)
2353 == Path::new("/").join(actual_path.strip_prefix("/system").unwrap_or(actual_path))
2354 {
2355 return Ok(());
2356 }
2357 Err(Status::new_service_specific_error_str(
2358 -1,
2359 Some(format!(
2360 "Early VM '{}' executable paths do not match. Expected: {}. Found: {:?}.",
2361 self.name,
2362 self.path,
2363 actual_path.display()
2364 )),
2365 ))
2366 }
2367}
2368
Frederick Mayle3a46b272025-02-10 21:55:49 -08002369static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> =
Inseob Kim7e1877b2024-11-07 17:28:56 +09002370 LazyLock::new(|| Mutex::new(HashMap::new()));
2371
Frederick Mayle3a46b272025-02-10 21:55:49 -08002372fn range_for_partition(partition: CallingPartition) -> Range<Cid> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002373 match partition {
Frederick Mayle3a46b272025-02-10 21:55:49 -08002374 CallingPartition::System => 100..200,
2375 CallingPartition::SystemExt | CallingPartition::Product => 200..300,
2376 CallingPartition::Vendor | CallingPartition::Odm => 300..400,
2377 CallingPartition::Unknown => 0..0,
Inseob Kimecde8c02024-09-03 13:11:08 +09002378 }
2379}
2380
Inseob Kim7e1877b2024-11-07 17:28:56 +09002381fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002382 if !xml_path.exists() {
2383 bail!("{} doesn't exist", xml_path.display());
2384 }
2385
2386 let xml =
2387 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2388 let xml = String::from_utf8(xml)
2389 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2390 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2391 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2392
Inseob Kim7e1877b2024-11-07 17:28:56 +09002393 Ok(early_vms.early_vm)
2394}
Inseob Kimecde8c02024-09-03 13:11:08 +09002395
Inseob Kim7e1877b2024-11-07 17:28:56 +09002396fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2397 for early_vm in early_vms {
2398 let cid = early_vm
2399 .cid
2400 .try_into()
2401 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2402
2403 ensure!(
2404 cid_range.contains(&cid),
2405 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2406 early_vm.name
2407 );
2408 }
2409 Ok(())
2410}
2411
Frederick Mayle3a46b272025-02-10 21:55:49 -08002412fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002413 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2414
Frederick Mayle3a46b272025-02-10 21:55:49 -08002415 if let Some(result) = cache.get(&partition) {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002416 return Ok(result.clone());
2417 }
2418
2419 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2420 let mut early_vms = Vec::new();
2421 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2422 match entry {
2423 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2424 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2425 }
2426 }
2427
Frederick Mayle3a46b272025-02-10 21:55:49 -08002428 validate_cid_range(&early_vms, &range_for_partition(partition))
Inseob Kim7e1877b2024-11-07 17:28:56 +09002429 .with_context(|| format!("CID validation for {partition} failed"))?;
2430
Frederick Mayle3a46b272025-02-10 21:55:49 -08002431 cache.insert(partition, early_vms.clone());
Inseob Kim7e1877b2024-11-07 17:28:56 +09002432
2433 Ok(early_vms)
2434}
2435
2436fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2437 let mut found_vm: Option<&EarlyVm> = None;
2438
2439 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002440 if early_vm.name != name {
2441 continue;
2442 }
2443
Inseob Kimecde8c02024-09-03 13:11:08 +09002444 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002445 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002446 }
2447
2448 found_vm = Some(early_vm);
2449 }
2450
Inseob Kim7e1877b2024-11-07 17:28:56 +09002451 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002452}
2453
Frederick Mayle3a46b272025-02-10 21:55:49 -08002454fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002455 let early_vms = get_early_vms_in_partition(partition)
2456 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2457
2458 Ok(find_early_vm(&early_vms, name)
2459 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2460 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002461}
2462
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002463#[cfg(test)]
2464mod tests {
2465 use super::*;
2466
2467 #[test]
2468 fn test_is_allowed_label_for_partition() -> Result<()> {
2469 let expected_results = vec![
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002470 (CallingPartition::System, "u:object_r:system_file:s0", true),
2471 (CallingPartition::System, "u:object_r:apk_data_file:s0", true),
2472 (CallingPartition::System, "u:object_r:app_data_file:s0", false),
2473 (CallingPartition::System, "u:object_r:app_data_file:s0:c512,c768", false),
2474 (CallingPartition::System, "u:object_r:privapp_data_file:s0:c512,c768", false),
2475 (CallingPartition::System, "invalid", false),
2476 (CallingPartition::System, "user:role:apk_data_file:severity:categories", true),
2477 (
2478 CallingPartition::System,
2479 "user:role:apk_data_file:severity:categories:extraneous",
2480 false,
2481 ),
2482 (CallingPartition::System, "u:object_r:vendor_unknowable:s0", false),
2483 (CallingPartition::Vendor, "u:object_r:vendor_unknowable:s0", true),
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002484 ];
2485
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002486 for (calling_partition, label, expected_valid) in expected_results {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002487 let context = SeContext::new(label)?;
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002488 let result = check_label_is_allowed(&context, calling_partition);
2489 if expected_valid != result.is_ok() {
2490 bail!(
2491 "Expected label {label} to be {} for {calling_partition} partition",
2492 if expected_valid { "allowed" } else { "disallowed" }
2493 );
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002494 }
2495 }
2496 Ok(())
2497 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002498
2499 #[test]
2500 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2501 let apk = tempfile::tempfile().unwrap();
2502 let idsig = tempfile::tempfile().unwrap();
2503
2504 let ret = create_or_update_idsig_file(
2505 &ParcelFileDescriptor::new(apk),
2506 &ParcelFileDescriptor::new(idsig),
2507 );
2508 assert!(ret.is_err(), "should fail");
2509 Ok(())
2510 }
2511
2512 #[test]
2513 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2514 let tmp_dir = tempfile::TempDir::new().unwrap();
2515 let apk = File::open(tmp_dir.path()).unwrap();
2516 let idsig = tempfile::tempfile().unwrap();
2517
2518 let ret = create_or_update_idsig_file(
2519 &ParcelFileDescriptor::new(apk),
2520 &ParcelFileDescriptor::new(idsig),
2521 );
2522 assert!(ret.is_err(), "should fail");
2523 Ok(())
2524 }
2525
2526 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2527 /// on ext4 filesystem is passed.
2528 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2529 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2530 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2531 #[test]
2532 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2533 // APEXes are backed by the ext4.
2534 let apk = File::open("/apex/com.android.virt/").unwrap();
2535 let idsig = tempfile::tempfile().unwrap();
2536
2537 let ret = create_or_update_idsig_file(
2538 &ParcelFileDescriptor::new(apk),
2539 &ParcelFileDescriptor::new(idsig),
2540 );
2541 assert!(ret.is_err(), "should fail");
2542 Ok(())
2543 }
Jiyong Park8d192952023-06-26 14:29:51 +09002544
2545 #[test]
2546 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2547 use std::io::Seek;
2548
2549 // Pick any APK
2550 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2551 let mut idsig = tempfile::tempfile().unwrap();
2552
2553 create_or_update_idsig_file(
2554 &ParcelFileDescriptor::new(apk.try_clone()?),
2555 &ParcelFileDescriptor::new(idsig.try_clone()?),
2556 )?;
2557 let modified_orig = idsig.metadata()?.modified()?;
2558 apk.rewind()?;
2559 idsig.rewind()?;
2560
2561 // Call the function again
2562 create_or_update_idsig_file(
2563 &ParcelFileDescriptor::new(apk.try_clone()?),
2564 &ParcelFileDescriptor::new(idsig.try_clone()?),
2565 )?;
2566 let modified_new = idsig.metadata()?.modified()?;
2567 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2568 Ok(())
2569 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002570
2571 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002572 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2573 use std::io::Read;
2574
2575 // Pick any APK
2576 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2577 let idsig_empty = tempfile::tempfile().unwrap();
2578 let mut idsig_invalid = tempfile::tempfile().unwrap();
2579 idsig_invalid.write_all(b"Oops")?;
2580
2581 // Create new idsig
2582 create_or_update_idsig_file(
2583 &ParcelFileDescriptor::new(apk.try_clone()?),
2584 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2585 )?;
2586 apk.rewind()?;
2587
2588 // Update idsig_invalid
2589 create_or_update_idsig_file(
2590 &ParcelFileDescriptor::new(apk.try_clone()?),
2591 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2592 )?;
2593
2594 // Ensure the 2 idsig files have same size!
2595 assert!(
2596 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2597 "idsig files differ in size"
2598 );
2599 // Ensure the 2 idsig files have same content!
2600 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2601 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2602 }
2603 Ok(())
2604 }
2605 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002606 fn test_append_kernel_param_first_param() {
2607 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2608 append_kernel_param("foo=1", &mut vm_config);
2609 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2610 }
2611
2612 #[test]
2613 fn test_append_kernel_param() {
2614 let mut vm_config =
2615 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2616 append_kernel_param("bar=42", &mut vm_config);
2617 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2618 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002619
Inseob Kim46257382024-01-03 15:41:22 +09002620 fn test_extract_os_name_from_config_path(
2621 path: &Path,
2622 expected_result: Option<&str>,
2623 ) -> Result<()> {
2624 let result = extract_os_name_from_config_path(path);
2625 if result.as_deref() != expected_result {
2626 bail!("Expected {:?} but was {:?}", expected_result, &result)
2627 }
2628 Ok(())
2629 }
2630
2631 #[test]
2632 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2633 test_extract_os_name_from_config_path(
2634 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2635 Some("microdroid"),
2636 )
2637 }
2638
2639 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002640 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2641 test_extract_os_name_from_config_path(
2642 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2643 Some("microdroid_16k"),
2644 )
2645 }
2646
2647 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002648 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2649 test_extract_os_name_from_config_path(
2650 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2651 Some("microdroid_gki-android14-6.1"),
2652 )
2653 }
2654
2655 #[test]
2656 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2657 test_extract_os_name_from_config_path(
2658 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2659 None,
2660 )
2661 }
2662
2663 #[test]
2664 fn test_extract_os_name_from_configs() -> Result<()> {
2665 let tmp_dir = tempfile::TempDir::new()?;
2666 let tmp_dir_path = tmp_dir.path().to_owned();
2667
2668 let mut os_names: HashSet<String> = HashSet::new();
2669 os_names.insert("microdroid".to_owned());
2670 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2671 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2672
2673 // config files
2674 for os_name in &os_names {
2675 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2676 }
2677
2678 // fake files not related to configs
2679 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2680 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2681
2682 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2683 Some(s) => s.to_owned(),
2684 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2685 };
2686
2687 let result = extract_os_names_from_configs(&glob_pattern)?;
2688 if result != os_names {
2689 bail!("Expected {:?} but was {:?}", os_names, result);
2690 }
2691 Ok(())
2692 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002693
2694 #[test]
2695 fn test_find_early_vms_from_xml() -> Result<()> {
2696 let tmp_dir = tempfile::TempDir::new()?;
2697 let tmp_dir_path = tmp_dir.path().to_owned();
2698 let xml_path = tmp_dir_path.join("early_vms.xml");
2699
2700 std::fs::write(
2701 &xml_path,
2702 br#"<?xml version="1.0" encoding="utf-8"?>
2703 <early_vms>
2704 <early_vm>
2705 <name>vm_demo_native_early</name>
2706 <cid>123</cid>
2707 <path>/system/bin/vm_demo_native_early</path>
2708 </early_vm>
2709 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002710 <name>vm_demo_native_early_2</name>
2711 <cid>456</cid>
2712 <path>/system/bin/vm_demo_native_early_2</path>
2713 </early_vm>
2714 </early_vms>
2715 "#,
2716 )?;
2717
2718 let cid_range = 100..1000;
2719
2720 let early_vms = get_early_vms_in_path(&xml_path)?;
2721 validate_cid_range(&early_vms, &cid_range)?;
2722
2723 let test_cases = [
2724 (
2725 "vm_demo_native_early",
2726 EarlyVm {
2727 name: "vm_demo_native_early".to_owned(),
2728 cid: 123,
2729 path: "/system/bin/vm_demo_native_early".to_owned(),
2730 },
2731 ),
2732 (
2733 "vm_demo_native_early_2",
2734 EarlyVm {
2735 name: "vm_demo_native_early_2".to_owned(),
2736 cid: 456,
2737 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2738 },
2739 ),
2740 ];
2741
2742 for (name, expected) in test_cases {
2743 let result = find_early_vm(&early_vms, name)?;
2744 assert_eq!(result, &expected);
2745 }
2746
2747 Ok(())
2748 }
2749
2750 #[test]
2751 fn test_invalid_cid_validation() -> Result<()> {
2752 let tmp_dir = tempfile::TempDir::new()?;
2753 let xml_path = tmp_dir.path().join("early_vms.xml");
2754
2755 let cid_range = 100..1000;
2756
2757 for cid in [-1, 999999] {
2758 std::fs::write(
2759 &xml_path,
2760 format!(
2761 r#"<?xml version="1.0" encoding="utf-8"?>
2762 <early_vms>
2763 <early_vm>
2764 <name>vm_demo_invalid_cid</name>
2765 <cid>{cid}</cid>
2766 <path>/system/bin/vm_demo_invalid_cid</path>
2767 </early_vm>
2768 </early_vms>
2769 "#
2770 ),
2771 )?;
2772
2773 let early_vms = get_early_vms_in_path(&xml_path)?;
2774 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2775 }
2776
2777 Ok(())
2778 }
2779
2780 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002781 fn test_symlink_to_system_ext_supported() -> Result<()> {
2782 let link_path = Path::new("/system/system_ext/file");
2783 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002784 assert_eq!(CallingPartition::SystemExt, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002785 Ok(())
2786 }
2787
2788 #[test]
2789 fn test_symlink_to_product_supported() -> Result<()> {
2790 let link_path = Path::new("/system/product/file");
2791 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002792 assert_eq!(CallingPartition::Product, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002793 Ok(())
2794 }
2795
2796 #[test]
Alice Wang78dd87a2025-02-13 08:56:07 +00002797 fn early_vm_exe_paths_match_succeeds_with_same_paths() {
2798 let early_vm = EarlyVm {
2799 name: "vm_demo_native_early".to_owned(),
2800 cid: 123,
2801 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2802 };
2803 let calling_exe_path = "/system_ext/bin/vm_demo_native_early";
2804 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2805 }
2806
2807 #[test]
2808 fn early_vm_exe_paths_match_succeeds_with_calling_exe_path_from_system() {
2809 let early_vm = EarlyVm {
2810 name: "vm_demo_native_early".to_owned(),
2811 cid: 123,
2812 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2813 };
2814 let calling_exe_path = "/system/system_ext/bin/vm_demo_native_early";
2815 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2816 }
2817
2818 #[test]
2819 fn early_vm_exe_paths_match_fails_with_unmatched_paths() {
2820 let early_vm = EarlyVm {
2821 name: "vm_demo_native_early".to_owned(),
2822 cid: 123,
2823 path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2824 };
2825 let calling_exe_path = "/system/etc/system_ext/bin/vm_demo_native_early";
2826 assert!(early_vm.check_exe_paths_match(calling_exe_path).is_err())
2827 }
2828
2829 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002830 fn test_duplicated_early_vms() -> Result<()> {
2831 let tmp_dir = tempfile::TempDir::new()?;
2832 let tmp_dir_path = tmp_dir.path().to_owned();
2833 let xml_path = tmp_dir_path.join("early_vms.xml");
2834
2835 std::fs::write(
2836 &xml_path,
2837 br#"<?xml version="1.0" encoding="utf-8"?>
2838 <early_vms>
2839 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002840 <name>vm_demo_duplicated_name</name>
2841 <cid>456</cid>
2842 <path>/system/bin/vm_demo_duplicated_name_1</path>
2843 </early_vm>
2844 <early_vm>
2845 <name>vm_demo_duplicated_name</name>
2846 <cid>789</cid>
2847 <path>/system/bin/vm_demo_duplicated_name_2</path>
2848 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002849 </early_vms>
2850 "#,
2851 )?;
2852
2853 let cid_range = 100..1000;
2854
Inseob Kim7e1877b2024-11-07 17:28:56 +09002855 let early_vms = get_early_vms_in_path(&xml_path)?;
2856 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002857
Inseob Kim7e1877b2024-11-07 17:28:56 +09002858 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002859
2860 Ok(())
2861 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002862}