blob: 91a05e3ebc4a914272ea8ad5b91d72948a51f817 [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
Jiyong Park0a248432021-08-20 23:32:39 +0900306 /// Creates or update the idsig file by digesting the input APK file.
307 fn createOrUpdateIdsigFile(
308 &self,
309 input_fd: &ParcelFileDescriptor,
310 idsig_fd: &ParcelFileDescriptor,
311 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900312 check_manage_access()?;
313
Jiyong Park2227eaa2023-08-04 11:59:18 +0900314 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900315 Ok(())
316 }
317
Andrew Walbran320b5602021-03-04 16:11:12 +0000318 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
319 /// and as such is only permitted from the shell user.
320 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000321 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000322 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000323 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900324
325 /// Get a list of assignable device types.
326 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
327 // Delegate to the global service, including checking the permission.
328 GLOBAL_SERVICE.getAssignableDevices()
329 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100330
Inseob Kim46257382024-01-03 15:41:22 +0900331 /// Get a list of supported OSes.
332 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
333 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
334 }
335
Jaewan Kimabd328b2024-12-10 15:59:33 +0900336 /// Get printable debug policy for testing and debugging
337 fn getDebugPolicy(&self) -> binder::Result<String> {
338 let debug_policy = DebugPolicy::from_host();
339 Ok(format!("{debug_policy:?}"))
340 }
341
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100342 /// Returns whether given feature is enabled
343 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
344 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000345 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100346 }
Alice Wange64dd182024-01-17 15:57:55 +0000347
348 fn enableTestAttestation(&self) -> binder::Result<()> {
349 GLOBAL_SERVICE.enableTestAttestation()
350 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000351
352 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
353 check_manage_access()?;
354 GLOBAL_SERVICE.isRemoteAttestationSupported()
355 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000356
357 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
358 // The response is specific to Microdroid. Updatable VMs are only possible if device
359 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
360 // this, however other guest OSes may do things differently.
361 check_manage_access()?;
362 Ok(is_secretkeeper_supported())
363 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000364
Shikha Panwar07d701c2024-03-28 14:43:52 +0000365 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
366 check_manage_access()?;
367 GLOBAL_SERVICE.removeVmInstance(instance_id)
368 }
369
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000370 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
371 check_manage_access()?;
372 GLOBAL_SERVICE.claimVmInstance(instance_id)
373 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000374}
375
Inseob Kimecde8c02024-09-03 13:11:08 +0900376/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
377#[derive(Debug, Default)]
378struct EarlyVmContext {
379 /// The unique CID assigned to the VM for vsock communication.
380 cid: Cid,
381 /// Temporary directory for this VM instance.
382 temp_dir: PathBuf,
383}
384
385impl EarlyVmContext {
386 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
387 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
388 // should trust clients, e.g. they won't run two VMs at the same time
389 let _ = remove_dir_all(&temp_dir);
390 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
391
392 Ok(Self { cid, temp_dir })
393 }
394}
395
396impl Interface for EarlyVmContext {}
397
398impl Drop for EarlyVmContext {
399 fn drop(&mut self) {
400 if let Err(e) = remove_dir_all(&self.temp_dir) {
401 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
402 }
403 }
404}
405
406impl IGlobalVmContext for EarlyVmContext {
407 fn getCid(&self) -> binder::Result<i32> {
408 Ok(self.cid as i32)
409 }
410
411 fn getTemporaryDirectory(&self) -> binder::Result<String> {
412 Ok(self.temp_dir.to_string_lossy().to_string())
413 }
414
415 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
416 Err(Status::new_exception_str(
417 ExceptionCode::UNSUPPORTED_OPERATION,
418 Some("Early VM doesn't support setting host console name"),
419 ))
420 }
421}
422
Frederick Mayle3a46b272025-02-10 21:55:49 -0800423#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
424enum CallingPartition {
425 Odm,
426 Product,
427 System,
428 SystemExt,
429 Vendor,
430 Unknown,
431}
432
433impl CallingPartition {
434 fn as_str(&self) -> &'static str {
435 match self {
436 CallingPartition::Odm => "odm",
437 CallingPartition::Product => "product",
438 CallingPartition::System => "system",
439 CallingPartition::SystemExt => "system_ext",
440 CallingPartition::Vendor => "vendor",
441 CallingPartition::Unknown => "[unknown]",
442 }
443 }
444}
445
446impl std::fmt::Display for CallingPartition {
447 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448 write!(f, "{}", self.as_str())
449 }
450}
451
452fn find_partition(path: Option<&Path>) -> binder::Result<CallingPartition> {
Frederick Maylecc9862f2025-02-10 20:42:59 -0800453 let Some(path) = path else {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800454 return Ok(CallingPartition::System);
Inseob Kime3e932d2024-12-16 20:06:57 +0900455 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000456 if path.starts_with("/system/system_ext/") {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800457 return Ok(CallingPartition::SystemExt);
Armelle Laine1a25d982025-01-31 06:39:54 +0000458 }
Frederick Mayle3a46b272025-02-10 21:55:49 -0800459 if path.starts_with("/system/product/") {
460 return Ok(CallingPartition::Product);
461 }
462 let partition = {
463 let mut components = path.components();
464 let Some(std::path::Component::Normal(partition)) = components.nth(1) else {
465 return Err(anyhow!("Can't find partition in '{}'", path.display()))
Frederick Maylecc9862f2025-02-10 20:42:59 -0800466 .or_service_specific_exception(-1);
467 };
Frederick Maylecc9862f2025-02-10 20:42:59 -0800468
Frederick Mayle3a46b272025-02-10 21:55:49 -0800469 // If path is under /apex, find a partition of the preinstalled .apex path
470 if partition == "apex" {
471 let Some(std::path::Component::Normal(apex_name)) = components.next() else {
472 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
473 .or_service_specific_exception(-1);
474 };
475 let apex_info_list = ApexInfoList::load()
476 .context("Failed to get apex info list")
477 .or_service_specific_exception(-1)?;
478 apex_info_list
479 .list
480 .iter()
481 .find(|apex_info| apex_info.name.as_str() == apex_name)
482 .map(|apex_info| apex_info.partition.to_lowercase())
483 .ok_or(anyhow!("Can't find apex info for {apex_name:?}"))
484 .or_service_specific_exception(-1)?
485 } else {
486 partition.to_string_lossy().into_owned()
487 }
488 };
489 Ok(match partition.as_str() {
490 "odm" => CallingPartition::Odm,
491 "product" => CallingPartition::Product,
492 "system" => CallingPartition::System,
493 "system_ext" => CallingPartition::SystemExt,
494 "vendor" => CallingPartition::Vendor,
495 _ => {
496 warn!("unknown partition for '{}'", path.display());
497 CallingPartition::Unknown
498 }
499 })
Inseob Kimecde8c02024-09-03 13:11:08 +0900500}
501
Jiyong Park8611a6c2021-07-09 18:17:44 +0900502impl VirtualizationService {
503 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000504 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900505 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000506
Inseob Kimecde8c02024-09-03 13:11:08 +0900507 fn create_early_vm_context(
508 &self,
509 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900510 calling_exe_path: Option<&Path>,
Inseob Kimecde8c02024-09-03 13:11:08 +0900511 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900512 let name = match config {
513 VirtualMachineConfig::RawConfig(config) => &config.name,
514 VirtualMachineConfig::AppConfig(config) => &config.name,
515 };
Inseob Kime3e932d2024-12-16 20:06:57 +0900516 let calling_partition = find_partition(calling_exe_path)?;
Frederick Mayle3a46b272025-02-10 21:55:49 -0800517 let early_vm = find_early_vm_for_partition(calling_partition, name)
Inseob Kime3e932d2024-12-16 20:06:57 +0900518 .or_service_specific_exception(-1)?;
519 let calling_exe_path = match calling_exe_path {
520 Some(path) => path,
521 None => {
522 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
523 .or_service_specific_exception(-1)
524 }
525 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000526 let expected_exe_path = Path::new(&early_vm.path);
527 if expected_exe_path != calling_exe_path
528 && Path::new("/system").join(expected_exe_path) != calling_exe_path
529 {
Inseob Kimecde8c02024-09-03 13:11:08 +0900530 return Err(anyhow!(
Inseob Kime3e932d2024-12-16 20:06:57 +0900531 "VM '{name}' in partition '{calling_partition}' must be created with '{}', not '{}'",
Inseob Kimecde8c02024-09-03 13:11:08 +0900532 &early_vm.path,
Inseob Kime3e932d2024-12-16 20:06:57 +0900533 calling_exe_path.display()
Inseob Kimecde8c02024-09-03 13:11:08 +0900534 ))
535 .or_service_specific_exception(-1);
536 }
537
538 let cid = early_vm.cid as Cid;
539 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
540
541 let context = EarlyVmContext::new(cid, temp_dir.clone())
542 .context(format!("Can't create early vm contexts for {cid}"))
543 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900544
Jiyong Park690c1ca2024-11-28 18:06:50 +0900545 if requires_vm_service(config) {
546 // Start VM service listening for connections from the new CID on port=CID.
547 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
548 let port = cid;
549 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
550 .context(format!("Could not start RpcServer on port {port}"))
551 .or_service_specific_exception(-1)?;
552 vm_server.start();
553 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
554 } else {
555 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
556 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900557 }
558
David Brazdil209074a2023-01-12 16:44:51 +0000559 fn create_vm_context(
560 &self,
561 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900562 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000563 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000564 const NUM_ATTEMPTS: usize = 5;
565
566 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000567 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000568 let cid = vm_context.getCid()? as Cid;
569 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900570
571 // We don't need to start the VM service for custom VMs.
572 if !requires_vm_service(config) {
573 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
574 }
575
David Brazdil8cf8f482022-11-23 14:21:26 +0000576 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
577
578 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000579 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000580 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000581 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000582 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900583 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000584 }
585 Err(err) => {
586 warn!("Could not start RpcServer on port {}: {}", port, err);
587 }
588 }
589 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900590 Err(anyhow!("Too many attempts to create VM context failed"))
591 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000592 }
593
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000594 fn create_vm_internal(
595 &self,
596 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900597 console_out_fd: Option<&ParcelFileDescriptor>,
598 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000599 log_fd: Option<&ParcelFileDescriptor>,
600 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000601 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000602 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000603 let requester_uid = get_calling_uid();
604 let requester_debug_pid = get_calling_pid();
605
Nikita Ioffe631717e2023-09-05 13:38:07 +0100606 check_config_features(config)?;
607
Inseob Kimecde8c02024-09-03 13:11:08 +0900608 if cfg!(early) {
609 check_config_allowed_for_early_vms(config)?;
610 }
611
Nikita Ioffeb1416122024-10-22 12:18:49 +0000612 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
613 info!("callers secontext: {}", caller_secontext);
614
David Brazdil209074a2023-01-12 16:44:51 +0000615 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900616 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Inseob Kime3e932d2024-12-16 20:06:57 +0900617 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref())?
Inseob Kimecde8c02024-09-03 13:11:08 +0900618 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900619 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900620 };
Inseob Kim1119d702022-05-02 18:01:58 +0900621
Alan Stokesfda70842023-12-20 17:50:14 +0000622 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100623 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900624 }
625
Nikita Ioffe5776f082023-02-10 21:38:26 +0000626 let gdb_port = extract_gdb_port(config);
627
628 // Additional permission checks if caller request gdb.
629 if gdb_port.is_some() {
630 check_gdb_allowed(config)?;
631 }
632
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800633 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900634 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800635 if let Some(dt_overlay) =
636 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
637 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900638 device_tree_overlays.push(dt_overlay);
639 }
640 if let Some(dtbo) = get_dtbo(config) {
641 let dtbo = File::from(
642 dtbo.as_ref()
643 .try_clone()
644 .context("Failed to create VM DTBO from ParcelFileDescriptor")
645 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
646 );
647 device_tree_overlays.push(dtbo);
648 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900649
Jaewan Kimf3143242024-03-15 06:56:31 +0000650 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000651 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900652 Some(prepare_ramdump_file(&temporary_directory)?)
653 } else {
654 None
655 };
656
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000657 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900658 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100659 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900660 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100661 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100662 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
663 Some(clone_file(fd)?)
664 } else if debug_config.dump_device_tree {
665 Some(prepare_dump_dt_file(&temporary_directory)?)
666 } else {
667 None
668 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000669
670 // Counter to generate unique IDs for temporary image files.
671 let mut next_temporary_image_id = 0;
672 // Files which are referred to from composite images. These must be mapped to the crosvm
673 // child process, and not closed before it is started.
674 let mut indirect_files = vec![];
675
Alan Stokes7bc146c2022-10-20 17:10:32 +0100676 let (is_app_config, config) = match config {
677 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
678 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900679 let config = load_app_config(config, &debug_config, &temporary_directory)
680 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900681 *is_protected = config.protectedVm;
682 let message = format!("Failed to load app config: {:?}", e);
683 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900684 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900685 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100686 (true, BorrowedOrOwned::Owned(config))
687 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000688 };
689 let config = config.as_ref();
690 *is_protected = config.protectedVm;
691
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000692 if !config.teeServices.is_empty() {
693 check_tee_service_permission(&caller_secontext, &config.teeServices)
694 .with_log()
695 .or_binder_exception(ExceptionCode::SECURITY)?;
696 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000697
Jiyong Park3051ffe2024-11-26 14:41:58 +0900698 let kernel = maybe_clone_file(&config.kernel)?;
699 let initrd = maybe_clone_file(&config.initrd)?;
700
701 if config.protectedVm {
702 // Fail fast with a meaningful error message in case device doesn't support pVMs.
703 check_protected_vm_is_supported()?;
704
705 // In a protected VM, we require custom kernels to come from a trusted source
706 // (b/237054515).
707 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
708
709 // Check if partition images are labeled incorrectly. This is to prevent random images
710 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
711 // from being loaded in a pVM. This applies to everything but the instance image in the
712 // raw config, and everything but the non-executable, generated partitions in the app
713 // config.
714 config
715 .disks
716 .iter()
717 .flat_map(|disk| disk.partitions.iter())
718 .filter(|partition| {
719 if is_app_config {
720 !is_safe_app_partition(&partition.label)
721 } else {
722 !is_safe_raw_partition(&partition.label)
723 }
724 })
725 .try_for_each(check_label_for_partition)
726 .or_service_specific_exception(-1)?;
727 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000728
Inseob Kimff48a7c2024-02-26 22:07:21 +0900729 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
730 // have unstable interfaces.
731 // TODO(b/316431494): remove once Treble interfaces are stabilized.
Frederick Mayle3a46b272025-02-10 21:55:49 -0800732 check_partitions_for_files(config, find_partition(CALLING_EXE_PATH.as_deref())?)
Inseob Kime3e932d2024-12-16 20:06:57 +0900733 .or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900734
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000735 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900736 write_zero_filler(&zero_filler_path)
737 .context("Failed to make composite image")
738 .with_log()
739 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000740
741 // Assemble disk images if needed.
742 let disks = config
743 .disks
744 .iter()
745 .map(|disk| {
746 assemble_disk_image(
747 disk,
748 &zero_filler_path,
749 &temporary_directory,
750 &mut next_temporary_image_id,
751 &mut indirect_files,
752 )
753 })
754 .collect::<Result<Vec<DiskFile>, _>>()?;
755
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700756 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
757
Jaewan Kimf43372b2024-12-13 18:33:58 +0900758 let (vfio_devices, dtbo) = match &config.devices {
759 AssignedDevices::Devices(devices) if !devices.is_empty() => {
760 let mut set = HashSet::new();
761 for device in devices.iter() {
762 let path = canonicalize(device)
763 .with_context(|| format!("can't canonicalize {device}"))
764 .or_service_specific_exception(-1)?;
765 if !set.insert(path) {
766 return Err(anyhow!("duplicated device {device}"))
767 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
768 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900769 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900770 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
771 let dtbo_file = File::from(
772 GLOBAL_SERVICE
773 .getDtboFile()?
774 .as_ref()
775 .try_clone()
776 .context("Failed to create VM DTBO from ParcelFileDescriptor")
777 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
778 );
779 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900780 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900781 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900782 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900783 let display_config = if cfg!(paravirtualized_devices) {
784 config
785 .displayConfig
786 .as_ref()
787 .map(DisplayConfig::new)
788 .transpose()
789 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
790 } else {
791 None
792 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700793 let gpu_config = if cfg!(paravirtualized_devices) {
794 config
795 .gpuConfig
796 .as_ref()
797 .map(GpuConfig::new)
798 .transpose()
799 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
800 } else {
801 None
802 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900803
Jeongik Chac181be72024-03-27 00:18:30 +0900804 let input_device_options = if cfg!(paravirtualized_devices) {
805 config
806 .inputDevices
807 .iter()
808 .map(to_input_device_option_from)
809 .collect::<Result<Vec<InputDeviceOption>, _>>()
810 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
811 } else {
812 vec![]
813 };
814
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900815 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900816 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900817 if *is_protected {
818 return Err(anyhow!("Network feature is not supported for pVM yet"))
819 .with_log()
820 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
821 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900822 Some(File::from(
823 GLOBAL_SERVICE
824 .createTapInterface(&get_this_pid().to_string())?
825 .as_ref()
826 .try_clone()
827 .context("Failed to get TAP interface from ParcelFileDescriptor")
828 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
829 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900830 } else {
831 None
832 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800833
834 let audio_config = if cfg!(paravirtualized_devices) {
835 config.audioConfig.as_ref().map(AudioConfig::new)
836 } else {
837 None
838 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900839
Elie Kheirallah29d72912024-08-07 20:17:26 +0000840 let usb_config = config
841 .usbConfig
842 .as_ref()
843 .map(UsbConfig::new)
844 .unwrap_or(Ok(UsbConfig { controller: false }))
845 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
846
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000847 let detect_hangup = is_app_config && gdb_port.is_none();
848
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800849 let custom_memory_backing_files = config
850 .customMemoryBackingFiles
851 .iter()
852 .map(|memory_backing_file| {
853 Ok((
854 clone_file(
855 memory_backing_file
856 .file
857 .as_ref()
858 .context("missing CustomMemoryBackingFile FD")
859 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
860 )?
861 .into(),
862 memory_backing_file.rangeStart as u64,
863 memory_backing_file.size as u64,
864 ))
865 })
866 .collect::<binder::Result<_>>()?;
867
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000868 // Actually start the VM.
869 let crosvm_config = CrosvmConfig {
870 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000871 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000872 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000873 kernel,
874 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000875 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700876 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000877 params: config.params.to_owned(),
878 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900879 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700880 memory_mib: config
881 .memoryMib
882 .try_into()
883 .ok()
884 .and_then(NonZeroU32::new)
885 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800886 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000887 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900888 console_out_fd,
889 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000890 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900891 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000892 indirect_files,
893 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000894 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000895 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900896 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000897 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900898 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900899 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900900 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000901 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900902 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800903 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000904 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700905 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800906 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800907 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000908 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000909 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800910 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
911 instance_id,
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800912 custom_memory_backing_files,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000913 };
914 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100915 VmInstance::new(
916 crosvm_config,
917 temporary_directory,
918 requester_uid,
919 requester_debug_pid,
920 vm_context,
921 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900922 .with_context(|| format!("Failed to create VM with config {:?}", config))
923 .with_log()
924 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000925 );
926 state.add_vm(Arc::downgrade(&instance));
927 Ok(VirtualMachine::create(instance))
928 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900929}
930
Alan Stokesfda70842023-12-20 17:50:14 +0000931/// Returns whether a VM config represents a "custom" virtual machine, which requires the
932/// USE_CUSTOM_VIRTUAL_MACHINE.
933fn is_custom_config(config: &VirtualMachineConfig) -> bool {
934 match config {
935 // Any raw (non-Microdroid) VM is considered custom.
936 VirtualMachineConfig::RawConfig(_) => true,
937 VirtualMachineConfig::AppConfig(config) => {
938 // Some features are reserved for platform apps only, even when using
939 // VirtualMachineAppConfig. Almost all of these features are grouped in the
940 // CustomConfig struct:
941 // - controlling CPUs;
942 // - gdbPort is set, meaning that crosvm will start a gdb server;
943 // - using anything other than the default kernel;
944 // - specifying devices to be assigned.
945 if config.customConfig.is_some() {
946 true
947 } else {
948 // Additional custom features not included in CustomConfig:
949 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000950 // - specifying extra APKs;
951 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900952 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000953 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900954 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
955 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000956 }
957 }
958 }
959}
960
Jiyong Park690c1ca2024-11-28 18:06:50 +0900961/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
962/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
963/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
964/// "microdroid" we run VirtualMachineService
965fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
966 match config {
967 VirtualMachineConfig::AppConfig(_) => true,
968 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
969 }
970}
971
Seungjae Yoo14e60182024-02-21 13:28:31 +0900972fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
973 let VirtualMachineConfig::AppConfig(config) = config else {
974 return Ok(None);
975 };
976 let Some(custom_config) = &config.customConfig else {
977 return Ok(None);
978 };
979 let Some(file) = custom_config.vendorImage.as_ref() else {
980 return Ok(None);
981 };
982
983 let file = clone_file(file)?;
984 let size =
985 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
986 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
987 .context("Failed to get vbmeta from microdroid-vendor.img")?;
988
989 for descriptor in vbmeta.descriptors()?.iter() {
990 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
991 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
992 return Ok(Some(root_digest.as_bytes().to_vec()));
993 }
994 }
995 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
996}
997
Jaewan Kimf43372b2024-12-13 18:33:58 +0900998fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000999 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001000 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001001 temporary_directory: &Path,
1002) -> binder::Result<Option<File>> {
1003 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
1004 // (e.g. instance-id)
1005 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
1006 let host_ref_dt = if host_ref_dt.exists()
1007 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
1008 {
1009 Some(host_ref_dt)
1010 } else {
1011 warn!("VM reference DT doesn't exist in host DT");
1012 None
1013 };
1014
1015 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
1016 .context("Failed to extract vendor hashtree digest")
1017 .or_service_specific_exception(-1)?;
1018
Matt Gilbrideaade4272024-12-05 13:52:42 +00001019 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001020 info!(
1021 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
1022 match the trusted digest in the pvmfw config, causing the VM to fail to start."
1023 );
Alan Stokesf46a17c2025-01-05 15:50:18 +00001024 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001025 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +00001026 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001027 };
1028
Matt Gilbrideaade4272024-12-05 13:52:42 +00001029 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001030 let mut untrusted_props = Vec::with_capacity(2);
1031 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001032 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001033 let want_updatable = extract_want_updatable(config);
1034 if want_updatable && is_secretkeeper_supported() {
1035 // Let guest know that it can defer rollback protection to Secretkeeper by setting
1036 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001037 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001038 let sk: Strong<dyn ISecretkeeper> =
1039 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1040 if sk.getInterfaceVersion()? >= 2 {
1041 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
1042 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001043 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001044 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001045 }
1046 }
1047
1048 let device_tree_overlay = if host_ref_dt.is_some()
1049 || !untrusted_props.is_empty()
1050 || !trusted_props.is_empty()
1051 {
1052 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1053 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1054 let fdt =
1055 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1056 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1057 .or_service_specific_exception(-1)?;
1058 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1059 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1060 } else {
1061 None
1062 };
1063 Ok(device_tree_overlay)
1064}
1065
Jaewan Kimf43372b2024-12-13 18:33:58 +09001066fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1067 let VirtualMachineConfig::RawConfig(config) = config else {
1068 return None;
1069 };
1070 match &config.devices {
1071 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1072 _ => None,
1073 }
1074}
1075
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001076fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001077 let file = OpenOptions::new()
1078 .create_new(true)
1079 .read(true)
1080 .write(true)
1081 .open(zero_filler_path)
1082 .with_context(|| "Failed to create zero.img")?;
1083 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001084 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001085}
1086
David Brazdilf50c7a62023-04-19 14:22:42 +00001087fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1088 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1089 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1090 part.flush()
1091}
1092
1093fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1094 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1095 part.flush()
1096}
1097
1098fn round_up(input: u64, granularity: u64) -> u64 {
1099 if granularity == 0 {
1100 return input;
1101 }
1102 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1103 let result = input.checked_add(granularity - 1).unwrap_or(input);
1104 (result / granularity) * granularity
1105}
1106
Jeongik Chac181be72024-03-27 00:18:30 +09001107fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1108 Ok(match input_device {
1109 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1110 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1111 height: u32::try_from(single_touch.height)?,
1112 width: u32::try_from(single_touch.width)?,
1113 name: if !single_touch.name.is_empty() {
1114 Some(single_touch.name.clone())
1115 } else {
1116 None
1117 },
1118 },
1119 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1120 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1121 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001122 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1123 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1124 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001125 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1126 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1127 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001128 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1129 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1130 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001131 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1132 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1133 height: u32::try_from(trackpad.height)?,
1134 width: u32::try_from(trackpad.width)?,
1135 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1136 },
Jeongik Cha10494912024-07-16 11:19:50 +09001137 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1138 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1139 height: u32::try_from(multi_touch.height)?,
1140 width: u32::try_from(multi_touch.width)?,
1141 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1142 },
Jeongik Chac181be72024-03-27 00:18:30 +09001143 })
1144}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001145
1146fn assemble_shared_paths(
1147 shared_paths: &[SharedPath],
1148 temporary_directory: &Path,
1149) -> Result<Vec<SharedPathConfig>, Status> {
1150 if shared_paths.is_empty() {
1151 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1152 }
1153
1154 shared_paths
1155 .iter()
1156 .map(|path| {
1157 Ok(SharedPathConfig {
1158 path: path.sharedPath.clone(),
1159 host_uid: path.hostUid,
1160 host_gid: path.hostGid,
1161 guest_uid: path.guestUid,
1162 guest_gid: path.guestGid,
1163 mask: path.mask,
1164 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001165 socket_path: temporary_directory
1166 .join(&path.socketPath)
1167 .to_string_lossy()
1168 .to_string(),
1169 socket_fd: maybe_clone_file(&path.socketFd)?,
1170 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001171 })
1172 })
1173 .collect()
1174}
1175
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001176/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1177///
1178/// This may involve assembling a composite disk from a set of partition images.
1179fn assemble_disk_image(
1180 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001181 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001182 temporary_directory: &Path,
1183 next_temporary_image_id: &mut u64,
1184 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001185) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001186 let image = if !disk.partitions.is_empty() {
1187 if disk.image.is_some() {
1188 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001189 return Err(anyhow!("DiskImage contains both image and partitions"))
1190 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001191 }
1192
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001193 let composite_image_filenames =
1194 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1195 let (image, partition_files) = make_composite_image(
1196 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001197 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001198 &composite_image_filenames.composite,
1199 &composite_image_filenames.header,
1200 &composite_image_filenames.footer,
1201 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001202 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1203 .with_log()
1204 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001205
1206 // Pass the file descriptors for the various partition files to crosvm when it
1207 // is run.
1208 indirect_files.extend(partition_files);
1209
1210 image
1211 } else if let Some(image) = &disk.image {
1212 clone_file(image)?
1213 } else {
1214 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001215 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1216 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001217 };
1218
1219 Ok(DiskFile { image, writable: disk.writable })
1220}
1221
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001222fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1223 if let Some(ref mut params) = vm_config.params {
1224 params.push(' ');
1225 params.push_str(param)
1226 } else {
1227 vm_config.params = Some(param.to_owned())
1228 }
1229}
1230
Inseob Kim46257382024-01-03 15:41:22 +09001231fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1232 if config.extension()?.to_str()? != "json" {
1233 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001234 }
Inseob Kim46257382024-01-03 15:41:22 +09001235
1236 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1237}
1238
1239fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1240 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1241 let os_names =
1242 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1243
1244 Ok(os_names)
1245}
1246
1247fn get_supported_os_names() -> Result<HashSet<String>> {
1248 if !cfg!(vendor_modules) {
1249 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1250 }
1251
1252 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1253}
1254
1255fn is_valid_os(os_name: &str) -> bool {
1256 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001257}
1258
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001259fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1260 if !cfg!(vendor_modules) {
1261 return false;
1262 }
1263 match config {
1264 VirtualMachineConfig::RawConfig(_) => false,
1265 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1266 }
1267}
1268
Jooyung Han21e9b922021-06-26 04:14:16 +09001269fn load_app_config(
1270 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001271 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001272 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001273) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001274 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1275 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001276 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001277
Shikha Panwar22e70452022-10-10 18:32:55 +00001278 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1279 Some(clone_file(file)?)
1280 } else {
1281 None
1282 };
1283
Alan Stokesfda70842023-12-20 17:50:14 +00001284 let vm_payload_config;
1285 let extra_apk_files: Vec<_>;
1286 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001287 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001288 vm_payload_config =
1289 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1290 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1291 extra_apk_files = vm_payload_config
1292 .extra_apks
1293 .iter()
1294 .enumerate()
1295 .map(|(i, apk)| {
1296 File::open(PathBuf::from(&apk.path))
1297 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1298 })
1299 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001300 }
Alan Stokesfda70842023-12-20 17:50:14 +00001301 Payload::PayloadConfig(payload_config) => {
1302 vm_payload_config = create_vm_payload_config(payload_config)?;
1303 extra_apk_files =
1304 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1305 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001306 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001307
Inseob Kim89b24592024-02-23 18:59:43 +09001308 let payload_config_os = vm_payload_config.os.name.as_str();
1309 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1310 bail!("'os' in payload config is deprecated");
1311 }
1312
Inseob Kim172f9eb2023-11-06 17:02:08 +09001313 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001314 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001315 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001316 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001317 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001318
1319 // It is safe to construct a filename based on the os_name because we've already checked that it
1320 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001321 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1322 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001323 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001324
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001325 if let Some(custom_config) = &config.customConfig {
1326 if let Some(file) = custom_config.customKernelImage.as_ref() {
1327 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1328 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001329 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001330
1331 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001332 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001333 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001334 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001335
Jaewan Kimf43372b2024-12-13 18:33:58 +09001336 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001337 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001338
1339 for param in custom_config.extraKernelCmdlineParams.iter() {
1340 append_kernel_param(param, &mut vm_config);
1341 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001342
1343 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001344 }
1345
Andrew Walbrancc045902021-07-27 16:06:17 +00001346 if config.memoryMib > 0 {
1347 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001348 }
1349
Chris Wailes6177c662024-05-09 14:37:44 -07001350 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001351 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001352 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001353 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001354 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001355
Shikha Panwar22e70452022-10-10 18:32:55 +00001356 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001357 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001358
1359 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1360 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001361 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001362 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001363 temporary_directory,
1364 apk_file,
1365 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001366 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001367 &vm_payload_config,
1368 &mut vm_config,
1369 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001370
Andrew Walbrancc0db522021-07-12 17:03:42 +00001371 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001372}
1373
Frederick Mayle3a46b272025-02-10 21:55:49 -08001374fn check_partition_for_file(
1375 fd: &ParcelFileDescriptor,
1376 calling_partition: CallingPartition,
1377) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001378 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1379 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1380
1381 // microdroid vendor image is OK
1382 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1383 {
1384 return Ok(());
1385 }
1386
Inseob Kime3e932d2024-12-16 20:06:57 +09001387 let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm");
Frederick Mayle3a46b272025-02-10 21:55:49 -08001388 let is_caller_vendor =
1389 calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm;
Inseob Kime3e932d2024-12-16 20:06:57 +09001390
1391 if is_fd_vendor != is_caller_vendor {
1392 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001393 }
1394
1395 Ok(())
1396}
1397
Inseob Kime3e932d2024-12-16 20:06:57 +09001398fn check_partitions_for_files(
1399 config: &VirtualMachineRawConfig,
Frederick Mayle3a46b272025-02-10 21:55:49 -08001400 calling_partition: CallingPartition,
Inseob Kime3e932d2024-12-16 20:06:57 +09001401) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001402 config
1403 .disks
1404 .iter()
1405 .flat_map(|disk| disk.partitions.iter())
1406 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001407 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001408
Inseob Kime3e932d2024-12-16 20:06:57 +09001409 config
1410 .disks
1411 .iter()
1412 .filter_map(|disk| disk.image.as_ref())
1413 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1414
1415 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1416 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1417 config
1418 .bootloader
1419 .as_ref()
1420 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001421
1422 Ok(())
1423}
1424
Alan Stokes0d1ef782022-09-27 13:46:35 +01001425fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1426 let mut apk_zip = ZipArchive::new(apk_file)?;
1427 let config_file = apk_zip.by_name(config_path)?;
1428 Ok(serde_json::from_reader(config_file)?)
1429}
1430
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001431fn create_vm_payload_config(
1432 payload_config: &VirtualMachinePayloadConfig,
1433) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001434 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1435 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1436 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001437
1438 let payload_binary_name = &payload_config.payloadBinaryName;
1439 if payload_binary_name.contains('/') {
1440 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1441 }
1442
1443 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001444
1445 // The VM only cares about how many there are, these names are actually ignored.
1446 let extra_apk_count = payload_config.extraApks.len();
1447 let extra_apks =
1448 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1449
Nikita Ioffe901083f2025-01-20 01:54:28 +00001450 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1451 // The only payload delivered via Mainline module in this release requires
1452 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1453 // APIs, so we use the fact that the payload is granted
1454 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1455 // com.android.i18n APEX.
1456 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1457 // Microdroid pVMs.
1458 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1459 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1460 } else {
1461 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1462 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001463}
1464
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001465/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001466fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001467 temporary_directory: &Path,
1468 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001469) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001470 let id = *next_temporary_image_id;
1471 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001472 CompositeImageFilenames {
1473 composite: temporary_directory.join(format!("composite-{}.img", id)),
1474 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1475 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1476 }
1477}
1478
1479/// Filenames for a composite disk image, including header and footer partitions.
1480#[derive(Clone, Debug, Eq, PartialEq)]
1481struct CompositeImageFilenames {
1482 /// The composite disk image itself.
1483 composite: PathBuf,
1484 /// The header partition image.
1485 header: PathBuf,
1486 /// The footer partition image.
1487 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001488}
1489
Jiyong Park753553b2021-07-12 21:21:09 +09001490/// Checks whether the caller has a specific permission
1491fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001492 if cfg!(early) {
1493 // Skip permission check for early VMs, in favor of SELinux
1494 return Ok(());
1495 }
David Brazdil1f530702022-10-03 12:18:10 +01001496 let calling_pid = get_calling_pid();
1497 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001498 // Root can do anything
1499 if calling_uid == 0 {
1500 return Ok(());
1501 }
1502 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001503 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001504 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001505 Ok(())
1506 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001507 Err(anyhow!("does not have the {} permission", perm))
1508 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001509 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001510}
1511
Jiyong Park753553b2021-07-12 21:21:09 +09001512/// Check whether the caller of the current Binder method is allowed to manage VMs
1513fn check_manage_access() -> binder::Result<()> {
1514 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1515}
1516
Inseob Kim1119d702022-05-02 18:01:58 +09001517/// Check whether the caller of the current Binder method is allowed to create custom VMs
1518fn check_use_custom_virtual_machine() -> binder::Result<()> {
1519 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1520}
1521
Nikita Ioffe901083f2025-01-20 01:54:28 +00001522/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1523/// rollback protection schema.
1524fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1525 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1526}
1527
Alan Stokes185fe112023-01-10 16:20:55 +00001528/// Return whether a partition is exempt from selinux label checks, because we know that it does
1529/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001530fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001531 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001532 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001533 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001534 || label == "microdroid-apk-idsig"
1535 || label == "payload-metadata"
1536 || label.starts_with("extra-idsig-")
1537}
1538
Alice Wangc206b9b2023-08-28 14:13:51 +00001539/// Returns whether a partition with the given label is safe for a raw config VM.
1540fn is_safe_raw_partition(label: &str) -> bool {
1541 label == "vm-instance"
1542}
1543
Alan Stokes185fe112023-01-10 16:20:55 +00001544/// Check that a file SELinux label is acceptable.
1545///
1546/// 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 +09001547/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001548///
1549/// Note that sepolicy must also grant read access for these types to both virtualization
1550/// service and crosvm.
1551///
1552/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1553/// user devices (W^X).
1554fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1555 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001556 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001557 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001558 | "staging_data_file" // updated/staged APEX images
1559 | "system_file" // immutable dm-verity protected partition
1560 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001561 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001562 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001563 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001564 }
1565}
1566
Alan Stokes185fe112023-01-10 16:20:55 +00001567fn check_label_for_partition(partition: &Partition) -> Result<()> {
1568 let file = partition.image.as_ref().unwrap().as_ref();
1569 check_label_is_allowed(&getfilecon(file)?)
1570 .with_context(|| format!("Partition {} invalid", &partition.label))
1571}
1572
1573fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1574 if let Some(f) = kernel {
1575 check_label_for_file(f, "kernel")?;
1576 }
1577 if let Some(f) = initrd {
1578 check_label_for_file(f, "initrd")?;
1579 }
1580 Ok(())
1581}
1582fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1583 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1584}
1585
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001586/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1587#[derive(Debug)]
1588struct VirtualMachine {
1589 instance: Arc<VmInstance>,
1590}
1591
1592impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001593 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001594 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001595 }
1596}
1597
1598impl Interface for VirtualMachine {}
1599
Devin Moore407df8f2024-08-27 19:39:16 +00001600impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001601 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001602 // Don't check permission. The owner of the VM might have passed this binder object to
1603 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001604 Ok(self.instance.cid as i32)
1605 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001606
Andrew Walbran6b650662021-09-07 13:13:23 +00001607 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001608 // Don't check permission. The owner of the VM might have passed this binder object to
1609 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001610 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001611 }
1612
1613 fn registerCallback(
1614 &self,
1615 callback: &Strong<dyn IVirtualMachineCallback>,
1616 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001617 // Don't check permission. The owner of the VM might have passed this binder object to
1618 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001619
1620 // Only register callback if it may be notified.
1621 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1622 let vm_state = self.instance.vm_state.lock().unwrap();
1623 if matches!(*vm_state, VmState::Dead) {
1624 warn!("Ignoring registerCallback() after VM is died");
1625 } else {
1626 self.instance.callbacks.add(callback.clone());
1627 }
1628 drop(vm_state);
1629
Andrew Walbrandae07162021-03-12 17:05:20 +00001630 Ok(())
1631 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001632
Andrew Walbranf8d94112021-09-07 11:45:36 +00001633 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001634 self.instance
1635 .start()
1636 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1637 .with_log()
1638 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001639 }
1640
Inseob Kima446f802022-07-11 19:46:37 +09001641 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001642 self.instance
1643 .kill()
1644 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1645 .with_log()
1646 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001647 }
1648
Keir Fraser48221ba2024-07-12 14:05:02 +00001649 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1650 let balloon = self
1651 .instance
1652 .get_memory_balloon()
1653 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1654 .with_log()
1655 .or_service_specific_exception(-1)?;
1656 Ok(balloon.try_into().unwrap())
1657 }
1658
1659 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001660 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001661 .set_memory_balloon(num_bytes.try_into().unwrap())
1662 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001663 .with_log()
1664 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001665 }
1666
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001667 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001668 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001669 return Err(Status::new_service_specific_error_str(
1670 IVirtualMachine::ERROR_UNEXPECTED,
1671 Some("Virtual Machine is not running"),
1672 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001673 }
Alan Stokes10c47672022-12-13 17:17:08 +00001674 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001675 if port < VSOCK_PRIV_PORT_MAX {
1676 return Err(Status::new_service_specific_error_str(
1677 IVirtualMachine::ERROR_UNEXPECTED,
1678 Some("Can't connect to privileged port {port}"),
1679 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001680 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001681 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1682 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001683 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001684 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001685 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001686
Devin Moore407df8f2024-08-27 19:39:16 +00001687 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1688 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1689 return Err(Status::new_service_specific_error_str(
1690 IVirtualMachine::ERROR_UNEXPECTED,
1691 Some("Virtual Machine is not running"),
1692 ));
1693 }
1694 let port = port as u32;
1695 if port < VSOCK_PRIV_PORT_MAX {
1696 return Err(Status::new_service_specific_error_str(
1697 IVirtualMachine::ERROR_UNEXPECTED,
1698 Some("Can't connect to privileged port {port}"),
1699 ));
1700 }
1701 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001702 let addr = sockaddr_vm {
1703 svm_family: AF_VSOCK as sa_family_t,
1704 svm_reserved1: 0,
1705 svm_port: port,
1706 svm_cid: cid,
1707 svm_zero: [0u8; 4],
1708 };
1709 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001710 let accessor = Accessor::new(name, get_connection_info);
1711 accessor
1712 .as_binder()
1713 .context("The newly created Accessor should always have a binder")
1714 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1715 }
1716
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001717 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1718 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1719 }
Jiyong Park23b67392024-07-04 13:51:42 +09001720
1721 fn suspend(&self) -> binder::Result<()> {
1722 self.instance
1723 .suspend()
1724 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1725 .with_log()
1726 .or_service_specific_exception(-1)
1727 }
1728
1729 fn resume(&self) -> binder::Result<()> {
1730 self.instance
1731 .resume()
1732 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1733 .with_log()
1734 .or_service_specific_exception(-1)
1735 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001736}
1737
1738impl Drop for VirtualMachine {
1739 fn drop(&mut self) {
1740 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001741 if let Err(e) = self.instance.kill() {
1742 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1743 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001744 }
1745}
1746
1747/// A set of Binders to be called back in response to various events on the VM, such as when it
1748/// dies.
1749#[derive(Debug, Default)]
1750pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1751
1752impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001753 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001754 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001755 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001756 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001757 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001758 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001759 }
1760 }
1761 }
1762
Inseob Kim14cb8692021-08-31 21:50:39 +09001763 /// Call all registered callbacks to notify that the payload is ready to serve.
1764 pub fn notify_payload_ready(&self, cid: Cid) {
1765 let callbacks = &*self.0.lock().unwrap();
1766 for callback in callbacks {
1767 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001768 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001769 }
1770 }
1771 }
1772
Inseob Kim2444af92021-08-31 01:22:50 +09001773 /// Call all registered callbacks to notify that the payload has finished.
1774 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1775 let callbacks = &*self.0.lock().unwrap();
1776 for callback in callbacks {
1777 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001778 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001779 }
1780 }
1781 }
1782
Jooyung Handd0a1732021-11-23 15:26:20 +09001783 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001784 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001785 let callbacks = &*self.0.lock().unwrap();
1786 for callback in callbacks {
1787 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001788 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001789 }
1790 }
1791 }
1792
Andrew Walbrandae07162021-03-12 17:05:20 +00001793 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001794 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001795 let mut callbacks = self.0.lock().unwrap();
1796 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001797 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001798 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001799 }
1800 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001801
1802 // Nothing to notify afterward because VM cannot be restarted.
1803 // Explicitly clear callbacks to prevent potential cyclic references
1804 // between callback and VmInstance.
1805 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001806 }
1807
1808 /// Add a new callback to the set.
1809 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1810 self.0.lock().unwrap().push(callback);
1811 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001812}
1813
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001814/// The mutable state of the VirtualizationService. There should only be one instance of this
1815/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001816#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001817struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001818 /// The VMs which have been started. When VMs are started a weak reference is added to this
1819 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1820 /// the Binder client are dropped the weak reference here will become invalid, and will be
1821 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001822 vms: Vec<Weak<VmInstance>>,
1823}
1824
1825impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001826 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001827 fn vms(&self) -> Vec<Arc<VmInstance>> {
1828 // Attempt to upgrade the weak pointers to strong pointers.
1829 self.vms.iter().filter_map(Weak::upgrade).collect()
1830 }
1831
1832 /// Add a new VM to the list.
1833 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1834 // Garbage collect any entries from the stored list which no longer exist.
1835 self.vms.retain(|vm| vm.strong_count() > 0);
1836
1837 // Actually add the new VM.
1838 self.vms.push(vm);
1839 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001840
Jiyong Park8611a6c2021-07-09 18:17:44 +09001841 /// Get a VM that corresponds to the given cid
1842 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1843 self.vms().into_iter().find(|vm| vm.cid == cid)
1844 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001845}
1846
Andrew Walbran6b650662021-09-07 13:13:23 +00001847/// Gets the `VirtualMachineState` of the given `VmInstance`.
1848fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001849 match &*instance.vm_state.lock().unwrap() {
1850 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1851 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001852 PayloadState::Starting => VirtualMachineState::STARTING,
1853 PayloadState::Started => VirtualMachineState::STARTED,
1854 PayloadState::Ready => VirtualMachineState::READY,
1855 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001856 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001857 },
1858 VmState::Dead => VirtualMachineState::DEAD,
1859 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001860 }
1861}
1862
David Brazdilf50c7a62023-04-19 14:22:42 +00001863/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001864pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1865 file.as_ref()
1866 .try_clone()
1867 .context("Failed to clone File from ParcelFileDescriptor")
1868 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001869 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001870}
1871
Andrew Walbrand3a84182021-09-07 14:48:52 +00001872/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001873fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001874 file.as_ref().map(clone_file).transpose()
1875}
1876
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001877/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001878fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1879 // SAFETY: ownership is transferred from stream to f
1880 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1881 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001882}
1883
Jiyong Parkdcf17412022-02-08 15:07:23 +09001884/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001885fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1886 VersionReq::parse(s)
1887 .with_context(|| format!("Invalid platform version requirement {}", s))
1888 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001889}
1890
Jiyong Parked180932023-02-24 19:55:41 +09001891/// Create the empty ramdump file
1892fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1893 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1894 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1895 // owner) for readout.
1896 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001897 let ramdump = File::create(ramdump_path)
1898 .context("Failed to prepare ramdump file")
1899 .with_log()
1900 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001901 Ok(ramdump)
1902}
1903
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001904/// Create the empty device tree dump file
1905fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1906 let path = temporary_directory.join("device_tree.dtb");
1907 let file = File::create(path)
1908 .context("Failed to prepare device tree dump file")
1909 .with_log()
1910 .or_service_specific_exception(-1)?;
1911 Ok(file)
1912}
1913
Nikita Ioffe5776f082023-02-10 21:38:26 +00001914fn is_protected(config: &VirtualMachineConfig) -> bool {
1915 match config {
1916 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1917 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1918 }
1919}
1920
1921fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1922 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001923 return Err(anyhow!("Can't use gdb with protected VMs"))
1924 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001925 }
1926
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001927 if get_debug_level(config) == Some(DebugLevel::NONE) {
1928 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1929 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001930 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001931
1932 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001933}
1934
Shikha Panwar61a74b52024-02-16 13:17:01 +00001935fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1936 match config {
1937 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1938 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1939 }
1940}
1941
Alan Stokesc96b35e2024-05-03 13:21:20 +01001942fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1943 match config {
1944 VirtualMachineConfig::RawConfig(_) => true,
1945 VirtualMachineConfig::AppConfig(config) => {
1946 let Some(custom) = &config.customConfig else { return true };
1947 custom.wantUpdatable
1948 }
1949 }
1950}
1951
Nikita Ioffe5776f082023-02-10 21:38:26 +00001952fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1953 match config {
1954 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001955 VirtualMachineConfig::AppConfig(config) => {
1956 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1957 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001958 }
1959}
1960
Nikita Ioffe631717e2023-09-05 13:38:07 +01001961fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1962 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1963 if let Some(custom_config) = &config.customConfig {
1964 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1965 return Err(anyhow!("vendor modules feature is disabled"))
1966 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1967 }
1968 }
1969 Ok(())
1970}
1971
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001972fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1973 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1974 if let Some(custom_config) = &config.customConfig {
1975 if !custom_config.devices.is_empty() {
1976 return Err(anyhow!("device assignment feature is disabled"))
1977 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1978 }
1979 }
1980 Ok(())
1981}
1982
Alan Stokesfda70842023-12-20 17:50:14 +00001983fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1984 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1985 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1986 if !payload_config.extraApks.is_empty() {
1987 return Err(anyhow!("multi-tenant feature is disabled"))
1988 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1989 }
1990 Ok(())
1991}
1992
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001993fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1994 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1995 if let Some(custom_config) = &config.customConfig {
1996 if !custom_config.extraKernelCmdlineParams.is_empty() {
1997 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1998 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1999 }
2000 }
2001 Ok(())
2002}
2003
Nikita Ioffe99548382024-10-21 15:54:46 +00002004fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
2005 match config {
2006 VirtualMachineConfig::RawConfig(config) => {
2007 if !config.teeServices.is_empty() {
2008 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2009 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2010 }
2011 }
2012 VirtualMachineConfig::AppConfig(config) => {
2013 if let Some(custom_config) = &config.customConfig {
2014 if !custom_config.teeServices.is_empty() {
2015 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2016 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2017 }
2018 }
2019 }
2020 };
2021 Ok(())
2022}
2023
Nikita Ioffef934e812024-07-05 15:44:41 +00002024fn check_protected_vm_is_supported() -> binder::Result<()> {
2025 let is_pvm_supported =
2026 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
2027 if is_pvm_supported {
2028 Ok(())
2029 } else {
2030 Err(anyhow!("pVM is not supported"))
2031 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
2032 }
2033}
2034
Nikita Ioffe631717e2023-09-05 13:38:07 +01002035fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
2036 if !cfg!(vendor_modules) {
2037 check_no_vendor_modules(config)?;
2038 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002039 if !cfg!(device_assignment) {
2040 check_no_devices(config)?;
2041 }
Alan Stokesfda70842023-12-20 17:50:14 +00002042 if !cfg!(multi_tenant) {
2043 check_no_extra_apks(config)?;
2044 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002045 if !cfg!(debuggable_vms_improvements) {
2046 check_no_extra_kernel_cmdline_params(config)?;
2047 }
Nikita Ioffe99548382024-10-21 15:54:46 +00002048 if !cfg!(tee_services_allowlist) {
2049 check_no_tee_services(config)?;
2050 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002051 Ok(())
2052}
2053
Inseob Kimecde8c02024-09-03 13:11:08 +09002054fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2055 check_no_vendor_modules(config)?;
2056 check_no_devices(config)?;
2057
2058 Ok(())
2059}
2060
Inseob Kim0168b462022-12-27 14:54:35 +09002061fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002062 fd: Option<&ParcelFileDescriptor>,
2063 tag: String,
2064) -> Result<Option<File>, Status> {
2065 if let Some(fd) = fd {
2066 return Ok(Some(clone_file(fd)?));
2067 }
2068
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002069 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002070 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002071
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002072 let mut reader = BufReader::new(File::from(read_fd));
2073 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002074
Frederick Mayle26e41af2025-02-05 18:30:29 -08002075 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002076 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002077 buf.clear();
2078 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002079 match reader.read_until(b'\n', &mut buf) {
2080 Ok(0) => {
2081 // EOF
2082 return;
2083 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002084 Ok(_size) => {
2085 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002086 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002087 // Logs sent via TTY usually end lines with "\r\n".
2088 if buf.last() == Some(&b'\r') {
2089 buf.pop();
2090 }
Inseob Kim0168b462022-12-27 14:54:35 +09002091 }
2092 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2093 }
2094 Err(e) => {
2095 error!("Could not read console pipe: {:?}", e);
2096 return;
2097 }
2098 };
2099 });
2100
2101 Ok(Some(write_fd))
2102}
2103
Jooyung Han35edb8f2021-07-01 16:17:16 +09002104/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2105/// it doesn't require that T implements Clone.
2106enum BorrowedOrOwned<'a, T> {
2107 Borrowed(&'a T),
2108 Owned(T),
2109}
2110
Chris Wailes73a1eb72025-01-15 11:56:43 -08002111impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002112 fn as_ref(&self) -> &T {
2113 match self {
2114 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002115 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002116 }
2117 }
2118}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002119
2120/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2121#[derive(Debug, Default)]
2122struct VirtualMachineService {
2123 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002124 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002125}
2126
2127impl Interface for VirtualMachineService {}
2128
2129impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002130 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2131 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002132 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002133 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002134 vm.update_payload_state(PayloadState::Started)
2135 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002136 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002137
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002138 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2139 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002140 Ok(())
2141 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002142 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002143 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002144 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002145 }
Inseob Kim2444af92021-08-31 01:22:50 +09002146
Inseob Kimc7d28c72021-10-25 14:28:10 +00002147 fn notifyPayloadReady(&self) -> binder::Result<()> {
2148 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002149 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002150 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002151 vm.update_payload_state(PayloadState::Ready)
2152 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002153 vm.callbacks.notify_payload_ready(cid);
2154 Ok(())
2155 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002156 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002157 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002158 }
2159 }
2160
Inseob Kimc7d28c72021-10-25 14:28:10 +00002161 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2162 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002163 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002164 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002165 vm.update_payload_state(PayloadState::Finished)
2166 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002167 vm.callbacks.notify_payload_finished(cid, exit_code);
2168 Ok(())
2169 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002170 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002171 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002172 }
2173 }
2174
Alan Stokes2bead0d2022-09-05 16:58:34 +01002175 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002176 let cid = self.cid;
2177 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002178 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002179 vm.update_payload_state(PayloadState::Finished)
2180 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002181 vm.callbacks.notify_error(cid, error_code, message);
2182 Ok(())
2183 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002184 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002185 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002186 }
2187 }
Alice Wangc2fec932023-02-23 16:24:02 +00002188
Shikha Panware45e9422024-02-28 21:18:10 +00002189 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2190 if !is_secretkeeper_supported() {
2191 return Err(StatusCode::NAME_NOT_FOUND)?;
2192 }
2193 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2194 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002195 }
2196
Alice Wange64dd182024-01-17 15:57:55 +00002197 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2198 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002199 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002200}
2201
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002202fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002203 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2204 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002205}
2206
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002207impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002208 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002209 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002210 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002211 BinderFeatures::default(),
2212 )
2213 }
2214}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002215
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002216struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2217
2218impl Interface for SecretkeeperProxy {}
2219
2220impl ISecretkeeper for SecretkeeperProxy {
2221 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2222 // Pass the request to the channel, and read the response.
2223 self.0.processSecretManagementRequest(req)
2224 }
2225
2226 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2227 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2228 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2229 }
2230
2231 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2232 self.0.deleteIds(ids)
2233 }
2234
2235 fn deleteAll(&self) -> binder::Result<()> {
2236 self.0.deleteAll()
2237 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002238
2239 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2240 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2241 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2242 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2243 // use this API from the proxy.
2244 Err(ExceptionCode::SECURITY.into())
2245 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002246}
2247
2248struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2249
2250impl Interface for AuthGraphKeyExchangeProxy {}
2251
2252impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2253 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2254 self.0.create()
2255 }
2256
2257 fn init(
2258 &self,
2259 peer_pub_key: &PubKey,
2260 peer_id: &Identity,
2261 peer_nonce: &[u8],
2262 peer_version: i32,
2263 ) -> binder::Result<KeInitResult> {
2264 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2265 }
2266
2267 fn finish(
2268 &self,
2269 peer_pub_key: &PubKey,
2270 peer_id: &Identity,
2271 peer_signature: &SessionIdSignature,
2272 peer_nonce: &[u8],
2273 peer_version: i32,
2274 own_key: &Key,
2275 ) -> binder::Result<SessionInfo> {
2276 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2277 }
2278
2279 fn authenticationComplete(
2280 &self,
2281 peer_signature: &SessionIdSignature,
2282 shared_keys: &[AuthgraphArc; 2],
2283 ) -> binder::Result<[AuthgraphArc; 2]> {
2284 self.0.authenticationComplete(peer_signature, shared_keys)
2285 }
2286}
2287
Inseob Kimecde8c02024-09-03 13:11:08 +09002288// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002289#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002290struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002291 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002292 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002293 path: String,
2294}
2295
2296#[derive(Debug, Default, Deserialize)]
2297struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002298 early_vm: Vec<EarlyVm>,
2299}
2300
Frederick Mayle3a46b272025-02-10 21:55:49 -08002301static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> =
Inseob Kim7e1877b2024-11-07 17:28:56 +09002302 LazyLock::new(|| Mutex::new(HashMap::new()));
2303
Frederick Mayle3a46b272025-02-10 21:55:49 -08002304fn range_for_partition(partition: CallingPartition) -> Range<Cid> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002305 match partition {
Frederick Mayle3a46b272025-02-10 21:55:49 -08002306 CallingPartition::System => 100..200,
2307 CallingPartition::SystemExt | CallingPartition::Product => 200..300,
2308 CallingPartition::Vendor | CallingPartition::Odm => 300..400,
2309 CallingPartition::Unknown => 0..0,
Inseob Kimecde8c02024-09-03 13:11:08 +09002310 }
2311}
2312
Inseob Kim7e1877b2024-11-07 17:28:56 +09002313fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002314 if !xml_path.exists() {
2315 bail!("{} doesn't exist", xml_path.display());
2316 }
2317
2318 let xml =
2319 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2320 let xml = String::from_utf8(xml)
2321 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2322 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2323 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2324
Inseob Kim7e1877b2024-11-07 17:28:56 +09002325 Ok(early_vms.early_vm)
2326}
Inseob Kimecde8c02024-09-03 13:11:08 +09002327
Inseob Kim7e1877b2024-11-07 17:28:56 +09002328fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2329 for early_vm in early_vms {
2330 let cid = early_vm
2331 .cid
2332 .try_into()
2333 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2334
2335 ensure!(
2336 cid_range.contains(&cid),
2337 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2338 early_vm.name
2339 );
2340 }
2341 Ok(())
2342}
2343
Frederick Mayle3a46b272025-02-10 21:55:49 -08002344fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002345 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2346
Frederick Mayle3a46b272025-02-10 21:55:49 -08002347 if let Some(result) = cache.get(&partition) {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002348 return Ok(result.clone());
2349 }
2350
2351 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2352 let mut early_vms = Vec::new();
2353 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2354 match entry {
2355 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2356 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2357 }
2358 }
2359
Frederick Mayle3a46b272025-02-10 21:55:49 -08002360 validate_cid_range(&early_vms, &range_for_partition(partition))
Inseob Kim7e1877b2024-11-07 17:28:56 +09002361 .with_context(|| format!("CID validation for {partition} failed"))?;
2362
Frederick Mayle3a46b272025-02-10 21:55:49 -08002363 cache.insert(partition, early_vms.clone());
Inseob Kim7e1877b2024-11-07 17:28:56 +09002364
2365 Ok(early_vms)
2366}
2367
2368fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2369 let mut found_vm: Option<&EarlyVm> = None;
2370
2371 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002372 if early_vm.name != name {
2373 continue;
2374 }
2375
Inseob Kimecde8c02024-09-03 13:11:08 +09002376 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002377 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002378 }
2379
2380 found_vm = Some(early_vm);
2381 }
2382
Inseob Kim7e1877b2024-11-07 17:28:56 +09002383 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002384}
2385
Frederick Mayle3a46b272025-02-10 21:55:49 -08002386fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002387 let early_vms = get_early_vms_in_partition(partition)
2388 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2389
2390 Ok(find_early_vm(&early_vms, name)
2391 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2392 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002393}
2394
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002395#[cfg(test)]
2396mod tests {
2397 use super::*;
2398
2399 #[test]
2400 fn test_is_allowed_label_for_partition() -> Result<()> {
2401 let expected_results = vec![
2402 ("u:object_r:system_file:s0", true),
2403 ("u:object_r:apk_data_file:s0", true),
2404 ("u:object_r:app_data_file:s0", false),
2405 ("u:object_r:app_data_file:s0:c512,c768", false),
2406 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2407 ("invalid", false),
2408 ("user:role:apk_data_file:severity:categories", true),
2409 ("user:role:apk_data_file:severity:categories:extraneous", false),
2410 ];
2411
2412 for (label, expected_valid) in expected_results {
2413 let context = SeContext::new(label)?;
2414 let result = check_label_is_allowed(&context);
2415 if expected_valid {
2416 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2417 } else if result.is_ok() {
2418 bail!("Expected label {} to be disallowed", label);
2419 }
2420 }
2421 Ok(())
2422 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002423
2424 #[test]
2425 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2426 let apk = tempfile::tempfile().unwrap();
2427 let idsig = tempfile::tempfile().unwrap();
2428
2429 let ret = create_or_update_idsig_file(
2430 &ParcelFileDescriptor::new(apk),
2431 &ParcelFileDescriptor::new(idsig),
2432 );
2433 assert!(ret.is_err(), "should fail");
2434 Ok(())
2435 }
2436
2437 #[test]
2438 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2439 let tmp_dir = tempfile::TempDir::new().unwrap();
2440 let apk = File::open(tmp_dir.path()).unwrap();
2441 let idsig = tempfile::tempfile().unwrap();
2442
2443 let ret = create_or_update_idsig_file(
2444 &ParcelFileDescriptor::new(apk),
2445 &ParcelFileDescriptor::new(idsig),
2446 );
2447 assert!(ret.is_err(), "should fail");
2448 Ok(())
2449 }
2450
2451 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2452 /// on ext4 filesystem is passed.
2453 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2454 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2455 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2456 #[test]
2457 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2458 // APEXes are backed by the ext4.
2459 let apk = File::open("/apex/com.android.virt/").unwrap();
2460 let idsig = tempfile::tempfile().unwrap();
2461
2462 let ret = create_or_update_idsig_file(
2463 &ParcelFileDescriptor::new(apk),
2464 &ParcelFileDescriptor::new(idsig),
2465 );
2466 assert!(ret.is_err(), "should fail");
2467 Ok(())
2468 }
Jiyong Park8d192952023-06-26 14:29:51 +09002469
2470 #[test]
2471 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2472 use std::io::Seek;
2473
2474 // Pick any APK
2475 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2476 let mut idsig = tempfile::tempfile().unwrap();
2477
2478 create_or_update_idsig_file(
2479 &ParcelFileDescriptor::new(apk.try_clone()?),
2480 &ParcelFileDescriptor::new(idsig.try_clone()?),
2481 )?;
2482 let modified_orig = idsig.metadata()?.modified()?;
2483 apk.rewind()?;
2484 idsig.rewind()?;
2485
2486 // Call the function again
2487 create_or_update_idsig_file(
2488 &ParcelFileDescriptor::new(apk.try_clone()?),
2489 &ParcelFileDescriptor::new(idsig.try_clone()?),
2490 )?;
2491 let modified_new = idsig.metadata()?.modified()?;
2492 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2493 Ok(())
2494 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002495
2496 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002497 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2498 use std::io::Read;
2499
2500 // Pick any APK
2501 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2502 let idsig_empty = tempfile::tempfile().unwrap();
2503 let mut idsig_invalid = tempfile::tempfile().unwrap();
2504 idsig_invalid.write_all(b"Oops")?;
2505
2506 // Create new idsig
2507 create_or_update_idsig_file(
2508 &ParcelFileDescriptor::new(apk.try_clone()?),
2509 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2510 )?;
2511 apk.rewind()?;
2512
2513 // Update idsig_invalid
2514 create_or_update_idsig_file(
2515 &ParcelFileDescriptor::new(apk.try_clone()?),
2516 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2517 )?;
2518
2519 // Ensure the 2 idsig files have same size!
2520 assert!(
2521 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2522 "idsig files differ in size"
2523 );
2524 // Ensure the 2 idsig files have same content!
2525 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2526 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2527 }
2528 Ok(())
2529 }
2530 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002531 fn test_append_kernel_param_first_param() {
2532 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2533 append_kernel_param("foo=1", &mut vm_config);
2534 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2535 }
2536
2537 #[test]
2538 fn test_append_kernel_param() {
2539 let mut vm_config =
2540 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2541 append_kernel_param("bar=42", &mut vm_config);
2542 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2543 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002544
Inseob Kim46257382024-01-03 15:41:22 +09002545 fn test_extract_os_name_from_config_path(
2546 path: &Path,
2547 expected_result: Option<&str>,
2548 ) -> Result<()> {
2549 let result = extract_os_name_from_config_path(path);
2550 if result.as_deref() != expected_result {
2551 bail!("Expected {:?} but was {:?}", expected_result, &result)
2552 }
2553 Ok(())
2554 }
2555
2556 #[test]
2557 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2558 test_extract_os_name_from_config_path(
2559 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2560 Some("microdroid"),
2561 )
2562 }
2563
2564 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002565 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2566 test_extract_os_name_from_config_path(
2567 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2568 Some("microdroid_16k"),
2569 )
2570 }
2571
2572 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002573 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2574 test_extract_os_name_from_config_path(
2575 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2576 Some("microdroid_gki-android14-6.1"),
2577 )
2578 }
2579
2580 #[test]
2581 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2582 test_extract_os_name_from_config_path(
2583 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2584 None,
2585 )
2586 }
2587
2588 #[test]
2589 fn test_extract_os_name_from_configs() -> Result<()> {
2590 let tmp_dir = tempfile::TempDir::new()?;
2591 let tmp_dir_path = tmp_dir.path().to_owned();
2592
2593 let mut os_names: HashSet<String> = HashSet::new();
2594 os_names.insert("microdroid".to_owned());
2595 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2596 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2597
2598 // config files
2599 for os_name in &os_names {
2600 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2601 }
2602
2603 // fake files not related to configs
2604 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2605 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2606
2607 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2608 Some(s) => s.to_owned(),
2609 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2610 };
2611
2612 let result = extract_os_names_from_configs(&glob_pattern)?;
2613 if result != os_names {
2614 bail!("Expected {:?} but was {:?}", os_names, result);
2615 }
2616 Ok(())
2617 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002618
2619 #[test]
2620 fn test_find_early_vms_from_xml() -> Result<()> {
2621 let tmp_dir = tempfile::TempDir::new()?;
2622 let tmp_dir_path = tmp_dir.path().to_owned();
2623 let xml_path = tmp_dir_path.join("early_vms.xml");
2624
2625 std::fs::write(
2626 &xml_path,
2627 br#"<?xml version="1.0" encoding="utf-8"?>
2628 <early_vms>
2629 <early_vm>
2630 <name>vm_demo_native_early</name>
2631 <cid>123</cid>
2632 <path>/system/bin/vm_demo_native_early</path>
2633 </early_vm>
2634 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002635 <name>vm_demo_native_early_2</name>
2636 <cid>456</cid>
2637 <path>/system/bin/vm_demo_native_early_2</path>
2638 </early_vm>
2639 </early_vms>
2640 "#,
2641 )?;
2642
2643 let cid_range = 100..1000;
2644
2645 let early_vms = get_early_vms_in_path(&xml_path)?;
2646 validate_cid_range(&early_vms, &cid_range)?;
2647
2648 let test_cases = [
2649 (
2650 "vm_demo_native_early",
2651 EarlyVm {
2652 name: "vm_demo_native_early".to_owned(),
2653 cid: 123,
2654 path: "/system/bin/vm_demo_native_early".to_owned(),
2655 },
2656 ),
2657 (
2658 "vm_demo_native_early_2",
2659 EarlyVm {
2660 name: "vm_demo_native_early_2".to_owned(),
2661 cid: 456,
2662 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2663 },
2664 ),
2665 ];
2666
2667 for (name, expected) in test_cases {
2668 let result = find_early_vm(&early_vms, name)?;
2669 assert_eq!(result, &expected);
2670 }
2671
2672 Ok(())
2673 }
2674
2675 #[test]
2676 fn test_invalid_cid_validation() -> Result<()> {
2677 let tmp_dir = tempfile::TempDir::new()?;
2678 let xml_path = tmp_dir.path().join("early_vms.xml");
2679
2680 let cid_range = 100..1000;
2681
2682 for cid in [-1, 999999] {
2683 std::fs::write(
2684 &xml_path,
2685 format!(
2686 r#"<?xml version="1.0" encoding="utf-8"?>
2687 <early_vms>
2688 <early_vm>
2689 <name>vm_demo_invalid_cid</name>
2690 <cid>{cid}</cid>
2691 <path>/system/bin/vm_demo_invalid_cid</path>
2692 </early_vm>
2693 </early_vms>
2694 "#
2695 ),
2696 )?;
2697
2698 let early_vms = get_early_vms_in_path(&xml_path)?;
2699 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2700 }
2701
2702 Ok(())
2703 }
2704
2705 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002706 fn test_symlink_to_system_ext_supported() -> Result<()> {
2707 let link_path = Path::new("/system/system_ext/file");
2708 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002709 assert_eq!(CallingPartition::SystemExt, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002710 Ok(())
2711 }
2712
2713 #[test]
2714 fn test_symlink_to_product_supported() -> Result<()> {
2715 let link_path = Path::new("/system/product/file");
2716 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002717 assert_eq!(CallingPartition::Product, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002718 Ok(())
2719 }
2720
2721 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002722 fn test_duplicated_early_vms() -> Result<()> {
2723 let tmp_dir = tempfile::TempDir::new()?;
2724 let tmp_dir_path = tmp_dir.path().to_owned();
2725 let xml_path = tmp_dir_path.join("early_vms.xml");
2726
2727 std::fs::write(
2728 &xml_path,
2729 br#"<?xml version="1.0" encoding="utf-8"?>
2730 <early_vms>
2731 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002732 <name>vm_demo_duplicated_name</name>
2733 <cid>456</cid>
2734 <path>/system/bin/vm_demo_duplicated_name_1</path>
2735 </early_vm>
2736 <early_vm>
2737 <name>vm_demo_duplicated_name</name>
2738 <cid>789</cid>
2739 <path>/system/bin/vm_demo_duplicated_name_2</path>
2740 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002741 </early_vms>
2742 "#,
2743 )?;
2744
2745 let cid_range = 100..1000;
2746
Inseob Kim7e1877b2024-11-07 17:28:56 +09002747 let early_vms = get_early_vms_in_path(&xml_path)?;
2748 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002749
Inseob Kim7e1877b2024-11-07 17:28:56 +09002750 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002751
2752 Ok(())
2753 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002754}