blob: 4e17daa488eba19cf35719cc2fd4968dd41fe064 [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
Inseob Kime3e932d2024-12-16 20:06:57 +0900423fn find_partition(path: Option<&Path>) -> binder::Result<String> {
Frederick Maylecc9862f2025-02-10 20:42:59 -0800424 let Some(path) = path else {
425 return Ok("system".to_owned());
Inseob Kime3e932d2024-12-16 20:06:57 +0900426 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000427 if path.starts_with("/system/system_ext/") {
428 return Ok("system_ext".to_owned());
429 } else if path.starts_with("/system/product/") {
430 return Ok("product".to_owned());
431 }
Inseob Kimf79c5722024-12-16 17:29:57 +0900432 let mut components = path.components();
Frederick Maylecc9862f2025-02-10 20:42:59 -0800433 let Some(std::path::Component::Normal(partition)) = components.nth(1) else {
434 return Err(anyhow!("Can't find partition in '{}'", path.display()))
435 .or_service_specific_exception(-1);
436 };
Inseob Kimf79c5722024-12-16 17:29:57 +0900437
Frederick Maylecc9862f2025-02-10 20:42:59 -0800438 // If path is under /apex, find a partition of the preinstalled .apex path
439 if partition == "apex" {
440 let Some(std::path::Component::Normal(apex_name)) = components.next() else {
441 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
442 .or_service_specific_exception(-1);
443 };
444 let apex_info_list = ApexInfoList::load()
445 .context("Failed to get apex info list")
446 .or_service_specific_exception(-1)?;
447 return apex_info_list
448 .list
449 .iter()
450 .find(|apex_info| apex_info.name.as_str() == apex_name)
451 .map(|apex_info| apex_info.partition.to_lowercase())
452 .ok_or(anyhow!("Can't find apex info for {apex_name:?}"))
453 .or_service_specific_exception(-1);
Inseob Kimecde8c02024-09-03 13:11:08 +0900454 }
Frederick Maylecc9862f2025-02-10 20:42:59 -0800455
456 Ok(partition.to_string_lossy().into_owned())
Inseob Kimecde8c02024-09-03 13:11:08 +0900457}
458
Jiyong Park8611a6c2021-07-09 18:17:44 +0900459impl VirtualizationService {
460 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000461 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900462 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000463
Inseob Kimecde8c02024-09-03 13:11:08 +0900464 fn create_early_vm_context(
465 &self,
466 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900467 calling_exe_path: Option<&Path>,
Inseob Kimecde8c02024-09-03 13:11:08 +0900468 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900469 let name = match config {
470 VirtualMachineConfig::RawConfig(config) => &config.name,
471 VirtualMachineConfig::AppConfig(config) => &config.name,
472 };
Inseob Kime3e932d2024-12-16 20:06:57 +0900473 let calling_partition = find_partition(calling_exe_path)?;
474 let early_vm = find_early_vm_for_partition(&calling_partition, name)
475 .or_service_specific_exception(-1)?;
476 let calling_exe_path = match calling_exe_path {
477 Some(path) => path,
478 None => {
479 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
480 .or_service_specific_exception(-1)
481 }
482 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000483 let expected_exe_path = Path::new(&early_vm.path);
484 if expected_exe_path != calling_exe_path
485 && Path::new("/system").join(expected_exe_path) != calling_exe_path
486 {
Inseob Kimecde8c02024-09-03 13:11:08 +0900487 return Err(anyhow!(
Inseob Kime3e932d2024-12-16 20:06:57 +0900488 "VM '{name}' in partition '{calling_partition}' must be created with '{}', not '{}'",
Inseob Kimecde8c02024-09-03 13:11:08 +0900489 &early_vm.path,
Inseob Kime3e932d2024-12-16 20:06:57 +0900490 calling_exe_path.display()
Inseob Kimecde8c02024-09-03 13:11:08 +0900491 ))
492 .or_service_specific_exception(-1);
493 }
494
495 let cid = early_vm.cid as Cid;
496 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
497
498 let context = EarlyVmContext::new(cid, temp_dir.clone())
499 .context(format!("Can't create early vm contexts for {cid}"))
500 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900501
Jiyong Park690c1ca2024-11-28 18:06:50 +0900502 if requires_vm_service(config) {
503 // Start VM service listening for connections from the new CID on port=CID.
504 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
505 let port = cid;
506 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
507 .context(format!("Could not start RpcServer on port {port}"))
508 .or_service_specific_exception(-1)?;
509 vm_server.start();
510 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
511 } else {
512 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
513 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900514 }
515
David Brazdil209074a2023-01-12 16:44:51 +0000516 fn create_vm_context(
517 &self,
518 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900519 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000520 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000521 const NUM_ATTEMPTS: usize = 5;
522
523 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000524 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000525 let cid = vm_context.getCid()? as Cid;
526 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900527
528 // We don't need to start the VM service for custom VMs.
529 if !requires_vm_service(config) {
530 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
531 }
532
David Brazdil8cf8f482022-11-23 14:21:26 +0000533 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
534
535 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000536 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000537 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000538 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000539 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900540 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000541 }
542 Err(err) => {
543 warn!("Could not start RpcServer on port {}: {}", port, err);
544 }
545 }
546 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900547 Err(anyhow!("Too many attempts to create VM context failed"))
548 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000549 }
550
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000551 fn create_vm_internal(
552 &self,
553 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900554 console_out_fd: Option<&ParcelFileDescriptor>,
555 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000556 log_fd: Option<&ParcelFileDescriptor>,
557 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000558 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000559 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000560 let requester_uid = get_calling_uid();
561 let requester_debug_pid = get_calling_pid();
562
Nikita Ioffe631717e2023-09-05 13:38:07 +0100563 check_config_features(config)?;
564
Inseob Kimecde8c02024-09-03 13:11:08 +0900565 if cfg!(early) {
566 check_config_allowed_for_early_vms(config)?;
567 }
568
Nikita Ioffeb1416122024-10-22 12:18:49 +0000569 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
570 info!("callers secontext: {}", caller_secontext);
571
David Brazdil209074a2023-01-12 16:44:51 +0000572 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900573 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Inseob Kime3e932d2024-12-16 20:06:57 +0900574 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref())?
Inseob Kimecde8c02024-09-03 13:11:08 +0900575 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900576 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900577 };
Inseob Kim1119d702022-05-02 18:01:58 +0900578
Alan Stokesfda70842023-12-20 17:50:14 +0000579 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100580 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900581 }
582
Nikita Ioffe5776f082023-02-10 21:38:26 +0000583 let gdb_port = extract_gdb_port(config);
584
585 // Additional permission checks if caller request gdb.
586 if gdb_port.is_some() {
587 check_gdb_allowed(config)?;
588 }
589
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800590 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900591 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800592 if let Some(dt_overlay) =
593 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
594 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900595 device_tree_overlays.push(dt_overlay);
596 }
597 if let Some(dtbo) = get_dtbo(config) {
598 let dtbo = File::from(
599 dtbo.as_ref()
600 .try_clone()
601 .context("Failed to create VM DTBO from ParcelFileDescriptor")
602 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
603 );
604 device_tree_overlays.push(dtbo);
605 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900606
Jaewan Kimf3143242024-03-15 06:56:31 +0000607 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000608 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900609 Some(prepare_ramdump_file(&temporary_directory)?)
610 } else {
611 None
612 };
613
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000614 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900615 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100616 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900617 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100618 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100619 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
620 Some(clone_file(fd)?)
621 } else if debug_config.dump_device_tree {
622 Some(prepare_dump_dt_file(&temporary_directory)?)
623 } else {
624 None
625 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000626
627 // Counter to generate unique IDs for temporary image files.
628 let mut next_temporary_image_id = 0;
629 // Files which are referred to from composite images. These must be mapped to the crosvm
630 // child process, and not closed before it is started.
631 let mut indirect_files = vec![];
632
Alan Stokes7bc146c2022-10-20 17:10:32 +0100633 let (is_app_config, config) = match config {
634 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
635 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900636 let config = load_app_config(config, &debug_config, &temporary_directory)
637 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900638 *is_protected = config.protectedVm;
639 let message = format!("Failed to load app config: {:?}", e);
640 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900641 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900642 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100643 (true, BorrowedOrOwned::Owned(config))
644 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000645 };
646 let config = config.as_ref();
647 *is_protected = config.protectedVm;
648
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000649 if !config.teeServices.is_empty() {
650 check_tee_service_permission(&caller_secontext, &config.teeServices)
651 .with_log()
652 .or_binder_exception(ExceptionCode::SECURITY)?;
653 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000654
Jiyong Park3051ffe2024-11-26 14:41:58 +0900655 let kernel = maybe_clone_file(&config.kernel)?;
656 let initrd = maybe_clone_file(&config.initrd)?;
657
658 if config.protectedVm {
659 // Fail fast with a meaningful error message in case device doesn't support pVMs.
660 check_protected_vm_is_supported()?;
661
662 // In a protected VM, we require custom kernels to come from a trusted source
663 // (b/237054515).
664 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
665
666 // Check if partition images are labeled incorrectly. This is to prevent random images
667 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
668 // from being loaded in a pVM. This applies to everything but the instance image in the
669 // raw config, and everything but the non-executable, generated partitions in the app
670 // config.
671 config
672 .disks
673 .iter()
674 .flat_map(|disk| disk.partitions.iter())
675 .filter(|partition| {
676 if is_app_config {
677 !is_safe_app_partition(&partition.label)
678 } else {
679 !is_safe_raw_partition(&partition.label)
680 }
681 })
682 .try_for_each(check_label_for_partition)
683 .or_service_specific_exception(-1)?;
684 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000685
Inseob Kimff48a7c2024-02-26 22:07:21 +0900686 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
687 // have unstable interfaces.
688 // TODO(b/316431494): remove once Treble interfaces are stabilized.
Inseob Kime3e932d2024-12-16 20:06:57 +0900689 check_partitions_for_files(config, &find_partition(CALLING_EXE_PATH.as_deref())?)
690 .or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900691
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000692 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900693 write_zero_filler(&zero_filler_path)
694 .context("Failed to make composite image")
695 .with_log()
696 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000697
698 // Assemble disk images if needed.
699 let disks = config
700 .disks
701 .iter()
702 .map(|disk| {
703 assemble_disk_image(
704 disk,
705 &zero_filler_path,
706 &temporary_directory,
707 &mut next_temporary_image_id,
708 &mut indirect_files,
709 )
710 })
711 .collect::<Result<Vec<DiskFile>, _>>()?;
712
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700713 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
714
Jaewan Kimf43372b2024-12-13 18:33:58 +0900715 let (vfio_devices, dtbo) = match &config.devices {
716 AssignedDevices::Devices(devices) if !devices.is_empty() => {
717 let mut set = HashSet::new();
718 for device in devices.iter() {
719 let path = canonicalize(device)
720 .with_context(|| format!("can't canonicalize {device}"))
721 .or_service_specific_exception(-1)?;
722 if !set.insert(path) {
723 return Err(anyhow!("duplicated device {device}"))
724 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
725 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900726 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900727 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
728 let dtbo_file = File::from(
729 GLOBAL_SERVICE
730 .getDtboFile()?
731 .as_ref()
732 .try_clone()
733 .context("Failed to create VM DTBO from ParcelFileDescriptor")
734 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
735 );
736 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900737 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900738 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900739 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900740 let display_config = if cfg!(paravirtualized_devices) {
741 config
742 .displayConfig
743 .as_ref()
744 .map(DisplayConfig::new)
745 .transpose()
746 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
747 } else {
748 None
749 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700750 let gpu_config = if cfg!(paravirtualized_devices) {
751 config
752 .gpuConfig
753 .as_ref()
754 .map(GpuConfig::new)
755 .transpose()
756 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
757 } else {
758 None
759 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900760
Jeongik Chac181be72024-03-27 00:18:30 +0900761 let input_device_options = if cfg!(paravirtualized_devices) {
762 config
763 .inputDevices
764 .iter()
765 .map(to_input_device_option_from)
766 .collect::<Result<Vec<InputDeviceOption>, _>>()
767 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
768 } else {
769 vec![]
770 };
771
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900772 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900773 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900774 if *is_protected {
775 return Err(anyhow!("Network feature is not supported for pVM yet"))
776 .with_log()
777 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
778 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900779 Some(File::from(
780 GLOBAL_SERVICE
781 .createTapInterface(&get_this_pid().to_string())?
782 .as_ref()
783 .try_clone()
784 .context("Failed to get TAP interface from ParcelFileDescriptor")
785 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
786 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900787 } else {
788 None
789 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800790
791 let audio_config = if cfg!(paravirtualized_devices) {
792 config.audioConfig.as_ref().map(AudioConfig::new)
793 } else {
794 None
795 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900796
Elie Kheirallah29d72912024-08-07 20:17:26 +0000797 let usb_config = config
798 .usbConfig
799 .as_ref()
800 .map(UsbConfig::new)
801 .unwrap_or(Ok(UsbConfig { controller: false }))
802 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
803
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000804 let detect_hangup = is_app_config && gdb_port.is_none();
805
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800806 let custom_memory_backing_files = config
807 .customMemoryBackingFiles
808 .iter()
809 .map(|memory_backing_file| {
810 Ok((
811 clone_file(
812 memory_backing_file
813 .file
814 .as_ref()
815 .context("missing CustomMemoryBackingFile FD")
816 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
817 )?
818 .into(),
819 memory_backing_file.rangeStart as u64,
820 memory_backing_file.size as u64,
821 ))
822 })
823 .collect::<binder::Result<_>>()?;
824
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000825 // Actually start the VM.
826 let crosvm_config = CrosvmConfig {
827 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000828 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000829 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000830 kernel,
831 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000832 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700833 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000834 params: config.params.to_owned(),
835 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900836 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700837 memory_mib: config
838 .memoryMib
839 .try_into()
840 .ok()
841 .and_then(NonZeroU32::new)
842 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800843 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000844 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900845 console_out_fd,
846 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000847 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900848 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000849 indirect_files,
850 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000851 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000852 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900853 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000854 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900855 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900856 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900857 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000858 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900859 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800860 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000861 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700862 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800863 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800864 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000865 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000866 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800867 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
868 instance_id,
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800869 custom_memory_backing_files,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000870 };
871 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100872 VmInstance::new(
873 crosvm_config,
874 temporary_directory,
875 requester_uid,
876 requester_debug_pid,
877 vm_context,
878 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900879 .with_context(|| format!("Failed to create VM with config {:?}", config))
880 .with_log()
881 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000882 );
883 state.add_vm(Arc::downgrade(&instance));
884 Ok(VirtualMachine::create(instance))
885 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900886}
887
Alan Stokesfda70842023-12-20 17:50:14 +0000888/// Returns whether a VM config represents a "custom" virtual machine, which requires the
889/// USE_CUSTOM_VIRTUAL_MACHINE.
890fn is_custom_config(config: &VirtualMachineConfig) -> bool {
891 match config {
892 // Any raw (non-Microdroid) VM is considered custom.
893 VirtualMachineConfig::RawConfig(_) => true,
894 VirtualMachineConfig::AppConfig(config) => {
895 // Some features are reserved for platform apps only, even when using
896 // VirtualMachineAppConfig. Almost all of these features are grouped in the
897 // CustomConfig struct:
898 // - controlling CPUs;
899 // - gdbPort is set, meaning that crosvm will start a gdb server;
900 // - using anything other than the default kernel;
901 // - specifying devices to be assigned.
902 if config.customConfig.is_some() {
903 true
904 } else {
905 // Additional custom features not included in CustomConfig:
906 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000907 // - specifying extra APKs;
908 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900909 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000910 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900911 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
912 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000913 }
914 }
915 }
916}
917
Jiyong Park690c1ca2024-11-28 18:06:50 +0900918/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
919/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
920/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
921/// "microdroid" we run VirtualMachineService
922fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
923 match config {
924 VirtualMachineConfig::AppConfig(_) => true,
925 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
926 }
927}
928
Seungjae Yoo14e60182024-02-21 13:28:31 +0900929fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
930 let VirtualMachineConfig::AppConfig(config) = config else {
931 return Ok(None);
932 };
933 let Some(custom_config) = &config.customConfig else {
934 return Ok(None);
935 };
936 let Some(file) = custom_config.vendorImage.as_ref() else {
937 return Ok(None);
938 };
939
940 let file = clone_file(file)?;
941 let size =
942 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
943 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
944 .context("Failed to get vbmeta from microdroid-vendor.img")?;
945
946 for descriptor in vbmeta.descriptors()?.iter() {
947 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
948 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
949 return Ok(Some(root_digest.as_bytes().to_vec()));
950 }
951 }
952 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
953}
954
Jaewan Kimf43372b2024-12-13 18:33:58 +0900955fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000956 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800957 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000958 temporary_directory: &Path,
959) -> binder::Result<Option<File>> {
960 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
961 // (e.g. instance-id)
962 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
963 let host_ref_dt = if host_ref_dt.exists()
964 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
965 {
966 Some(host_ref_dt)
967 } else {
968 warn!("VM reference DT doesn't exist in host DT");
969 None
970 };
971
972 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
973 .context("Failed to extract vendor hashtree digest")
974 .or_service_specific_exception(-1)?;
975
Matt Gilbrideaade4272024-12-05 13:52:42 +0000976 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000977 info!(
978 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
979 match the trusted digest in the pvmfw config, causing the VM to fail to start."
980 );
Alan Stokesf46a17c2025-01-05 15:50:18 +0000981 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000982 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +0000983 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000984 };
985
Matt Gilbrideaade4272024-12-05 13:52:42 +0000986 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000987 let mut untrusted_props = Vec::with_capacity(2);
988 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000989 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000990 let want_updatable = extract_want_updatable(config);
991 if want_updatable && is_secretkeeper_supported() {
992 // Let guest know that it can defer rollback protection to Secretkeeper by setting
993 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000994 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +0000995 let sk: Strong<dyn ISecretkeeper> =
996 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
997 if sk.getInterfaceVersion()? >= 2 {
998 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
999 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001000 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001001 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001002 }
1003 }
1004
1005 let device_tree_overlay = if host_ref_dt.is_some()
1006 || !untrusted_props.is_empty()
1007 || !trusted_props.is_empty()
1008 {
1009 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1010 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1011 let fdt =
1012 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1013 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1014 .or_service_specific_exception(-1)?;
1015 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1016 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1017 } else {
1018 None
1019 };
1020 Ok(device_tree_overlay)
1021}
1022
Jaewan Kimf43372b2024-12-13 18:33:58 +09001023fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1024 let VirtualMachineConfig::RawConfig(config) = config else {
1025 return None;
1026 };
1027 match &config.devices {
1028 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1029 _ => None,
1030 }
1031}
1032
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001033fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001034 let file = OpenOptions::new()
1035 .create_new(true)
1036 .read(true)
1037 .write(true)
1038 .open(zero_filler_path)
1039 .with_context(|| "Failed to create zero.img")?;
1040 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001041 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001042}
1043
David Brazdilf50c7a62023-04-19 14:22:42 +00001044fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1045 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1046 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1047 part.flush()
1048}
1049
1050fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1051 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1052 part.flush()
1053}
1054
1055fn round_up(input: u64, granularity: u64) -> u64 {
1056 if granularity == 0 {
1057 return input;
1058 }
1059 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1060 let result = input.checked_add(granularity - 1).unwrap_or(input);
1061 (result / granularity) * granularity
1062}
1063
Jeongik Chac181be72024-03-27 00:18:30 +09001064fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1065 Ok(match input_device {
1066 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1067 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1068 height: u32::try_from(single_touch.height)?,
1069 width: u32::try_from(single_touch.width)?,
1070 name: if !single_touch.name.is_empty() {
1071 Some(single_touch.name.clone())
1072 } else {
1073 None
1074 },
1075 },
1076 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1077 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1078 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001079 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1080 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1081 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001082 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1083 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1084 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001085 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1086 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1087 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001088 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1089 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1090 height: u32::try_from(trackpad.height)?,
1091 width: u32::try_from(trackpad.width)?,
1092 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1093 },
Jeongik Cha10494912024-07-16 11:19:50 +09001094 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1095 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1096 height: u32::try_from(multi_touch.height)?,
1097 width: u32::try_from(multi_touch.width)?,
1098 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1099 },
Jeongik Chac181be72024-03-27 00:18:30 +09001100 })
1101}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001102
1103fn assemble_shared_paths(
1104 shared_paths: &[SharedPath],
1105 temporary_directory: &Path,
1106) -> Result<Vec<SharedPathConfig>, Status> {
1107 if shared_paths.is_empty() {
1108 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1109 }
1110
1111 shared_paths
1112 .iter()
1113 .map(|path| {
1114 Ok(SharedPathConfig {
1115 path: path.sharedPath.clone(),
1116 host_uid: path.hostUid,
1117 host_gid: path.hostGid,
1118 guest_uid: path.guestUid,
1119 guest_gid: path.guestGid,
1120 mask: path.mask,
1121 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001122 socket_path: temporary_directory
1123 .join(&path.socketPath)
1124 .to_string_lossy()
1125 .to_string(),
1126 socket_fd: maybe_clone_file(&path.socketFd)?,
1127 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001128 })
1129 })
1130 .collect()
1131}
1132
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001133/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1134///
1135/// This may involve assembling a composite disk from a set of partition images.
1136fn assemble_disk_image(
1137 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001138 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001139 temporary_directory: &Path,
1140 next_temporary_image_id: &mut u64,
1141 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001142) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001143 let image = if !disk.partitions.is_empty() {
1144 if disk.image.is_some() {
1145 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001146 return Err(anyhow!("DiskImage contains both image and partitions"))
1147 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001148 }
1149
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001150 let composite_image_filenames =
1151 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1152 let (image, partition_files) = make_composite_image(
1153 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001154 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001155 &composite_image_filenames.composite,
1156 &composite_image_filenames.header,
1157 &composite_image_filenames.footer,
1158 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001159 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1160 .with_log()
1161 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001162
1163 // Pass the file descriptors for the various partition files to crosvm when it
1164 // is run.
1165 indirect_files.extend(partition_files);
1166
1167 image
1168 } else if let Some(image) = &disk.image {
1169 clone_file(image)?
1170 } else {
1171 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001172 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1173 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001174 };
1175
1176 Ok(DiskFile { image, writable: disk.writable })
1177}
1178
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001179fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1180 if let Some(ref mut params) = vm_config.params {
1181 params.push(' ');
1182 params.push_str(param)
1183 } else {
1184 vm_config.params = Some(param.to_owned())
1185 }
1186}
1187
Inseob Kim46257382024-01-03 15:41:22 +09001188fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1189 if config.extension()?.to_str()? != "json" {
1190 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001191 }
Inseob Kim46257382024-01-03 15:41:22 +09001192
1193 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1194}
1195
1196fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1197 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1198 let os_names =
1199 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1200
1201 Ok(os_names)
1202}
1203
1204fn get_supported_os_names() -> Result<HashSet<String>> {
1205 if !cfg!(vendor_modules) {
1206 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1207 }
1208
1209 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1210}
1211
1212fn is_valid_os(os_name: &str) -> bool {
1213 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001214}
1215
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001216fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1217 if !cfg!(vendor_modules) {
1218 return false;
1219 }
1220 match config {
1221 VirtualMachineConfig::RawConfig(_) => false,
1222 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1223 }
1224}
1225
Jooyung Han21e9b922021-06-26 04:14:16 +09001226fn load_app_config(
1227 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001228 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001229 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001230) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001231 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1232 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001233 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001234
Shikha Panwar22e70452022-10-10 18:32:55 +00001235 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1236 Some(clone_file(file)?)
1237 } else {
1238 None
1239 };
1240
Alan Stokesfda70842023-12-20 17:50:14 +00001241 let vm_payload_config;
1242 let extra_apk_files: Vec<_>;
1243 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001244 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001245 vm_payload_config =
1246 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1247 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1248 extra_apk_files = vm_payload_config
1249 .extra_apks
1250 .iter()
1251 .enumerate()
1252 .map(|(i, apk)| {
1253 File::open(PathBuf::from(&apk.path))
1254 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1255 })
1256 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001257 }
Alan Stokesfda70842023-12-20 17:50:14 +00001258 Payload::PayloadConfig(payload_config) => {
1259 vm_payload_config = create_vm_payload_config(payload_config)?;
1260 extra_apk_files =
1261 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1262 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001263 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001264
Inseob Kim89b24592024-02-23 18:59:43 +09001265 let payload_config_os = vm_payload_config.os.name.as_str();
1266 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1267 bail!("'os' in payload config is deprecated");
1268 }
1269
Inseob Kim172f9eb2023-11-06 17:02:08 +09001270 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001271 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001272 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001273 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001274 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001275
1276 // It is safe to construct a filename based on the os_name because we've already checked that it
1277 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001278 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1279 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001280 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001281
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001282 if let Some(custom_config) = &config.customConfig {
1283 if let Some(file) = custom_config.customKernelImage.as_ref() {
1284 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1285 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001286 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001287
1288 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001289 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001290 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001291 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001292
Jaewan Kimf43372b2024-12-13 18:33:58 +09001293 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001294 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001295
1296 for param in custom_config.extraKernelCmdlineParams.iter() {
1297 append_kernel_param(param, &mut vm_config);
1298 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001299
1300 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001301 }
1302
Andrew Walbrancc045902021-07-27 16:06:17 +00001303 if config.memoryMib > 0 {
1304 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001305 }
1306
Chris Wailes6177c662024-05-09 14:37:44 -07001307 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001308 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001309 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001310 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001311 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001312
Shikha Panwar22e70452022-10-10 18:32:55 +00001313 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001314 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001315
1316 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1317 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001318 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001319 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001320 temporary_directory,
1321 apk_file,
1322 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001323 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001324 &vm_payload_config,
1325 &mut vm_config,
1326 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001327
Andrew Walbrancc0db522021-07-12 17:03:42 +00001328 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001329}
1330
Inseob Kime3e932d2024-12-16 20:06:57 +09001331fn check_partition_for_file(fd: &ParcelFileDescriptor, calling_partition: &str) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001332 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1333 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1334
1335 // microdroid vendor image is OK
1336 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1337 {
1338 return Ok(());
1339 }
1340
Inseob Kime3e932d2024-12-16 20:06:57 +09001341 let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm");
1342 let is_caller_vendor = calling_partition == "vendor" || calling_partition == "odm";
1343
1344 if is_fd_vendor != is_caller_vendor {
1345 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001346 }
1347
1348 Ok(())
1349}
1350
Inseob Kime3e932d2024-12-16 20:06:57 +09001351fn check_partitions_for_files(
1352 config: &VirtualMachineRawConfig,
1353 calling_partition: &str,
1354) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001355 config
1356 .disks
1357 .iter()
1358 .flat_map(|disk| disk.partitions.iter())
1359 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001360 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001361
Inseob Kime3e932d2024-12-16 20:06:57 +09001362 config
1363 .disks
1364 .iter()
1365 .filter_map(|disk| disk.image.as_ref())
1366 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1367
1368 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1369 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1370 config
1371 .bootloader
1372 .as_ref()
1373 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001374
1375 Ok(())
1376}
1377
Alan Stokes0d1ef782022-09-27 13:46:35 +01001378fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1379 let mut apk_zip = ZipArchive::new(apk_file)?;
1380 let config_file = apk_zip.by_name(config_path)?;
1381 Ok(serde_json::from_reader(config_file)?)
1382}
1383
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001384fn create_vm_payload_config(
1385 payload_config: &VirtualMachinePayloadConfig,
1386) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001387 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1388 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1389 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001390
1391 let payload_binary_name = &payload_config.payloadBinaryName;
1392 if payload_binary_name.contains('/') {
1393 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1394 }
1395
1396 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001397
1398 // The VM only cares about how many there are, these names are actually ignored.
1399 let extra_apk_count = payload_config.extraApks.len();
1400 let extra_apks =
1401 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1402
Nikita Ioffe901083f2025-01-20 01:54:28 +00001403 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1404 // The only payload delivered via Mainline module in this release requires
1405 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1406 // APIs, so we use the fact that the payload is granted
1407 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1408 // com.android.i18n APEX.
1409 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1410 // Microdroid pVMs.
1411 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1412 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1413 } else {
1414 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1415 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001416}
1417
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001418/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001419fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001420 temporary_directory: &Path,
1421 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001422) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001423 let id = *next_temporary_image_id;
1424 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001425 CompositeImageFilenames {
1426 composite: temporary_directory.join(format!("composite-{}.img", id)),
1427 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1428 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1429 }
1430}
1431
1432/// Filenames for a composite disk image, including header and footer partitions.
1433#[derive(Clone, Debug, Eq, PartialEq)]
1434struct CompositeImageFilenames {
1435 /// The composite disk image itself.
1436 composite: PathBuf,
1437 /// The header partition image.
1438 header: PathBuf,
1439 /// The footer partition image.
1440 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001441}
1442
Jiyong Park753553b2021-07-12 21:21:09 +09001443/// Checks whether the caller has a specific permission
1444fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001445 if cfg!(early) {
1446 // Skip permission check for early VMs, in favor of SELinux
1447 return Ok(());
1448 }
David Brazdil1f530702022-10-03 12:18:10 +01001449 let calling_pid = get_calling_pid();
1450 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001451 // Root can do anything
1452 if calling_uid == 0 {
1453 return Ok(());
1454 }
1455 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001456 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001457 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001458 Ok(())
1459 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001460 Err(anyhow!("does not have the {} permission", perm))
1461 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001462 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001463}
1464
Jiyong Park753553b2021-07-12 21:21:09 +09001465/// Check whether the caller of the current Binder method is allowed to manage VMs
1466fn check_manage_access() -> binder::Result<()> {
1467 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1468}
1469
Inseob Kim1119d702022-05-02 18:01:58 +09001470/// Check whether the caller of the current Binder method is allowed to create custom VMs
1471fn check_use_custom_virtual_machine() -> binder::Result<()> {
1472 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1473}
1474
Nikita Ioffe901083f2025-01-20 01:54:28 +00001475/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1476/// rollback protection schema.
1477fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1478 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1479}
1480
Alan Stokes185fe112023-01-10 16:20:55 +00001481/// Return whether a partition is exempt from selinux label checks, because we know that it does
1482/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001483fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001484 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001485 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001486 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001487 || label == "microdroid-apk-idsig"
1488 || label == "payload-metadata"
1489 || label.starts_with("extra-idsig-")
1490}
1491
Alice Wangc206b9b2023-08-28 14:13:51 +00001492/// Returns whether a partition with the given label is safe for a raw config VM.
1493fn is_safe_raw_partition(label: &str) -> bool {
1494 label == "vm-instance"
1495}
1496
Alan Stokes185fe112023-01-10 16:20:55 +00001497/// Check that a file SELinux label is acceptable.
1498///
1499/// 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 +09001500/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001501///
1502/// Note that sepolicy must also grant read access for these types to both virtualization
1503/// service and crosvm.
1504///
1505/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1506/// user devices (W^X).
1507fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1508 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001509 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001510 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001511 | "staging_data_file" // updated/staged APEX images
1512 | "system_file" // immutable dm-verity protected partition
1513 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001514 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001515 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001516 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001517 }
1518}
1519
Alan Stokes185fe112023-01-10 16:20:55 +00001520fn check_label_for_partition(partition: &Partition) -> Result<()> {
1521 let file = partition.image.as_ref().unwrap().as_ref();
1522 check_label_is_allowed(&getfilecon(file)?)
1523 .with_context(|| format!("Partition {} invalid", &partition.label))
1524}
1525
1526fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1527 if let Some(f) = kernel {
1528 check_label_for_file(f, "kernel")?;
1529 }
1530 if let Some(f) = initrd {
1531 check_label_for_file(f, "initrd")?;
1532 }
1533 Ok(())
1534}
1535fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1536 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1537}
1538
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001539/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1540#[derive(Debug)]
1541struct VirtualMachine {
1542 instance: Arc<VmInstance>,
1543}
1544
1545impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001546 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001547 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001548 }
1549}
1550
1551impl Interface for VirtualMachine {}
1552
Devin Moore407df8f2024-08-27 19:39:16 +00001553impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001554 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001555 // Don't check permission. The owner of the VM might have passed this binder object to
1556 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001557 Ok(self.instance.cid as i32)
1558 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001559
Andrew Walbran6b650662021-09-07 13:13:23 +00001560 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001561 // Don't check permission. The owner of the VM might have passed this binder object to
1562 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001563 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001564 }
1565
1566 fn registerCallback(
1567 &self,
1568 callback: &Strong<dyn IVirtualMachineCallback>,
1569 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001570 // Don't check permission. The owner of the VM might have passed this binder object to
1571 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001572
1573 // Only register callback if it may be notified.
1574 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1575 let vm_state = self.instance.vm_state.lock().unwrap();
1576 if matches!(*vm_state, VmState::Dead) {
1577 warn!("Ignoring registerCallback() after VM is died");
1578 } else {
1579 self.instance.callbacks.add(callback.clone());
1580 }
1581 drop(vm_state);
1582
Andrew Walbrandae07162021-03-12 17:05:20 +00001583 Ok(())
1584 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001585
Andrew Walbranf8d94112021-09-07 11:45:36 +00001586 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001587 self.instance
1588 .start()
1589 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1590 .with_log()
1591 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001592 }
1593
Inseob Kima446f802022-07-11 19:46:37 +09001594 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001595 self.instance
1596 .kill()
1597 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1598 .with_log()
1599 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001600 }
1601
Keir Fraser48221ba2024-07-12 14:05:02 +00001602 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1603 let balloon = self
1604 .instance
1605 .get_memory_balloon()
1606 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1607 .with_log()
1608 .or_service_specific_exception(-1)?;
1609 Ok(balloon.try_into().unwrap())
1610 }
1611
1612 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001613 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001614 .set_memory_balloon(num_bytes.try_into().unwrap())
1615 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001616 .with_log()
1617 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001618 }
1619
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001620 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001621 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001622 return Err(Status::new_service_specific_error_str(
1623 IVirtualMachine::ERROR_UNEXPECTED,
1624 Some("Virtual Machine is not running"),
1625 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001626 }
Alan Stokes10c47672022-12-13 17:17:08 +00001627 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001628 if port < VSOCK_PRIV_PORT_MAX {
1629 return Err(Status::new_service_specific_error_str(
1630 IVirtualMachine::ERROR_UNEXPECTED,
1631 Some("Can't connect to privileged port {port}"),
1632 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001633 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001634 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1635 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001636 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001637 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001638 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001639
Devin Moore407df8f2024-08-27 19:39:16 +00001640 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1641 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1642 return Err(Status::new_service_specific_error_str(
1643 IVirtualMachine::ERROR_UNEXPECTED,
1644 Some("Virtual Machine is not running"),
1645 ));
1646 }
1647 let port = port as u32;
1648 if port < VSOCK_PRIV_PORT_MAX {
1649 return Err(Status::new_service_specific_error_str(
1650 IVirtualMachine::ERROR_UNEXPECTED,
1651 Some("Can't connect to privileged port {port}"),
1652 ));
1653 }
1654 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001655 let addr = sockaddr_vm {
1656 svm_family: AF_VSOCK as sa_family_t,
1657 svm_reserved1: 0,
1658 svm_port: port,
1659 svm_cid: cid,
1660 svm_zero: [0u8; 4],
1661 };
1662 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001663 let accessor = Accessor::new(name, get_connection_info);
1664 accessor
1665 .as_binder()
1666 .context("The newly created Accessor should always have a binder")
1667 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1668 }
1669
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001670 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1671 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1672 }
Jiyong Park23b67392024-07-04 13:51:42 +09001673
1674 fn suspend(&self) -> binder::Result<()> {
1675 self.instance
1676 .suspend()
1677 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1678 .with_log()
1679 .or_service_specific_exception(-1)
1680 }
1681
1682 fn resume(&self) -> binder::Result<()> {
1683 self.instance
1684 .resume()
1685 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1686 .with_log()
1687 .or_service_specific_exception(-1)
1688 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001689}
1690
1691impl Drop for VirtualMachine {
1692 fn drop(&mut self) {
1693 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001694 if let Err(e) = self.instance.kill() {
1695 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1696 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001697 }
1698}
1699
1700/// A set of Binders to be called back in response to various events on the VM, such as when it
1701/// dies.
1702#[derive(Debug, Default)]
1703pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1704
1705impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001706 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001707 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001708 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001709 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001710 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001711 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001712 }
1713 }
1714 }
1715
Inseob Kim14cb8692021-08-31 21:50:39 +09001716 /// Call all registered callbacks to notify that the payload is ready to serve.
1717 pub fn notify_payload_ready(&self, cid: Cid) {
1718 let callbacks = &*self.0.lock().unwrap();
1719 for callback in callbacks {
1720 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001721 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001722 }
1723 }
1724 }
1725
Inseob Kim2444af92021-08-31 01:22:50 +09001726 /// Call all registered callbacks to notify that the payload has finished.
1727 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1728 let callbacks = &*self.0.lock().unwrap();
1729 for callback in callbacks {
1730 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001731 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001732 }
1733 }
1734 }
1735
Jooyung Handd0a1732021-11-23 15:26:20 +09001736 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001737 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001738 let callbacks = &*self.0.lock().unwrap();
1739 for callback in callbacks {
1740 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001741 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001742 }
1743 }
1744 }
1745
Andrew Walbrandae07162021-03-12 17:05:20 +00001746 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001747 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001748 let mut callbacks = self.0.lock().unwrap();
1749 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001750 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001751 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001752 }
1753 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001754
1755 // Nothing to notify afterward because VM cannot be restarted.
1756 // Explicitly clear callbacks to prevent potential cyclic references
1757 // between callback and VmInstance.
1758 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001759 }
1760
1761 /// Add a new callback to the set.
1762 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1763 self.0.lock().unwrap().push(callback);
1764 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001765}
1766
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001767/// The mutable state of the VirtualizationService. There should only be one instance of this
1768/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001769#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001770struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001771 /// The VMs which have been started. When VMs are started a weak reference is added to this
1772 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1773 /// the Binder client are dropped the weak reference here will become invalid, and will be
1774 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001775 vms: Vec<Weak<VmInstance>>,
1776}
1777
1778impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001779 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001780 fn vms(&self) -> Vec<Arc<VmInstance>> {
1781 // Attempt to upgrade the weak pointers to strong pointers.
1782 self.vms.iter().filter_map(Weak::upgrade).collect()
1783 }
1784
1785 /// Add a new VM to the list.
1786 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1787 // Garbage collect any entries from the stored list which no longer exist.
1788 self.vms.retain(|vm| vm.strong_count() > 0);
1789
1790 // Actually add the new VM.
1791 self.vms.push(vm);
1792 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001793
Jiyong Park8611a6c2021-07-09 18:17:44 +09001794 /// Get a VM that corresponds to the given cid
1795 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1796 self.vms().into_iter().find(|vm| vm.cid == cid)
1797 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001798}
1799
Andrew Walbran6b650662021-09-07 13:13:23 +00001800/// Gets the `VirtualMachineState` of the given `VmInstance`.
1801fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001802 match &*instance.vm_state.lock().unwrap() {
1803 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1804 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001805 PayloadState::Starting => VirtualMachineState::STARTING,
1806 PayloadState::Started => VirtualMachineState::STARTED,
1807 PayloadState::Ready => VirtualMachineState::READY,
1808 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001809 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001810 },
1811 VmState::Dead => VirtualMachineState::DEAD,
1812 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001813 }
1814}
1815
David Brazdilf50c7a62023-04-19 14:22:42 +00001816/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001817pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1818 file.as_ref()
1819 .try_clone()
1820 .context("Failed to clone File from ParcelFileDescriptor")
1821 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001822 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001823}
1824
Andrew Walbrand3a84182021-09-07 14:48:52 +00001825/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001826fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001827 file.as_ref().map(clone_file).transpose()
1828}
1829
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001830/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001831fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1832 // SAFETY: ownership is transferred from stream to f
1833 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1834 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001835}
1836
Jiyong Parkdcf17412022-02-08 15:07:23 +09001837/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001838fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1839 VersionReq::parse(s)
1840 .with_context(|| format!("Invalid platform version requirement {}", s))
1841 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001842}
1843
Jiyong Parked180932023-02-24 19:55:41 +09001844/// Create the empty ramdump file
1845fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1846 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1847 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1848 // owner) for readout.
1849 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001850 let ramdump = File::create(ramdump_path)
1851 .context("Failed to prepare ramdump file")
1852 .with_log()
1853 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001854 Ok(ramdump)
1855}
1856
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001857/// Create the empty device tree dump file
1858fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1859 let path = temporary_directory.join("device_tree.dtb");
1860 let file = File::create(path)
1861 .context("Failed to prepare device tree dump file")
1862 .with_log()
1863 .or_service_specific_exception(-1)?;
1864 Ok(file)
1865}
1866
Nikita Ioffe5776f082023-02-10 21:38:26 +00001867fn is_protected(config: &VirtualMachineConfig) -> bool {
1868 match config {
1869 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1870 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1871 }
1872}
1873
1874fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1875 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001876 return Err(anyhow!("Can't use gdb with protected VMs"))
1877 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001878 }
1879
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001880 if get_debug_level(config) == Some(DebugLevel::NONE) {
1881 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1882 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001883 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001884
1885 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001886}
1887
Shikha Panwar61a74b52024-02-16 13:17:01 +00001888fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1889 match config {
1890 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1891 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1892 }
1893}
1894
Alan Stokesc96b35e2024-05-03 13:21:20 +01001895fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1896 match config {
1897 VirtualMachineConfig::RawConfig(_) => true,
1898 VirtualMachineConfig::AppConfig(config) => {
1899 let Some(custom) = &config.customConfig else { return true };
1900 custom.wantUpdatable
1901 }
1902 }
1903}
1904
Nikita Ioffe5776f082023-02-10 21:38:26 +00001905fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1906 match config {
1907 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001908 VirtualMachineConfig::AppConfig(config) => {
1909 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1910 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001911 }
1912}
1913
Nikita Ioffe631717e2023-09-05 13:38:07 +01001914fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1915 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1916 if let Some(custom_config) = &config.customConfig {
1917 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1918 return Err(anyhow!("vendor modules feature is disabled"))
1919 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1920 }
1921 }
1922 Ok(())
1923}
1924
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001925fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1926 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1927 if let Some(custom_config) = &config.customConfig {
1928 if !custom_config.devices.is_empty() {
1929 return Err(anyhow!("device assignment feature is disabled"))
1930 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1931 }
1932 }
1933 Ok(())
1934}
1935
Alan Stokesfda70842023-12-20 17:50:14 +00001936fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1937 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1938 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1939 if !payload_config.extraApks.is_empty() {
1940 return Err(anyhow!("multi-tenant feature is disabled"))
1941 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1942 }
1943 Ok(())
1944}
1945
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001946fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1947 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1948 if let Some(custom_config) = &config.customConfig {
1949 if !custom_config.extraKernelCmdlineParams.is_empty() {
1950 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1951 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1952 }
1953 }
1954 Ok(())
1955}
1956
Nikita Ioffe99548382024-10-21 15:54:46 +00001957fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1958 match config {
1959 VirtualMachineConfig::RawConfig(config) => {
1960 if !config.teeServices.is_empty() {
1961 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1962 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1963 }
1964 }
1965 VirtualMachineConfig::AppConfig(config) => {
1966 if let Some(custom_config) = &config.customConfig {
1967 if !custom_config.teeServices.is_empty() {
1968 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1969 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1970 }
1971 }
1972 }
1973 };
1974 Ok(())
1975}
1976
Nikita Ioffef934e812024-07-05 15:44:41 +00001977fn check_protected_vm_is_supported() -> binder::Result<()> {
1978 let is_pvm_supported =
1979 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1980 if is_pvm_supported {
1981 Ok(())
1982 } else {
1983 Err(anyhow!("pVM is not supported"))
1984 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1985 }
1986}
1987
Nikita Ioffe631717e2023-09-05 13:38:07 +01001988fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1989 if !cfg!(vendor_modules) {
1990 check_no_vendor_modules(config)?;
1991 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001992 if !cfg!(device_assignment) {
1993 check_no_devices(config)?;
1994 }
Alan Stokesfda70842023-12-20 17:50:14 +00001995 if !cfg!(multi_tenant) {
1996 check_no_extra_apks(config)?;
1997 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001998 if !cfg!(debuggable_vms_improvements) {
1999 check_no_extra_kernel_cmdline_params(config)?;
2000 }
Nikita Ioffe99548382024-10-21 15:54:46 +00002001 if !cfg!(tee_services_allowlist) {
2002 check_no_tee_services(config)?;
2003 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002004 Ok(())
2005}
2006
Inseob Kimecde8c02024-09-03 13:11:08 +09002007fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2008 check_no_vendor_modules(config)?;
2009 check_no_devices(config)?;
2010
2011 Ok(())
2012}
2013
Inseob Kim0168b462022-12-27 14:54:35 +09002014fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002015 fd: Option<&ParcelFileDescriptor>,
2016 tag: String,
2017) -> Result<Option<File>, Status> {
2018 if let Some(fd) = fd {
2019 return Ok(Some(clone_file(fd)?));
2020 }
2021
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002022 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002023 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002024
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002025 let mut reader = BufReader::new(File::from(read_fd));
2026 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002027
Frederick Mayle26e41af2025-02-05 18:30:29 -08002028 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002029 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002030 buf.clear();
2031 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002032 match reader.read_until(b'\n', &mut buf) {
2033 Ok(0) => {
2034 // EOF
2035 return;
2036 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002037 Ok(_size) => {
2038 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002039 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002040 // Logs sent via TTY usually end lines with "\r\n".
2041 if buf.last() == Some(&b'\r') {
2042 buf.pop();
2043 }
Inseob Kim0168b462022-12-27 14:54:35 +09002044 }
2045 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2046 }
2047 Err(e) => {
2048 error!("Could not read console pipe: {:?}", e);
2049 return;
2050 }
2051 };
2052 });
2053
2054 Ok(Some(write_fd))
2055}
2056
Jooyung Han35edb8f2021-07-01 16:17:16 +09002057/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2058/// it doesn't require that T implements Clone.
2059enum BorrowedOrOwned<'a, T> {
2060 Borrowed(&'a T),
2061 Owned(T),
2062}
2063
Chris Wailes73a1eb72025-01-15 11:56:43 -08002064impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002065 fn as_ref(&self) -> &T {
2066 match self {
2067 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002068 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002069 }
2070 }
2071}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002072
2073/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2074#[derive(Debug, Default)]
2075struct VirtualMachineService {
2076 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002077 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002078}
2079
2080impl Interface for VirtualMachineService {}
2081
2082impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002083 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2084 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002085 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002086 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002087 vm.update_payload_state(PayloadState::Started)
2088 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002089 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002090
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002091 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2092 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002093 Ok(())
2094 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002095 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002096 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002097 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002098 }
Inseob Kim2444af92021-08-31 01:22:50 +09002099
Inseob Kimc7d28c72021-10-25 14:28:10 +00002100 fn notifyPayloadReady(&self) -> binder::Result<()> {
2101 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002102 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002103 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002104 vm.update_payload_state(PayloadState::Ready)
2105 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002106 vm.callbacks.notify_payload_ready(cid);
2107 Ok(())
2108 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002109 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002110 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002111 }
2112 }
2113
Inseob Kimc7d28c72021-10-25 14:28:10 +00002114 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2115 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002116 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002117 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002118 vm.update_payload_state(PayloadState::Finished)
2119 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002120 vm.callbacks.notify_payload_finished(cid, exit_code);
2121 Ok(())
2122 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002123 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002124 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002125 }
2126 }
2127
Alan Stokes2bead0d2022-09-05 16:58:34 +01002128 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002129 let cid = self.cid;
2130 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002131 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002132 vm.update_payload_state(PayloadState::Finished)
2133 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002134 vm.callbacks.notify_error(cid, error_code, message);
2135 Ok(())
2136 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002137 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002138 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002139 }
2140 }
Alice Wangc2fec932023-02-23 16:24:02 +00002141
Shikha Panware45e9422024-02-28 21:18:10 +00002142 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2143 if !is_secretkeeper_supported() {
2144 return Err(StatusCode::NAME_NOT_FOUND)?;
2145 }
2146 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2147 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002148 }
2149
Alice Wange64dd182024-01-17 15:57:55 +00002150 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2151 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002152 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002153}
2154
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002155fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002156 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2157 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002158}
2159
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002160impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002161 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002162 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002163 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002164 BinderFeatures::default(),
2165 )
2166 }
2167}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002168
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002169struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2170
2171impl Interface for SecretkeeperProxy {}
2172
2173impl ISecretkeeper for SecretkeeperProxy {
2174 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2175 // Pass the request to the channel, and read the response.
2176 self.0.processSecretManagementRequest(req)
2177 }
2178
2179 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2180 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2181 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2182 }
2183
2184 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2185 self.0.deleteIds(ids)
2186 }
2187
2188 fn deleteAll(&self) -> binder::Result<()> {
2189 self.0.deleteAll()
2190 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002191
2192 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2193 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2194 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2195 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2196 // use this API from the proxy.
2197 Err(ExceptionCode::SECURITY.into())
2198 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002199}
2200
2201struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2202
2203impl Interface for AuthGraphKeyExchangeProxy {}
2204
2205impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2206 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2207 self.0.create()
2208 }
2209
2210 fn init(
2211 &self,
2212 peer_pub_key: &PubKey,
2213 peer_id: &Identity,
2214 peer_nonce: &[u8],
2215 peer_version: i32,
2216 ) -> binder::Result<KeInitResult> {
2217 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2218 }
2219
2220 fn finish(
2221 &self,
2222 peer_pub_key: &PubKey,
2223 peer_id: &Identity,
2224 peer_signature: &SessionIdSignature,
2225 peer_nonce: &[u8],
2226 peer_version: i32,
2227 own_key: &Key,
2228 ) -> binder::Result<SessionInfo> {
2229 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2230 }
2231
2232 fn authenticationComplete(
2233 &self,
2234 peer_signature: &SessionIdSignature,
2235 shared_keys: &[AuthgraphArc; 2],
2236 ) -> binder::Result<[AuthgraphArc; 2]> {
2237 self.0.authenticationComplete(peer_signature, shared_keys)
2238 }
2239}
2240
Inseob Kimecde8c02024-09-03 13:11:08 +09002241// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002242#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002243struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002244 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002245 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002246 path: String,
2247}
2248
2249#[derive(Debug, Default, Deserialize)]
2250struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002251 early_vm: Vec<EarlyVm>,
2252}
2253
Inseob Kim7e1877b2024-11-07 17:28:56 +09002254static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2255 LazyLock::new(|| Mutex::new(HashMap::new()));
2256
Inseob Kimecde8c02024-09-03 13:11:08 +09002257fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2258 match partition {
2259 "system" => Ok(100..200),
2260 "system_ext" | "product" => Ok(200..300),
Inseob Kime3e932d2024-12-16 20:06:57 +09002261 "vendor" | "odm" => Ok(300..400),
Inseob Kimecde8c02024-09-03 13:11:08 +09002262 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2263 }
2264}
2265
Inseob Kim7e1877b2024-11-07 17:28:56 +09002266fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002267 if !xml_path.exists() {
2268 bail!("{} doesn't exist", xml_path.display());
2269 }
2270
2271 let xml =
2272 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2273 let xml = String::from_utf8(xml)
2274 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2275 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2276 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2277
Inseob Kim7e1877b2024-11-07 17:28:56 +09002278 Ok(early_vms.early_vm)
2279}
Inseob Kimecde8c02024-09-03 13:11:08 +09002280
Inseob Kim7e1877b2024-11-07 17:28:56 +09002281fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2282 for early_vm in early_vms {
2283 let cid = early_vm
2284 .cid
2285 .try_into()
2286 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2287
2288 ensure!(
2289 cid_range.contains(&cid),
2290 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2291 early_vm.name
2292 );
2293 }
2294 Ok(())
2295}
2296
2297fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2298 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2299
2300 if let Some(result) = cache.get(partition) {
2301 return Ok(result.clone());
2302 }
2303
2304 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2305 let mut early_vms = Vec::new();
2306 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2307 match entry {
2308 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2309 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2310 }
2311 }
2312
2313 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2314 .with_context(|| format!("CID validation for {partition} failed"))?;
2315
2316 cache.insert(partition.to_owned(), early_vms.clone());
2317
2318 Ok(early_vms)
2319}
2320
2321fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2322 let mut found_vm: Option<&EarlyVm> = None;
2323
2324 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002325 if early_vm.name != name {
2326 continue;
2327 }
2328
Inseob Kimecde8c02024-09-03 13:11:08 +09002329 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002330 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002331 }
2332
2333 found_vm = Some(early_vm);
2334 }
2335
Inseob Kim7e1877b2024-11-07 17:28:56 +09002336 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002337}
2338
2339fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002340 let early_vms = get_early_vms_in_partition(partition)
2341 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2342
2343 Ok(find_early_vm(&early_vms, name)
2344 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2345 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002346}
2347
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002348#[cfg(test)]
2349mod tests {
2350 use super::*;
2351
2352 #[test]
2353 fn test_is_allowed_label_for_partition() -> Result<()> {
2354 let expected_results = vec![
2355 ("u:object_r:system_file:s0", true),
2356 ("u:object_r:apk_data_file:s0", true),
2357 ("u:object_r:app_data_file:s0", false),
2358 ("u:object_r:app_data_file:s0:c512,c768", false),
2359 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2360 ("invalid", false),
2361 ("user:role:apk_data_file:severity:categories", true),
2362 ("user:role:apk_data_file:severity:categories:extraneous", false),
2363 ];
2364
2365 for (label, expected_valid) in expected_results {
2366 let context = SeContext::new(label)?;
2367 let result = check_label_is_allowed(&context);
2368 if expected_valid {
2369 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2370 } else if result.is_ok() {
2371 bail!("Expected label {} to be disallowed", label);
2372 }
2373 }
2374 Ok(())
2375 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002376
2377 #[test]
2378 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2379 let apk = tempfile::tempfile().unwrap();
2380 let idsig = tempfile::tempfile().unwrap();
2381
2382 let ret = create_or_update_idsig_file(
2383 &ParcelFileDescriptor::new(apk),
2384 &ParcelFileDescriptor::new(idsig),
2385 );
2386 assert!(ret.is_err(), "should fail");
2387 Ok(())
2388 }
2389
2390 #[test]
2391 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2392 let tmp_dir = tempfile::TempDir::new().unwrap();
2393 let apk = File::open(tmp_dir.path()).unwrap();
2394 let idsig = tempfile::tempfile().unwrap();
2395
2396 let ret = create_or_update_idsig_file(
2397 &ParcelFileDescriptor::new(apk),
2398 &ParcelFileDescriptor::new(idsig),
2399 );
2400 assert!(ret.is_err(), "should fail");
2401 Ok(())
2402 }
2403
2404 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2405 /// on ext4 filesystem is passed.
2406 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2407 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2408 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2409 #[test]
2410 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2411 // APEXes are backed by the ext4.
2412 let apk = File::open("/apex/com.android.virt/").unwrap();
2413 let idsig = tempfile::tempfile().unwrap();
2414
2415 let ret = create_or_update_idsig_file(
2416 &ParcelFileDescriptor::new(apk),
2417 &ParcelFileDescriptor::new(idsig),
2418 );
2419 assert!(ret.is_err(), "should fail");
2420 Ok(())
2421 }
Jiyong Park8d192952023-06-26 14:29:51 +09002422
2423 #[test]
2424 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2425 use std::io::Seek;
2426
2427 // Pick any APK
2428 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2429 let mut idsig = tempfile::tempfile().unwrap();
2430
2431 create_or_update_idsig_file(
2432 &ParcelFileDescriptor::new(apk.try_clone()?),
2433 &ParcelFileDescriptor::new(idsig.try_clone()?),
2434 )?;
2435 let modified_orig = idsig.metadata()?.modified()?;
2436 apk.rewind()?;
2437 idsig.rewind()?;
2438
2439 // Call the function again
2440 create_or_update_idsig_file(
2441 &ParcelFileDescriptor::new(apk.try_clone()?),
2442 &ParcelFileDescriptor::new(idsig.try_clone()?),
2443 )?;
2444 let modified_new = idsig.metadata()?.modified()?;
2445 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2446 Ok(())
2447 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002448
2449 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002450 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2451 use std::io::Read;
2452
2453 // Pick any APK
2454 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2455 let idsig_empty = tempfile::tempfile().unwrap();
2456 let mut idsig_invalid = tempfile::tempfile().unwrap();
2457 idsig_invalid.write_all(b"Oops")?;
2458
2459 // Create new idsig
2460 create_or_update_idsig_file(
2461 &ParcelFileDescriptor::new(apk.try_clone()?),
2462 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2463 )?;
2464 apk.rewind()?;
2465
2466 // Update idsig_invalid
2467 create_or_update_idsig_file(
2468 &ParcelFileDescriptor::new(apk.try_clone()?),
2469 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2470 )?;
2471
2472 // Ensure the 2 idsig files have same size!
2473 assert!(
2474 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2475 "idsig files differ in size"
2476 );
2477 // Ensure the 2 idsig files have same content!
2478 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2479 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2480 }
2481 Ok(())
2482 }
2483 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002484 fn test_append_kernel_param_first_param() {
2485 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2486 append_kernel_param("foo=1", &mut vm_config);
2487 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2488 }
2489
2490 #[test]
2491 fn test_append_kernel_param() {
2492 let mut vm_config =
2493 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2494 append_kernel_param("bar=42", &mut vm_config);
2495 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2496 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002497
Inseob Kim46257382024-01-03 15:41:22 +09002498 fn test_extract_os_name_from_config_path(
2499 path: &Path,
2500 expected_result: Option<&str>,
2501 ) -> Result<()> {
2502 let result = extract_os_name_from_config_path(path);
2503 if result.as_deref() != expected_result {
2504 bail!("Expected {:?} but was {:?}", expected_result, &result)
2505 }
2506 Ok(())
2507 }
2508
2509 #[test]
2510 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2511 test_extract_os_name_from_config_path(
2512 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2513 Some("microdroid"),
2514 )
2515 }
2516
2517 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002518 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2519 test_extract_os_name_from_config_path(
2520 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2521 Some("microdroid_16k"),
2522 )
2523 }
2524
2525 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002526 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2527 test_extract_os_name_from_config_path(
2528 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2529 Some("microdroid_gki-android14-6.1"),
2530 )
2531 }
2532
2533 #[test]
2534 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2535 test_extract_os_name_from_config_path(
2536 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2537 None,
2538 )
2539 }
2540
2541 #[test]
2542 fn test_extract_os_name_from_configs() -> Result<()> {
2543 let tmp_dir = tempfile::TempDir::new()?;
2544 let tmp_dir_path = tmp_dir.path().to_owned();
2545
2546 let mut os_names: HashSet<String> = HashSet::new();
2547 os_names.insert("microdroid".to_owned());
2548 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2549 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2550
2551 // config files
2552 for os_name in &os_names {
2553 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2554 }
2555
2556 // fake files not related to configs
2557 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2558 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2559
2560 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2561 Some(s) => s.to_owned(),
2562 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2563 };
2564
2565 let result = extract_os_names_from_configs(&glob_pattern)?;
2566 if result != os_names {
2567 bail!("Expected {:?} but was {:?}", os_names, result);
2568 }
2569 Ok(())
2570 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002571
2572 #[test]
2573 fn test_find_early_vms_from_xml() -> Result<()> {
2574 let tmp_dir = tempfile::TempDir::new()?;
2575 let tmp_dir_path = tmp_dir.path().to_owned();
2576 let xml_path = tmp_dir_path.join("early_vms.xml");
2577
2578 std::fs::write(
2579 &xml_path,
2580 br#"<?xml version="1.0" encoding="utf-8"?>
2581 <early_vms>
2582 <early_vm>
2583 <name>vm_demo_native_early</name>
2584 <cid>123</cid>
2585 <path>/system/bin/vm_demo_native_early</path>
2586 </early_vm>
2587 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002588 <name>vm_demo_native_early_2</name>
2589 <cid>456</cid>
2590 <path>/system/bin/vm_demo_native_early_2</path>
2591 </early_vm>
2592 </early_vms>
2593 "#,
2594 )?;
2595
2596 let cid_range = 100..1000;
2597
2598 let early_vms = get_early_vms_in_path(&xml_path)?;
2599 validate_cid_range(&early_vms, &cid_range)?;
2600
2601 let test_cases = [
2602 (
2603 "vm_demo_native_early",
2604 EarlyVm {
2605 name: "vm_demo_native_early".to_owned(),
2606 cid: 123,
2607 path: "/system/bin/vm_demo_native_early".to_owned(),
2608 },
2609 ),
2610 (
2611 "vm_demo_native_early_2",
2612 EarlyVm {
2613 name: "vm_demo_native_early_2".to_owned(),
2614 cid: 456,
2615 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2616 },
2617 ),
2618 ];
2619
2620 for (name, expected) in test_cases {
2621 let result = find_early_vm(&early_vms, name)?;
2622 assert_eq!(result, &expected);
2623 }
2624
2625 Ok(())
2626 }
2627
2628 #[test]
2629 fn test_invalid_cid_validation() -> Result<()> {
2630 let tmp_dir = tempfile::TempDir::new()?;
2631 let xml_path = tmp_dir.path().join("early_vms.xml");
2632
2633 let cid_range = 100..1000;
2634
2635 for cid in [-1, 999999] {
2636 std::fs::write(
2637 &xml_path,
2638 format!(
2639 r#"<?xml version="1.0" encoding="utf-8"?>
2640 <early_vms>
2641 <early_vm>
2642 <name>vm_demo_invalid_cid</name>
2643 <cid>{cid}</cid>
2644 <path>/system/bin/vm_demo_invalid_cid</path>
2645 </early_vm>
2646 </early_vms>
2647 "#
2648 ),
2649 )?;
2650
2651 let early_vms = get_early_vms_in_path(&xml_path)?;
2652 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2653 }
2654
2655 Ok(())
2656 }
2657
2658 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002659 fn test_symlink_to_system_ext_supported() -> Result<()> {
2660 let link_path = Path::new("/system/system_ext/file");
2661 let partition = find_partition(Some(link_path)).unwrap();
2662 assert_eq!("system_ext", partition);
2663 Ok(())
2664 }
2665
2666 #[test]
2667 fn test_symlink_to_product_supported() -> Result<()> {
2668 let link_path = Path::new("/system/product/file");
2669 let partition = find_partition(Some(link_path)).unwrap();
2670 assert_eq!("product", partition);
2671 Ok(())
2672 }
2673
2674 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002675 fn test_duplicated_early_vms() -> Result<()> {
2676 let tmp_dir = tempfile::TempDir::new()?;
2677 let tmp_dir_path = tmp_dir.path().to_owned();
2678 let xml_path = tmp_dir_path.join("early_vms.xml");
2679
2680 std::fs::write(
2681 &xml_path,
2682 br#"<?xml version="1.0" encoding="utf-8"?>
2683 <early_vms>
2684 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002685 <name>vm_demo_duplicated_name</name>
2686 <cid>456</cid>
2687 <path>/system/bin/vm_demo_duplicated_name_1</path>
2688 </early_vm>
2689 <early_vm>
2690 <name>vm_demo_duplicated_name</name>
2691 <cid>789</cid>
2692 <path>/system/bin/vm_demo_duplicated_name_2</path>
2693 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002694 </early_vms>
2695 "#,
2696 )?;
2697
2698 let cid_range = 100..1000;
2699
Inseob Kim7e1877b2024-11-07 17:28:56 +09002700 let early_vms = get_early_vms_in_path(&xml_path)?;
2701 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002702
Inseob Kim7e1877b2024-11-07 17:28:56 +09002703 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002704
2705 Ok(())
2706 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002707}