blob: e954d218d9cb4ef479257f93a71451acca0132a4 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Seungjae Yoo13af0b62024-05-20 14:15:13 +090017use crate::{get_calling_pid, get_calling_uid, get_this_pid};
Alan Stokesfda70842023-12-20 17:50:14 +000018use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use crate::composite::make_composite_image;
Akilesh Kailash05515dc2024-10-22 21:42:52 -070020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, SharedPathConfig, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
Jaewan Kimabd328b2024-12-10 15:59:33 +090021use crate::debug_config::{DebugConfig, DebugPolicy};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Inseob Kimf79c5722024-12-16 17:29:57 +090023use crate::payload::{ApexInfoList, add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Nikita Ioffe13748d22024-10-23 15:10:39 +000024use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Jaewan Kimf43372b2024-12-13 18:33:58 +090032 AssignedDevices::AssignedDevices,
Inseob Kim53d0b212023-07-20 16:58:37 +090033 AssignableDevice::AssignableDevice,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Akilesh Kailash05515dc2024-10-22 21:42:52 -070035 SharedPath::SharedPath,
Jeongik Chac181be72024-03-27 00:18:30 +090036 InputDevice::InputDevice,
Devin Moore407df8f2024-08-27 19:39:16 +000037 IVirtualMachine::{self, BnVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000038 IVirtualMachineCallback::IVirtualMachineCallback,
39 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090040 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000041 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090042 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090043 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000044 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010045 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090046 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000047 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090048};
Inseob Kimecde8c02024-09-03 13:11:08 +090049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000052 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053};
Shikha Panware45e9422024-02-28 21:18:10 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +000056use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000057use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
58 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
59 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
60 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
61 SessionInitiationInfo::SessionInitiationInfo,
62};
Inseob Kim7e1877b2024-11-07 17:28:56 +090063use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090065use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010066use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000067 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
68 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000069};
Inseob Kim46257382024-01-03 15:41:22 +090070use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000071use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000072use log::{debug, error, info, warn};
Nikita Ioffe901083f2025-01-20 01:54:28 +000073use microdroid_payload_config::{ApexConfig, ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090074use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000075use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000076use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090077use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090078use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090079use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000080use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000081use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090082use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090083use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000084use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090085use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000086use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090087use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090088use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000089use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010091use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090092use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010093use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000094use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090095use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096
David Brazdil41d1a872022-10-05 14:44:19 +010097/// The unique ID of a VM used (together with a port number) for vsock communication.
98pub type Cid = u32;
99
David Brazdil4b4c5102022-12-19 22:56:20 +0000100pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
101
Devin Moore407df8f2024-08-27 19:39:16 +0000102/// Vsock privileged ports are below this number.
103const VSOCK_PRIV_PORT_MAX: u32 = 1024;
104
Jooyung Han95884632021-07-06 22:27:54 +0900105/// The size of zero.img.
106/// Gaps in composite disk images are filled with a shared zero.img.
107const ZERO_FILLER_SIZE: u64 = 4096;
108
David Brazdilf50c7a62023-04-19 14:22:42 +0000109/// Magic string for the instance image
110const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
111
112/// Version of the instance image format
113const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
114
Alan Stokes0d1ef782022-09-27 13:46:35 +0100115const MICRODROID_OS_NAME: &str = "microdroid";
116
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000117const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000118 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000119
David Brazdilf50c7a62023-04-19 14:22:42 +0000120const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
121
122/// crosvm requires all partitions to be a multiple of 4KiB.
123const PARTITION_GRANULARITY_BYTES: u64 = 4096;
124
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000125const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
126
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100127pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
128 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900129 if cfg!(early) {
130 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
131 } else {
132 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
133 .expect("Could not connect to VirtualizationServiceInternal")
134 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100135 });
136static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
137 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000138
Inseob Kime3e932d2024-12-16 20:06:57 +0900139static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
140 let calling_exe_link = format!("/proc/{}/exe", get_calling_pid());
141 match fs::read_link(&calling_exe_link) {
142 Ok(calling_exe_path) => Some(calling_exe_path),
143 Err(e) => {
144 // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we
145 // discourage vendor apps, regarding such cases as system is safer.
146 // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of
147 // apps.
148 warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system");
149 None
150 }
151 }
152});
153
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000154fn create_or_update_idsig_file(
155 input_fd: &ParcelFileDescriptor,
156 idsig_fd: &ParcelFileDescriptor,
157) -> Result<()> {
158 let mut input = clone_file(input_fd)?;
159 let metadata = input.metadata().context("failed to get input metadata")?;
160 if !metadata.is_file() {
161 bail!("input is not a regular file");
162 }
Alan Stokes25f69362023-03-06 16:51:54 +0000163 let mut sig =
164 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
165 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000166
167 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900168
169 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
170 // if the idsig file already has the same APK digest.
171 if output.metadata()?.len() > 0 {
172 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
173 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
174 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
175 return Ok(());
176 }
177 }
178 // if we fail to read v4signature from output, that's fine. User can pass a random file.
179 // We will anyway overwrite the file to the v4signature generated from input_fd.
180 }
181
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000182 output
183 .seek(SeekFrom::Start(0))
184 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000185 output.set_len(0).context("failed to set_len on the idsig output")?;
186 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000187 Ok(())
188}
189
Alan Stokes25f69362023-03-06 16:51:54 +0000190fn get_current_sdk() -> Result<u32> {
191 let current_sdk = system_properties::read("ro.build.version.sdk")?;
192 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
193 current_sdk.parse().context("Malformed SDK version")
194}
195
David Brazdil4b4c5102022-12-19 22:56:20 +0000196pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
197 for dir_entry in read_dir(path)? {
198 remove_file(dir_entry?.path())?;
199 }
200 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100201}
202
David Brazdil528e0472022-10-10 15:06:02 +0100203/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000204#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000205pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900206 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000207}
208
Shikha Panward8e35422021-10-11 13:51:27 +0000209impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000210 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000211 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
212 let state = &mut *self.state.lock().unwrap();
213 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000214 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000215 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000216 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
217 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000218 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000219 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000220 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000221 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
222 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000223 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000224 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000225 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000226 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000227 .or(Err(StatusCode::UNKNOWN_ERROR))?;
228 }
229 Ok(())
230 }
231}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000232impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000233 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
234 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000235 ///
236 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000237 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000238 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000239 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900240 console_out_fd: Option<&ParcelFileDescriptor>,
241 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000242 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000243 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000244 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000245 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900246 let ret = self.create_vm_internal(
247 config,
248 console_out_fd,
249 console_in_fd,
250 log_fd,
251 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000252 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900253 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000254 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000255 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000256 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000257
Shikha Panwar61a74b52024-02-16 13:17:01 +0000258 /// Allocate a new instance_id to the VM
259 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000260 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000261 GLOBAL_SERVICE.allocateInstanceId()
262 }
263
Andrew Walbrandff3b942021-06-09 15:20:36 +0000264 /// Initialise an empty partition image of the given size to be used as a writable partition.
265 fn initializeWritablePartition(
266 &self,
267 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000268 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900269 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000270 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900271 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900272 let size_bytes = size_bytes
273 .try_into()
274 .with_context(|| format!("Invalid size: {}", size_bytes))
275 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000276 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000277 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000278 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000279 image
280 .seek(SeekFrom::Start(0))
281 .context("failed to move cursor to start")
282 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900283 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700284 // Set the file length. In most filesystems, this will not allocate any physical disk
285 // space, it will only change the logical size.
286 image
287 .set_len(size_bytes)
288 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900289 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000290
291 match partition_type {
292 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700293 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
294 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000295 _ => Err(Error::new(
296 ErrorKind::Unsupported,
297 format!("Unsupported partition type {:?}", partition_type),
298 )),
299 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900300 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
301 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000302
303 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000304 }
305
Shraddha Basantwania9a9c4f2025-02-25 09:51:48 -0800306 fn setEncryptedStorageSize(
307 &self,
308 image_fd: &ParcelFileDescriptor,
309 size: i64,
310 ) -> binder::Result<()> {
311 check_manage_access()?;
312
313 let size = size
314 .try_into()
315 .with_context(|| format!("Invalid size: {}", size))
316 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
317 let size = round_up(size, PARTITION_GRANULARITY_BYTES);
318
319 let image = clone_file(image_fd)?;
320 let image_size = image.metadata().unwrap().len();
321
322 if image_size > size {
323 return Err(Status::new_exception_str(
324 ExceptionCode::ILLEGAL_ARGUMENT,
325 Some("Can't shrink encrypted storage"),
326 ));
327 }
328 // Reset the file length. In most filesystems, this will not allocate any physical disk
329 // space, it will only change the logical size.
330 image.set_len(size).context("Failed to extend file").or_service_specific_exception(-1)?;
331 Ok(())
332 }
333
Jiyong Park0a248432021-08-20 23:32:39 +0900334 /// Creates or update the idsig file by digesting the input APK file.
335 fn createOrUpdateIdsigFile(
336 &self,
337 input_fd: &ParcelFileDescriptor,
338 idsig_fd: &ParcelFileDescriptor,
339 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900340 check_manage_access()?;
341
Jiyong Park2227eaa2023-08-04 11:59:18 +0900342 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900343 Ok(())
344 }
345
Andrew Walbran320b5602021-03-04 16:11:12 +0000346 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
347 /// and as such is only permitted from the shell user.
348 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000349 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000350 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000351 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900352
353 /// Get a list of assignable device types.
354 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
355 // Delegate to the global service, including checking the permission.
356 GLOBAL_SERVICE.getAssignableDevices()
357 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100358
Inseob Kim46257382024-01-03 15:41:22 +0900359 /// Get a list of supported OSes.
360 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
361 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
362 }
363
Jaewan Kimabd328b2024-12-10 15:59:33 +0900364 /// Get printable debug policy for testing and debugging
365 fn getDebugPolicy(&self) -> binder::Result<String> {
366 let debug_policy = DebugPolicy::from_host();
367 Ok(format!("{debug_policy:?}"))
368 }
369
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100370 /// Returns whether given feature is enabled
371 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
372 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000373 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100374 }
Alice Wange64dd182024-01-17 15:57:55 +0000375
376 fn enableTestAttestation(&self) -> binder::Result<()> {
377 GLOBAL_SERVICE.enableTestAttestation()
378 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000379
380 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
381 check_manage_access()?;
382 GLOBAL_SERVICE.isRemoteAttestationSupported()
383 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000384
385 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
386 // The response is specific to Microdroid. Updatable VMs are only possible if device
387 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
388 // this, however other guest OSes may do things differently.
389 check_manage_access()?;
390 Ok(is_secretkeeper_supported())
391 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000392
Shikha Panwar07d701c2024-03-28 14:43:52 +0000393 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
394 check_manage_access()?;
395 GLOBAL_SERVICE.removeVmInstance(instance_id)
396 }
397
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000398 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
399 check_manage_access()?;
400 GLOBAL_SERVICE.claimVmInstance(instance_id)
401 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000402}
403
Inseob Kimecde8c02024-09-03 13:11:08 +0900404/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
405#[derive(Debug, Default)]
406struct EarlyVmContext {
407 /// The unique CID assigned to the VM for vsock communication.
408 cid: Cid,
409 /// Temporary directory for this VM instance.
410 temp_dir: PathBuf,
411}
412
413impl EarlyVmContext {
414 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
415 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
416 // should trust clients, e.g. they won't run two VMs at the same time
417 let _ = remove_dir_all(&temp_dir);
418 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
419
420 Ok(Self { cid, temp_dir })
421 }
422}
423
424impl Interface for EarlyVmContext {}
425
426impl Drop for EarlyVmContext {
427 fn drop(&mut self) {
428 if let Err(e) = remove_dir_all(&self.temp_dir) {
429 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
430 }
431 }
432}
433
434impl IGlobalVmContext for EarlyVmContext {
435 fn getCid(&self) -> binder::Result<i32> {
436 Ok(self.cid as i32)
437 }
438
439 fn getTemporaryDirectory(&self) -> binder::Result<String> {
440 Ok(self.temp_dir.to_string_lossy().to_string())
441 }
442
443 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
444 Err(Status::new_exception_str(
445 ExceptionCode::UNSUPPORTED_OPERATION,
446 Some("Early VM doesn't support setting host console name"),
447 ))
448 }
449}
450
Inseob Kime3e932d2024-12-16 20:06:57 +0900451fn find_partition(path: Option<&Path>) -> binder::Result<String> {
452 let path = match path {
453 Some(path) => path,
454 None => return Ok("system".to_owned()),
455 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000456 if path.starts_with("/system/system_ext/") {
457 return Ok("system_ext".to_owned());
458 } else if path.starts_with("/system/product/") {
459 return Ok("product".to_owned());
460 }
Inseob Kimf79c5722024-12-16 17:29:57 +0900461 let mut components = path.components();
462 match components.nth(1) {
Inseob Kimecde8c02024-09-03 13:11:08 +0900463 Some(std::path::Component::Normal(partition)) => {
Inseob Kimf79c5722024-12-16 17:29:57 +0900464 if partition != "apex" {
465 return Ok(partition.to_string_lossy().into_owned());
466 }
467
468 // If path is under /apex, find a partition of the preinstalled .apex path
469 let apex_name = match components.next() {
470 Some(std::path::Component::Normal(name)) => name.to_string_lossy(),
471 _ => {
472 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
473 .or_service_specific_exception(-1)
474 }
475 };
476
477 let apex_info_list = ApexInfoList::load()
478 .context("Failed to get apex info list")
479 .or_service_specific_exception(-1)?;
480
481 for apex_info in apex_info_list.list.iter() {
482 if apex_info.name == apex_name {
483 return Ok(apex_info.partition.to_lowercase());
484 }
485 }
486
487 Err(anyhow!("Can't find apex info for '{apex_name}'")).or_service_specific_exception(-1)
Inseob Kimecde8c02024-09-03 13:11:08 +0900488 }
489 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
490 .or_service_specific_exception(-1),
491 }
492}
493
Jiyong Park8611a6c2021-07-09 18:17:44 +0900494impl VirtualizationService {
495 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000496 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900497 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000498
Inseob Kimecde8c02024-09-03 13:11:08 +0900499 fn create_early_vm_context(
500 &self,
501 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900502 calling_exe_path: Option<&Path>,
Inseob Kimecde8c02024-09-03 13:11:08 +0900503 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900504 let name = match config {
505 VirtualMachineConfig::RawConfig(config) => &config.name,
506 VirtualMachineConfig::AppConfig(config) => &config.name,
507 };
Inseob Kime3e932d2024-12-16 20:06:57 +0900508 let calling_partition = find_partition(calling_exe_path)?;
509 let early_vm = find_early_vm_for_partition(&calling_partition, name)
510 .or_service_specific_exception(-1)?;
511 let calling_exe_path = match calling_exe_path {
512 Some(path) => path,
513 None => {
514 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
515 .or_service_specific_exception(-1)
516 }
517 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000518 let expected_exe_path = Path::new(&early_vm.path);
519 if expected_exe_path != calling_exe_path
520 && Path::new("/system").join(expected_exe_path) != calling_exe_path
521 {
Inseob Kimecde8c02024-09-03 13:11:08 +0900522 return Err(anyhow!(
Inseob Kime3e932d2024-12-16 20:06:57 +0900523 "VM '{name}' in partition '{calling_partition}' must be created with '{}', not '{}'",
Inseob Kimecde8c02024-09-03 13:11:08 +0900524 &early_vm.path,
Inseob Kime3e932d2024-12-16 20:06:57 +0900525 calling_exe_path.display()
Inseob Kimecde8c02024-09-03 13:11:08 +0900526 ))
527 .or_service_specific_exception(-1);
528 }
529
530 let cid = early_vm.cid as Cid;
531 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
532
533 let context = EarlyVmContext::new(cid, temp_dir.clone())
534 .context(format!("Can't create early vm contexts for {cid}"))
535 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900536
Jiyong Park690c1ca2024-11-28 18:06:50 +0900537 if requires_vm_service(config) {
538 // Start VM service listening for connections from the new CID on port=CID.
539 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
540 let port = cid;
541 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
542 .context(format!("Could not start RpcServer on port {port}"))
543 .or_service_specific_exception(-1)?;
544 vm_server.start();
545 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
546 } else {
547 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
548 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900549 }
550
David Brazdil209074a2023-01-12 16:44:51 +0000551 fn create_vm_context(
552 &self,
553 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900554 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000555 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000556 const NUM_ATTEMPTS: usize = 5;
557
558 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000559 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000560 let cid = vm_context.getCid()? as Cid;
561 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900562
563 // We don't need to start the VM service for custom VMs.
564 if !requires_vm_service(config) {
565 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
566 }
567
David Brazdil8cf8f482022-11-23 14:21:26 +0000568 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
569
570 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000571 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000572 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000573 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000574 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900575 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000576 }
577 Err(err) => {
578 warn!("Could not start RpcServer on port {}: {}", port, err);
579 }
580 }
581 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900582 Err(anyhow!("Too many attempts to create VM context failed"))
583 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000584 }
585
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000586 fn create_vm_internal(
587 &self,
588 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900589 console_out_fd: Option<&ParcelFileDescriptor>,
590 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000591 log_fd: Option<&ParcelFileDescriptor>,
592 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000593 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000594 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000595 let requester_uid = get_calling_uid();
596 let requester_debug_pid = get_calling_pid();
597
Nikita Ioffe631717e2023-09-05 13:38:07 +0100598 check_config_features(config)?;
599
Inseob Kimecde8c02024-09-03 13:11:08 +0900600 if cfg!(early) {
601 check_config_allowed_for_early_vms(config)?;
602 }
603
Nikita Ioffeb1416122024-10-22 12:18:49 +0000604 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
605 info!("callers secontext: {}", caller_secontext);
606
David Brazdil209074a2023-01-12 16:44:51 +0000607 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900608 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Inseob Kime3e932d2024-12-16 20:06:57 +0900609 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref())?
Inseob Kimecde8c02024-09-03 13:11:08 +0900610 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900611 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900612 };
Inseob Kim1119d702022-05-02 18:01:58 +0900613
Alan Stokesfda70842023-12-20 17:50:14 +0000614 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100615 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900616 }
617
Nikita Ioffe5776f082023-02-10 21:38:26 +0000618 let gdb_port = extract_gdb_port(config);
619
620 // Additional permission checks if caller request gdb.
621 if gdb_port.is_some() {
622 check_gdb_allowed(config)?;
623 }
624
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800625 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900626 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800627 if let Some(dt_overlay) =
628 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
629 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900630 device_tree_overlays.push(dt_overlay);
631 }
632 if let Some(dtbo) = get_dtbo(config) {
633 let dtbo = File::from(
634 dtbo.as_ref()
635 .try_clone()
636 .context("Failed to create VM DTBO from ParcelFileDescriptor")
637 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
638 );
639 device_tree_overlays.push(dtbo);
640 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900641
Jaewan Kimf3143242024-03-15 06:56:31 +0000642 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000643 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900644 Some(prepare_ramdump_file(&temporary_directory)?)
645 } else {
646 None
647 };
648
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000649 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900650 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100651 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900652 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100653 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100654 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
655 Some(clone_file(fd)?)
656 } else if debug_config.dump_device_tree {
657 Some(prepare_dump_dt_file(&temporary_directory)?)
658 } else {
659 None
660 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000661
662 // Counter to generate unique IDs for temporary image files.
663 let mut next_temporary_image_id = 0;
664 // Files which are referred to from composite images. These must be mapped to the crosvm
665 // child process, and not closed before it is started.
666 let mut indirect_files = vec![];
667
Alan Stokes7bc146c2022-10-20 17:10:32 +0100668 let (is_app_config, config) = match config {
669 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
670 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900671 let config = load_app_config(config, &debug_config, &temporary_directory)
672 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900673 *is_protected = config.protectedVm;
674 let message = format!("Failed to load app config: {:?}", e);
675 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900676 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900677 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100678 (true, BorrowedOrOwned::Owned(config))
679 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000680 };
681 let config = config.as_ref();
682 *is_protected = config.protectedVm;
683
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000684 if !config.teeServices.is_empty() {
685 check_tee_service_permission(&caller_secontext, &config.teeServices)
686 .with_log()
687 .or_binder_exception(ExceptionCode::SECURITY)?;
688 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000689
Jiyong Park3051ffe2024-11-26 14:41:58 +0900690 let kernel = maybe_clone_file(&config.kernel)?;
691 let initrd = maybe_clone_file(&config.initrd)?;
692
693 if config.protectedVm {
694 // Fail fast with a meaningful error message in case device doesn't support pVMs.
695 check_protected_vm_is_supported()?;
696
697 // In a protected VM, we require custom kernels to come from a trusted source
698 // (b/237054515).
699 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
700
701 // Check if partition images are labeled incorrectly. This is to prevent random images
702 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
703 // from being loaded in a pVM. This applies to everything but the instance image in the
704 // raw config, and everything but the non-executable, generated partitions in the app
705 // config.
706 config
707 .disks
708 .iter()
709 .flat_map(|disk| disk.partitions.iter())
710 .filter(|partition| {
711 if is_app_config {
712 !is_safe_app_partition(&partition.label)
713 } else {
714 !is_safe_raw_partition(&partition.label)
715 }
716 })
717 .try_for_each(check_label_for_partition)
718 .or_service_specific_exception(-1)?;
719 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000720
Inseob Kimff48a7c2024-02-26 22:07:21 +0900721 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
722 // have unstable interfaces.
723 // TODO(b/316431494): remove once Treble interfaces are stabilized.
Inseob Kime3e932d2024-12-16 20:06:57 +0900724 check_partitions_for_files(config, &find_partition(CALLING_EXE_PATH.as_deref())?)
725 .or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900726
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000727 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900728 write_zero_filler(&zero_filler_path)
729 .context("Failed to make composite image")
730 .with_log()
731 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000732
733 // Assemble disk images if needed.
734 let disks = config
735 .disks
736 .iter()
737 .map(|disk| {
738 assemble_disk_image(
739 disk,
740 &zero_filler_path,
741 &temporary_directory,
742 &mut next_temporary_image_id,
743 &mut indirect_files,
744 )
745 })
746 .collect::<Result<Vec<DiskFile>, _>>()?;
747
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700748 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
749
Jaewan Kimf43372b2024-12-13 18:33:58 +0900750 let (vfio_devices, dtbo) = match &config.devices {
751 AssignedDevices::Devices(devices) if !devices.is_empty() => {
752 let mut set = HashSet::new();
753 for device in devices.iter() {
754 let path = canonicalize(device)
755 .with_context(|| format!("can't canonicalize {device}"))
756 .or_service_specific_exception(-1)?;
757 if !set.insert(path) {
758 return Err(anyhow!("duplicated device {device}"))
759 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
760 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900761 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900762 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
763 let dtbo_file = File::from(
764 GLOBAL_SERVICE
765 .getDtboFile()?
766 .as_ref()
767 .try_clone()
768 .context("Failed to create VM DTBO from ParcelFileDescriptor")
769 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
770 );
771 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900772 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900773 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900774 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900775 let display_config = if cfg!(paravirtualized_devices) {
776 config
777 .displayConfig
778 .as_ref()
779 .map(DisplayConfig::new)
780 .transpose()
781 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
782 } else {
783 None
784 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700785 let gpu_config = if cfg!(paravirtualized_devices) {
786 config
787 .gpuConfig
788 .as_ref()
789 .map(GpuConfig::new)
790 .transpose()
791 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
792 } else {
793 None
794 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900795
Jeongik Chac181be72024-03-27 00:18:30 +0900796 let input_device_options = if cfg!(paravirtualized_devices) {
797 config
798 .inputDevices
799 .iter()
800 .map(to_input_device_option_from)
801 .collect::<Result<Vec<InputDeviceOption>, _>>()
802 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
803 } else {
804 vec![]
805 };
806
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900807 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900808 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900809 if *is_protected {
810 return Err(anyhow!("Network feature is not supported for pVM yet"))
811 .with_log()
812 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
813 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900814 Some(File::from(
815 GLOBAL_SERVICE
816 .createTapInterface(&get_this_pid().to_string())?
817 .as_ref()
818 .try_clone()
819 .context("Failed to get TAP interface from ParcelFileDescriptor")
820 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
821 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900822 } else {
823 None
824 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800825
826 let audio_config = if cfg!(paravirtualized_devices) {
827 config.audioConfig.as_ref().map(AudioConfig::new)
828 } else {
829 None
830 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900831
Elie Kheirallah29d72912024-08-07 20:17:26 +0000832 let usb_config = config
833 .usbConfig
834 .as_ref()
835 .map(UsbConfig::new)
836 .unwrap_or(Ok(UsbConfig { controller: false }))
837 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
838
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000839 let detect_hangup = is_app_config && gdb_port.is_none();
840
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800841 let custom_memory_backing_files = config
842 .customMemoryBackingFiles
843 .iter()
844 .map(|memory_backing_file| {
845 Ok((
846 clone_file(
847 memory_backing_file
848 .file
849 .as_ref()
850 .context("missing CustomMemoryBackingFile FD")
851 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
852 )?
853 .into(),
854 memory_backing_file.rangeStart as u64,
855 memory_backing_file.size as u64,
856 ))
857 })
858 .collect::<binder::Result<_>>()?;
859
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000860 // Actually start the VM.
861 let crosvm_config = CrosvmConfig {
862 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000863 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000864 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000865 kernel,
866 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000867 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700868 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000869 params: config.params.to_owned(),
870 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900871 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700872 memory_mib: config
873 .memoryMib
874 .try_into()
875 .ok()
876 .and_then(NonZeroU32::new)
877 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800878 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000879 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900880 console_out_fd,
881 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000882 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900883 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000884 indirect_files,
885 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000886 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000887 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900888 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000889 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900890 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900891 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900892 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000893 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900894 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800895 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000896 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700897 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800898 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800899 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000900 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000901 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800902 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
903 instance_id,
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800904 custom_memory_backing_files,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000905 };
906 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100907 VmInstance::new(
908 crosvm_config,
909 temporary_directory,
910 requester_uid,
911 requester_debug_pid,
912 vm_context,
913 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900914 .with_context(|| format!("Failed to create VM with config {:?}", config))
915 .with_log()
916 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000917 );
918 state.add_vm(Arc::downgrade(&instance));
919 Ok(VirtualMachine::create(instance))
920 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900921}
922
Alan Stokesfda70842023-12-20 17:50:14 +0000923/// Returns whether a VM config represents a "custom" virtual machine, which requires the
924/// USE_CUSTOM_VIRTUAL_MACHINE.
925fn is_custom_config(config: &VirtualMachineConfig) -> bool {
926 match config {
927 // Any raw (non-Microdroid) VM is considered custom.
928 VirtualMachineConfig::RawConfig(_) => true,
929 VirtualMachineConfig::AppConfig(config) => {
930 // Some features are reserved for platform apps only, even when using
931 // VirtualMachineAppConfig. Almost all of these features are grouped in the
932 // CustomConfig struct:
933 // - controlling CPUs;
934 // - gdbPort is set, meaning that crosvm will start a gdb server;
935 // - using anything other than the default kernel;
936 // - specifying devices to be assigned.
937 if config.customConfig.is_some() {
938 true
939 } else {
940 // Additional custom features not included in CustomConfig:
941 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000942 // - specifying extra APKs;
943 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900944 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000945 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900946 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
947 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000948 }
949 }
950 }
951}
952
Jiyong Park690c1ca2024-11-28 18:06:50 +0900953/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
954/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
955/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
956/// "microdroid" we run VirtualMachineService
957fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
958 match config {
959 VirtualMachineConfig::AppConfig(_) => true,
960 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
961 }
962}
963
Seungjae Yoo14e60182024-02-21 13:28:31 +0900964fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
965 let VirtualMachineConfig::AppConfig(config) = config else {
966 return Ok(None);
967 };
968 let Some(custom_config) = &config.customConfig else {
969 return Ok(None);
970 };
971 let Some(file) = custom_config.vendorImage.as_ref() else {
972 return Ok(None);
973 };
974
975 let file = clone_file(file)?;
976 let size =
977 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
978 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
979 .context("Failed to get vbmeta from microdroid-vendor.img")?;
980
981 for descriptor in vbmeta.descriptors()?.iter() {
982 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
983 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
984 return Ok(Some(root_digest.as_bytes().to_vec()));
985 }
986 }
987 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
988}
989
Jaewan Kimf43372b2024-12-13 18:33:58 +0900990fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000991 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800992 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000993 temporary_directory: &Path,
994) -> binder::Result<Option<File>> {
995 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
996 // (e.g. instance-id)
997 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
998 let host_ref_dt = if host_ref_dt.exists()
999 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
1000 {
1001 Some(host_ref_dt)
1002 } else {
1003 warn!("VM reference DT doesn't exist in host DT");
1004 None
1005 };
1006
1007 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
1008 .context("Failed to extract vendor hashtree digest")
1009 .or_service_specific_exception(-1)?;
1010
Matt Gilbrideaade4272024-12-05 13:52:42 +00001011 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001012 info!(
1013 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
1014 match the trusted digest in the pvmfw config, causing the VM to fail to start."
1015 );
Alan Stokesf46a17c2025-01-05 15:50:18 +00001016 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001017 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +00001018 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001019 };
1020
Matt Gilbrideaade4272024-12-05 13:52:42 +00001021 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001022 let mut untrusted_props = Vec::with_capacity(2);
1023 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001024 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001025 let want_updatable = extract_want_updatable(config);
1026 if want_updatable && is_secretkeeper_supported() {
1027 // Let guest know that it can defer rollback protection to Secretkeeper by setting
1028 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001029 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001030 let sk: Strong<dyn ISecretkeeper> =
1031 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1032 if sk.getInterfaceVersion()? >= 2 {
1033 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
1034 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001035 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001036 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001037 }
1038 }
1039
1040 let device_tree_overlay = if host_ref_dt.is_some()
1041 || !untrusted_props.is_empty()
1042 || !trusted_props.is_empty()
1043 {
1044 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1045 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1046 let fdt =
1047 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1048 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1049 .or_service_specific_exception(-1)?;
1050 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1051 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1052 } else {
1053 None
1054 };
1055 Ok(device_tree_overlay)
1056}
1057
Jaewan Kimf43372b2024-12-13 18:33:58 +09001058fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1059 let VirtualMachineConfig::RawConfig(config) = config else {
1060 return None;
1061 };
1062 match &config.devices {
1063 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1064 _ => None,
1065 }
1066}
1067
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001068fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001069 let file = OpenOptions::new()
1070 .create_new(true)
1071 .read(true)
1072 .write(true)
1073 .open(zero_filler_path)
1074 .with_context(|| "Failed to create zero.img")?;
1075 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001076 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001077}
1078
David Brazdilf50c7a62023-04-19 14:22:42 +00001079fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1080 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1081 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1082 part.flush()
1083}
1084
1085fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1086 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1087 part.flush()
1088}
1089
1090fn round_up(input: u64, granularity: u64) -> u64 {
1091 if granularity == 0 {
1092 return input;
1093 }
1094 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1095 let result = input.checked_add(granularity - 1).unwrap_or(input);
1096 (result / granularity) * granularity
1097}
1098
Jeongik Chac181be72024-03-27 00:18:30 +09001099fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1100 Ok(match input_device {
1101 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1102 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1103 height: u32::try_from(single_touch.height)?,
1104 width: u32::try_from(single_touch.width)?,
1105 name: if !single_touch.name.is_empty() {
1106 Some(single_touch.name.clone())
1107 } else {
1108 None
1109 },
1110 },
1111 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1112 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1113 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001114 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1115 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1116 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001117 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1118 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1119 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001120 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1121 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1122 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001123 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1124 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1125 height: u32::try_from(trackpad.height)?,
1126 width: u32::try_from(trackpad.width)?,
1127 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1128 },
Jeongik Cha10494912024-07-16 11:19:50 +09001129 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1130 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1131 height: u32::try_from(multi_touch.height)?,
1132 width: u32::try_from(multi_touch.width)?,
1133 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1134 },
Jeongik Chac181be72024-03-27 00:18:30 +09001135 })
1136}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001137
1138fn assemble_shared_paths(
1139 shared_paths: &[SharedPath],
1140 temporary_directory: &Path,
1141) -> Result<Vec<SharedPathConfig>, Status> {
1142 if shared_paths.is_empty() {
1143 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1144 }
1145
1146 shared_paths
1147 .iter()
1148 .map(|path| {
1149 Ok(SharedPathConfig {
1150 path: path.sharedPath.clone(),
1151 host_uid: path.hostUid,
1152 host_gid: path.hostGid,
1153 guest_uid: path.guestUid,
1154 guest_gid: path.guestGid,
1155 mask: path.mask,
1156 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001157 socket_path: temporary_directory
1158 .join(&path.socketPath)
1159 .to_string_lossy()
1160 .to_string(),
1161 socket_fd: maybe_clone_file(&path.socketFd)?,
1162 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001163 })
1164 })
1165 .collect()
1166}
1167
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001168/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1169///
1170/// This may involve assembling a composite disk from a set of partition images.
1171fn assemble_disk_image(
1172 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001173 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001174 temporary_directory: &Path,
1175 next_temporary_image_id: &mut u64,
1176 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001177) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001178 let image = if !disk.partitions.is_empty() {
1179 if disk.image.is_some() {
1180 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001181 return Err(anyhow!("DiskImage contains both image and partitions"))
1182 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001183 }
1184
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001185 let composite_image_filenames =
1186 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1187 let (image, partition_files) = make_composite_image(
1188 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001189 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001190 &composite_image_filenames.composite,
1191 &composite_image_filenames.header,
1192 &composite_image_filenames.footer,
1193 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001194 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1195 .with_log()
1196 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001197
1198 // Pass the file descriptors for the various partition files to crosvm when it
1199 // is run.
1200 indirect_files.extend(partition_files);
1201
1202 image
1203 } else if let Some(image) = &disk.image {
1204 clone_file(image)?
1205 } else {
1206 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001207 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1208 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001209 };
1210
1211 Ok(DiskFile { image, writable: disk.writable })
1212}
1213
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001214fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1215 if let Some(ref mut params) = vm_config.params {
1216 params.push(' ');
1217 params.push_str(param)
1218 } else {
1219 vm_config.params = Some(param.to_owned())
1220 }
1221}
1222
Inseob Kim46257382024-01-03 15:41:22 +09001223fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1224 if config.extension()?.to_str()? != "json" {
1225 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001226 }
Inseob Kim46257382024-01-03 15:41:22 +09001227
1228 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1229}
1230
1231fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1232 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1233 let os_names =
1234 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1235
1236 Ok(os_names)
1237}
1238
1239fn get_supported_os_names() -> Result<HashSet<String>> {
1240 if !cfg!(vendor_modules) {
1241 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1242 }
1243
1244 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1245}
1246
1247fn is_valid_os(os_name: &str) -> bool {
1248 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001249}
1250
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001251fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1252 if !cfg!(vendor_modules) {
1253 return false;
1254 }
1255 match config {
1256 VirtualMachineConfig::RawConfig(_) => false,
1257 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1258 }
1259}
1260
Jooyung Han21e9b922021-06-26 04:14:16 +09001261fn load_app_config(
1262 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001263 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001264 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001265) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001266 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1267 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001268 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001269
Shikha Panwar22e70452022-10-10 18:32:55 +00001270 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1271 Some(clone_file(file)?)
1272 } else {
1273 None
1274 };
1275
Alan Stokesfda70842023-12-20 17:50:14 +00001276 let vm_payload_config;
1277 let extra_apk_files: Vec<_>;
1278 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001279 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001280 vm_payload_config =
1281 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1282 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1283 extra_apk_files = vm_payload_config
1284 .extra_apks
1285 .iter()
1286 .enumerate()
1287 .map(|(i, apk)| {
1288 File::open(PathBuf::from(&apk.path))
1289 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1290 })
1291 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001292 }
Alan Stokesfda70842023-12-20 17:50:14 +00001293 Payload::PayloadConfig(payload_config) => {
1294 vm_payload_config = create_vm_payload_config(payload_config)?;
1295 extra_apk_files =
1296 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1297 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001298 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001299
Inseob Kim89b24592024-02-23 18:59:43 +09001300 let payload_config_os = vm_payload_config.os.name.as_str();
1301 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1302 bail!("'os' in payload config is deprecated");
1303 }
1304
Inseob Kim172f9eb2023-11-06 17:02:08 +09001305 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001306 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001307 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001308 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001309 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001310
1311 // It is safe to construct a filename based on the os_name because we've already checked that it
1312 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001313 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1314 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001315 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001316
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001317 if let Some(custom_config) = &config.customConfig {
1318 if let Some(file) = custom_config.customKernelImage.as_ref() {
1319 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1320 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001321 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001322
1323 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001324 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001325 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001326 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001327
Jaewan Kimf43372b2024-12-13 18:33:58 +09001328 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001329 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001330
1331 for param in custom_config.extraKernelCmdlineParams.iter() {
1332 append_kernel_param(param, &mut vm_config);
1333 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001334
1335 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001336 }
1337
Andrew Walbrancc045902021-07-27 16:06:17 +00001338 if config.memoryMib > 0 {
1339 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001340 }
1341
Chris Wailes6177c662024-05-09 14:37:44 -07001342 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001343 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001344 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001345 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001346 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001347
Shikha Panwar22e70452022-10-10 18:32:55 +00001348 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001349 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001350
1351 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1352 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001353 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001354 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001355 temporary_directory,
1356 apk_file,
1357 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001358 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001359 &vm_payload_config,
1360 &mut vm_config,
1361 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001362
Andrew Walbrancc0db522021-07-12 17:03:42 +00001363 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001364}
1365
Inseob Kime3e932d2024-12-16 20:06:57 +09001366fn check_partition_for_file(fd: &ParcelFileDescriptor, calling_partition: &str) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001367 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1368 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1369
1370 // microdroid vendor image is OK
1371 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1372 {
1373 return Ok(());
1374 }
1375
Inseob Kime3e932d2024-12-16 20:06:57 +09001376 let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm");
1377 let is_caller_vendor = calling_partition == "vendor" || calling_partition == "odm";
1378
1379 if is_fd_vendor != is_caller_vendor {
1380 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001381 }
1382
1383 Ok(())
1384}
1385
Inseob Kime3e932d2024-12-16 20:06:57 +09001386fn check_partitions_for_files(
1387 config: &VirtualMachineRawConfig,
1388 calling_partition: &str,
1389) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001390 config
1391 .disks
1392 .iter()
1393 .flat_map(|disk| disk.partitions.iter())
1394 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001395 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001396
Inseob Kime3e932d2024-12-16 20:06:57 +09001397 config
1398 .disks
1399 .iter()
1400 .filter_map(|disk| disk.image.as_ref())
1401 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1402
1403 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1404 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1405 config
1406 .bootloader
1407 .as_ref()
1408 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001409
1410 Ok(())
1411}
1412
Alan Stokes0d1ef782022-09-27 13:46:35 +01001413fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1414 let mut apk_zip = ZipArchive::new(apk_file)?;
1415 let config_file = apk_zip.by_name(config_path)?;
1416 Ok(serde_json::from_reader(config_file)?)
1417}
1418
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001419fn create_vm_payload_config(
1420 payload_config: &VirtualMachinePayloadConfig,
1421) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001422 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1423 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1424 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001425
1426 let payload_binary_name = &payload_config.payloadBinaryName;
1427 if payload_binary_name.contains('/') {
1428 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1429 }
1430
1431 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001432
1433 // The VM only cares about how many there are, these names are actually ignored.
1434 let extra_apk_count = payload_config.extraApks.len();
1435 let extra_apks =
1436 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1437
Nikita Ioffe901083f2025-01-20 01:54:28 +00001438 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1439 // The only payload delivered via Mainline module in this release requires
1440 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1441 // APIs, so we use the fact that the payload is granted
1442 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1443 // com.android.i18n APEX.
1444 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1445 // Microdroid pVMs.
1446 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1447 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1448 } else {
1449 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1450 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001451}
1452
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001453/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001454fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001455 temporary_directory: &Path,
1456 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001457) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001458 let id = *next_temporary_image_id;
1459 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001460 CompositeImageFilenames {
1461 composite: temporary_directory.join(format!("composite-{}.img", id)),
1462 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1463 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1464 }
1465}
1466
1467/// Filenames for a composite disk image, including header and footer partitions.
1468#[derive(Clone, Debug, Eq, PartialEq)]
1469struct CompositeImageFilenames {
1470 /// The composite disk image itself.
1471 composite: PathBuf,
1472 /// The header partition image.
1473 header: PathBuf,
1474 /// The footer partition image.
1475 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001476}
1477
Jiyong Park753553b2021-07-12 21:21:09 +09001478/// Checks whether the caller has a specific permission
1479fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001480 if cfg!(early) {
1481 // Skip permission check for early VMs, in favor of SELinux
1482 return Ok(());
1483 }
David Brazdil1f530702022-10-03 12:18:10 +01001484 let calling_pid = get_calling_pid();
1485 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001486 // Root can do anything
1487 if calling_uid == 0 {
1488 return Ok(());
1489 }
1490 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001491 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001492 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001493 Ok(())
1494 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001495 Err(anyhow!("does not have the {} permission", perm))
1496 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001497 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001498}
1499
Jiyong Park753553b2021-07-12 21:21:09 +09001500/// Check whether the caller of the current Binder method is allowed to manage VMs
1501fn check_manage_access() -> binder::Result<()> {
1502 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1503}
1504
Inseob Kim1119d702022-05-02 18:01:58 +09001505/// Check whether the caller of the current Binder method is allowed to create custom VMs
1506fn check_use_custom_virtual_machine() -> binder::Result<()> {
1507 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1508}
1509
Nikita Ioffe901083f2025-01-20 01:54:28 +00001510/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1511/// rollback protection schema.
1512fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1513 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1514}
1515
Alan Stokes185fe112023-01-10 16:20:55 +00001516/// Return whether a partition is exempt from selinux label checks, because we know that it does
1517/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001518fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001519 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001520 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001521 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001522 || label == "microdroid-apk-idsig"
1523 || label == "payload-metadata"
1524 || label.starts_with("extra-idsig-")
1525}
1526
Alice Wangc206b9b2023-08-28 14:13:51 +00001527/// Returns whether a partition with the given label is safe for a raw config VM.
1528fn is_safe_raw_partition(label: &str) -> bool {
1529 label == "vm-instance"
1530}
1531
Alan Stokes185fe112023-01-10 16:20:55 +00001532/// Check that a file SELinux label is acceptable.
1533///
1534/// 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 +09001535/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001536///
1537/// Note that sepolicy must also grant read access for these types to both virtualization
1538/// service and crosvm.
1539///
1540/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1541/// user devices (W^X).
1542fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1543 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001544 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001545 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001546 | "staging_data_file" // updated/staged APEX images
1547 | "system_file" // immutable dm-verity protected partition
1548 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001549 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001550 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001551 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001552 }
1553}
1554
Alan Stokes185fe112023-01-10 16:20:55 +00001555fn check_label_for_partition(partition: &Partition) -> Result<()> {
1556 let file = partition.image.as_ref().unwrap().as_ref();
1557 check_label_is_allowed(&getfilecon(file)?)
1558 .with_context(|| format!("Partition {} invalid", &partition.label))
1559}
1560
1561fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1562 if let Some(f) = kernel {
1563 check_label_for_file(f, "kernel")?;
1564 }
1565 if let Some(f) = initrd {
1566 check_label_for_file(f, "initrd")?;
1567 }
1568 Ok(())
1569}
1570fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1571 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1572}
1573
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001574/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1575#[derive(Debug)]
1576struct VirtualMachine {
1577 instance: Arc<VmInstance>,
1578}
1579
1580impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001581 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001582 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001583 }
1584}
1585
1586impl Interface for VirtualMachine {}
1587
Devin Moore407df8f2024-08-27 19:39:16 +00001588impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001589 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001590 // Don't check permission. The owner of the VM might have passed this binder object to
1591 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001592 Ok(self.instance.cid as i32)
1593 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001594
Andrew Walbran6b650662021-09-07 13:13:23 +00001595 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001596 // Don't check permission. The owner of the VM might have passed this binder object to
1597 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001598 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001599 }
1600
1601 fn registerCallback(
1602 &self,
1603 callback: &Strong<dyn IVirtualMachineCallback>,
1604 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001605 // Don't check permission. The owner of the VM might have passed this binder object to
1606 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001607
1608 // Only register callback if it may be notified.
1609 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1610 let vm_state = self.instance.vm_state.lock().unwrap();
1611 if matches!(*vm_state, VmState::Dead) {
1612 warn!("Ignoring registerCallback() after VM is died");
1613 } else {
1614 self.instance.callbacks.add(callback.clone());
1615 }
1616 drop(vm_state);
1617
Andrew Walbrandae07162021-03-12 17:05:20 +00001618 Ok(())
1619 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001620
Andrew Walbranf8d94112021-09-07 11:45:36 +00001621 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001622 self.instance
1623 .start()
1624 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1625 .with_log()
1626 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001627 }
1628
Inseob Kima446f802022-07-11 19:46:37 +09001629 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001630 self.instance
1631 .kill()
1632 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1633 .with_log()
1634 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001635 }
1636
Keir Fraser48221ba2024-07-12 14:05:02 +00001637 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1638 let balloon = self
1639 .instance
1640 .get_memory_balloon()
1641 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1642 .with_log()
1643 .or_service_specific_exception(-1)?;
1644 Ok(balloon.try_into().unwrap())
1645 }
1646
1647 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001648 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001649 .set_memory_balloon(num_bytes.try_into().unwrap())
1650 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001651 .with_log()
1652 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001653 }
1654
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001655 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001656 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001657 return Err(Status::new_service_specific_error_str(
1658 IVirtualMachine::ERROR_UNEXPECTED,
1659 Some("Virtual Machine is not running"),
1660 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001661 }
Alan Stokes10c47672022-12-13 17:17:08 +00001662 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001663 if port < VSOCK_PRIV_PORT_MAX {
1664 return Err(Status::new_service_specific_error_str(
1665 IVirtualMachine::ERROR_UNEXPECTED,
1666 Some("Can't connect to privileged port {port}"),
1667 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001668 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001669 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1670 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001671 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001672 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001673 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001674
Devin Moore407df8f2024-08-27 19:39:16 +00001675 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1676 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1677 return Err(Status::new_service_specific_error_str(
1678 IVirtualMachine::ERROR_UNEXPECTED,
1679 Some("Virtual Machine is not running"),
1680 ));
1681 }
1682 let port = port as u32;
1683 if port < VSOCK_PRIV_PORT_MAX {
1684 return Err(Status::new_service_specific_error_str(
1685 IVirtualMachine::ERROR_UNEXPECTED,
1686 Some("Can't connect to privileged port {port}"),
1687 ));
1688 }
1689 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001690 let addr = sockaddr_vm {
1691 svm_family: AF_VSOCK as sa_family_t,
1692 svm_reserved1: 0,
1693 svm_port: port,
1694 svm_cid: cid,
1695 svm_zero: [0u8; 4],
1696 };
1697 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001698 let accessor = Accessor::new(name, get_connection_info);
1699 accessor
1700 .as_binder()
1701 .context("The newly created Accessor should always have a binder")
1702 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1703 }
1704
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001705 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1706 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1707 }
Jiyong Park23b67392024-07-04 13:51:42 +09001708
1709 fn suspend(&self) -> binder::Result<()> {
1710 self.instance
1711 .suspend()
1712 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1713 .with_log()
1714 .or_service_specific_exception(-1)
1715 }
1716
1717 fn resume(&self) -> binder::Result<()> {
1718 self.instance
1719 .resume()
1720 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1721 .with_log()
1722 .or_service_specific_exception(-1)
1723 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001724}
1725
1726impl Drop for VirtualMachine {
1727 fn drop(&mut self) {
1728 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001729 if let Err(e) = self.instance.kill() {
1730 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1731 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001732 }
1733}
1734
1735/// A set of Binders to be called back in response to various events on the VM, such as when it
1736/// dies.
1737#[derive(Debug, Default)]
1738pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1739
1740impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001741 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001742 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001743 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001744 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001745 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001746 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001747 }
1748 }
1749 }
1750
Inseob Kim14cb8692021-08-31 21:50:39 +09001751 /// Call all registered callbacks to notify that the payload is ready to serve.
1752 pub fn notify_payload_ready(&self, cid: Cid) {
1753 let callbacks = &*self.0.lock().unwrap();
1754 for callback in callbacks {
1755 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001756 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001757 }
1758 }
1759 }
1760
Inseob Kim2444af92021-08-31 01:22:50 +09001761 /// Call all registered callbacks to notify that the payload has finished.
1762 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1763 let callbacks = &*self.0.lock().unwrap();
1764 for callback in callbacks {
1765 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001766 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001767 }
1768 }
1769 }
1770
Jooyung Handd0a1732021-11-23 15:26:20 +09001771 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001772 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001773 let callbacks = &*self.0.lock().unwrap();
1774 for callback in callbacks {
1775 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001776 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001777 }
1778 }
1779 }
1780
Andrew Walbrandae07162021-03-12 17:05:20 +00001781 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001782 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001783 let mut callbacks = self.0.lock().unwrap();
1784 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001785 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001786 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001787 }
1788 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001789
1790 // Nothing to notify afterward because VM cannot be restarted.
1791 // Explicitly clear callbacks to prevent potential cyclic references
1792 // between callback and VmInstance.
1793 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001794 }
1795
1796 /// Add a new callback to the set.
1797 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1798 self.0.lock().unwrap().push(callback);
1799 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001800}
1801
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001802/// The mutable state of the VirtualizationService. There should only be one instance of this
1803/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001804#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001805struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001806 /// The VMs which have been started. When VMs are started a weak reference is added to this
1807 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1808 /// the Binder client are dropped the weak reference here will become invalid, and will be
1809 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001810 vms: Vec<Weak<VmInstance>>,
1811}
1812
1813impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001814 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001815 fn vms(&self) -> Vec<Arc<VmInstance>> {
1816 // Attempt to upgrade the weak pointers to strong pointers.
1817 self.vms.iter().filter_map(Weak::upgrade).collect()
1818 }
1819
1820 /// Add a new VM to the list.
1821 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1822 // Garbage collect any entries from the stored list which no longer exist.
1823 self.vms.retain(|vm| vm.strong_count() > 0);
1824
1825 // Actually add the new VM.
1826 self.vms.push(vm);
1827 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001828
Jiyong Park8611a6c2021-07-09 18:17:44 +09001829 /// Get a VM that corresponds to the given cid
1830 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1831 self.vms().into_iter().find(|vm| vm.cid == cid)
1832 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001833}
1834
Andrew Walbran6b650662021-09-07 13:13:23 +00001835/// Gets the `VirtualMachineState` of the given `VmInstance`.
1836fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001837 match &*instance.vm_state.lock().unwrap() {
1838 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1839 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001840 PayloadState::Starting => VirtualMachineState::STARTING,
1841 PayloadState::Started => VirtualMachineState::STARTED,
1842 PayloadState::Ready => VirtualMachineState::READY,
1843 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001844 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001845 },
1846 VmState::Dead => VirtualMachineState::DEAD,
1847 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001848 }
1849}
1850
David Brazdilf50c7a62023-04-19 14:22:42 +00001851/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001852pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1853 file.as_ref()
1854 .try_clone()
1855 .context("Failed to clone File from ParcelFileDescriptor")
1856 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001857 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001858}
1859
Andrew Walbrand3a84182021-09-07 14:48:52 +00001860/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001861fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001862 file.as_ref().map(clone_file).transpose()
1863}
1864
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001865/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001866fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1867 // SAFETY: ownership is transferred from stream to f
1868 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1869 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001870}
1871
Jiyong Parkdcf17412022-02-08 15:07:23 +09001872/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001873fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1874 VersionReq::parse(s)
1875 .with_context(|| format!("Invalid platform version requirement {}", s))
1876 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001877}
1878
Jiyong Parked180932023-02-24 19:55:41 +09001879/// Create the empty ramdump file
1880fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1881 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1882 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1883 // owner) for readout.
1884 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001885 let ramdump = File::create(ramdump_path)
1886 .context("Failed to prepare ramdump file")
1887 .with_log()
1888 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001889 Ok(ramdump)
1890}
1891
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001892/// Create the empty device tree dump file
1893fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1894 let path = temporary_directory.join("device_tree.dtb");
1895 let file = File::create(path)
1896 .context("Failed to prepare device tree dump file")
1897 .with_log()
1898 .or_service_specific_exception(-1)?;
1899 Ok(file)
1900}
1901
Nikita Ioffe5776f082023-02-10 21:38:26 +00001902fn is_protected(config: &VirtualMachineConfig) -> bool {
1903 match config {
1904 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1905 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1906 }
1907}
1908
1909fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1910 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001911 return Err(anyhow!("Can't use gdb with protected VMs"))
1912 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001913 }
1914
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001915 if get_debug_level(config) == Some(DebugLevel::NONE) {
1916 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1917 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001918 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001919
1920 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001921}
1922
Shikha Panwar61a74b52024-02-16 13:17:01 +00001923fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1924 match config {
1925 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1926 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1927 }
1928}
1929
Alan Stokesc96b35e2024-05-03 13:21:20 +01001930fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1931 match config {
1932 VirtualMachineConfig::RawConfig(_) => true,
1933 VirtualMachineConfig::AppConfig(config) => {
1934 let Some(custom) = &config.customConfig else { return true };
1935 custom.wantUpdatable
1936 }
1937 }
1938}
1939
Nikita Ioffe5776f082023-02-10 21:38:26 +00001940fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1941 match config {
1942 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001943 VirtualMachineConfig::AppConfig(config) => {
1944 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1945 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001946 }
1947}
1948
Nikita Ioffe631717e2023-09-05 13:38:07 +01001949fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1950 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1951 if let Some(custom_config) = &config.customConfig {
1952 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1953 return Err(anyhow!("vendor modules feature is disabled"))
1954 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1955 }
1956 }
1957 Ok(())
1958}
1959
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001960fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1961 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1962 if let Some(custom_config) = &config.customConfig {
1963 if !custom_config.devices.is_empty() {
1964 return Err(anyhow!("device assignment feature is disabled"))
1965 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1966 }
1967 }
1968 Ok(())
1969}
1970
Alan Stokesfda70842023-12-20 17:50:14 +00001971fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1972 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1973 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1974 if !payload_config.extraApks.is_empty() {
1975 return Err(anyhow!("multi-tenant feature is disabled"))
1976 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1977 }
1978 Ok(())
1979}
1980
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001981fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1982 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1983 if let Some(custom_config) = &config.customConfig {
1984 if !custom_config.extraKernelCmdlineParams.is_empty() {
1985 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1986 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1987 }
1988 }
1989 Ok(())
1990}
1991
Nikita Ioffe99548382024-10-21 15:54:46 +00001992fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1993 match config {
1994 VirtualMachineConfig::RawConfig(config) => {
1995 if !config.teeServices.is_empty() {
1996 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1997 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1998 }
1999 }
2000 VirtualMachineConfig::AppConfig(config) => {
2001 if let Some(custom_config) = &config.customConfig {
2002 if !custom_config.teeServices.is_empty() {
2003 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2004 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2005 }
2006 }
2007 }
2008 };
2009 Ok(())
2010}
2011
Nikita Ioffef934e812024-07-05 15:44:41 +00002012fn check_protected_vm_is_supported() -> binder::Result<()> {
2013 let is_pvm_supported =
2014 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
2015 if is_pvm_supported {
2016 Ok(())
2017 } else {
2018 Err(anyhow!("pVM is not supported"))
2019 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
2020 }
2021}
2022
Nikita Ioffe631717e2023-09-05 13:38:07 +01002023fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
2024 if !cfg!(vendor_modules) {
2025 check_no_vendor_modules(config)?;
2026 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002027 if !cfg!(device_assignment) {
2028 check_no_devices(config)?;
2029 }
Alan Stokesfda70842023-12-20 17:50:14 +00002030 if !cfg!(multi_tenant) {
2031 check_no_extra_apks(config)?;
2032 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002033 if !cfg!(debuggable_vms_improvements) {
2034 check_no_extra_kernel_cmdline_params(config)?;
2035 }
Nikita Ioffe99548382024-10-21 15:54:46 +00002036 if !cfg!(tee_services_allowlist) {
2037 check_no_tee_services(config)?;
2038 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002039 Ok(())
2040}
2041
Inseob Kimecde8c02024-09-03 13:11:08 +09002042fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2043 check_no_vendor_modules(config)?;
2044 check_no_devices(config)?;
2045
2046 Ok(())
2047}
2048
Inseob Kim0168b462022-12-27 14:54:35 +09002049fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002050 fd: Option<&ParcelFileDescriptor>,
2051 tag: String,
2052) -> Result<Option<File>, Status> {
2053 if let Some(fd) = fd {
2054 return Ok(Some(clone_file(fd)?));
2055 }
2056
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002057 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002058 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002059
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002060 let mut reader = BufReader::new(File::from(read_fd));
2061 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002062
Frederick Mayle26e41af2025-02-05 18:30:29 -08002063 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002064 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002065 buf.clear();
2066 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002067 match reader.read_until(b'\n', &mut buf) {
2068 Ok(0) => {
2069 // EOF
2070 return;
2071 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002072 Ok(_size) => {
2073 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002074 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002075 // Logs sent via TTY usually end lines with "\r\n".
2076 if buf.last() == Some(&b'\r') {
2077 buf.pop();
2078 }
Inseob Kim0168b462022-12-27 14:54:35 +09002079 }
2080 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2081 }
2082 Err(e) => {
2083 error!("Could not read console pipe: {:?}", e);
2084 return;
2085 }
2086 };
2087 });
2088
2089 Ok(Some(write_fd))
2090}
2091
Jooyung Han35edb8f2021-07-01 16:17:16 +09002092/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2093/// it doesn't require that T implements Clone.
2094enum BorrowedOrOwned<'a, T> {
2095 Borrowed(&'a T),
2096 Owned(T),
2097}
2098
Chris Wailes73a1eb72025-01-15 11:56:43 -08002099impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002100 fn as_ref(&self) -> &T {
2101 match self {
2102 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002103 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002104 }
2105 }
2106}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002107
2108/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2109#[derive(Debug, Default)]
2110struct VirtualMachineService {
2111 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002112 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002113}
2114
2115impl Interface for VirtualMachineService {}
2116
2117impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002118 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2119 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002120 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002121 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002122 vm.update_payload_state(PayloadState::Started)
2123 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002124 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002125
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002126 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2127 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002128 Ok(())
2129 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002130 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002131 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002132 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002133 }
Inseob Kim2444af92021-08-31 01:22:50 +09002134
Inseob Kimc7d28c72021-10-25 14:28:10 +00002135 fn notifyPayloadReady(&self) -> binder::Result<()> {
2136 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002137 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002138 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002139 vm.update_payload_state(PayloadState::Ready)
2140 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002141 vm.callbacks.notify_payload_ready(cid);
2142 Ok(())
2143 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002144 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002145 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002146 }
2147 }
2148
Inseob Kimc7d28c72021-10-25 14:28:10 +00002149 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2150 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002151 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002152 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002153 vm.update_payload_state(PayloadState::Finished)
2154 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002155 vm.callbacks.notify_payload_finished(cid, exit_code);
2156 Ok(())
2157 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002158 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002159 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002160 }
2161 }
2162
Alan Stokes2bead0d2022-09-05 16:58:34 +01002163 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002164 let cid = self.cid;
2165 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002166 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002167 vm.update_payload_state(PayloadState::Finished)
2168 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002169 vm.callbacks.notify_error(cid, error_code, message);
2170 Ok(())
2171 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002172 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002173 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002174 }
2175 }
Alice Wangc2fec932023-02-23 16:24:02 +00002176
Shikha Panware45e9422024-02-28 21:18:10 +00002177 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2178 if !is_secretkeeper_supported() {
2179 return Err(StatusCode::NAME_NOT_FOUND)?;
2180 }
2181 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2182 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002183 }
2184
Alice Wange64dd182024-01-17 15:57:55 +00002185 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2186 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002187 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002188}
2189
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002190fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002191 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2192 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002193}
2194
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002195impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002196 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002197 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002198 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002199 BinderFeatures::default(),
2200 )
2201 }
2202}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002203
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002204struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2205
2206impl Interface for SecretkeeperProxy {}
2207
2208impl ISecretkeeper for SecretkeeperProxy {
2209 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2210 // Pass the request to the channel, and read the response.
2211 self.0.processSecretManagementRequest(req)
2212 }
2213
2214 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2215 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2216 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2217 }
2218
2219 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2220 self.0.deleteIds(ids)
2221 }
2222
2223 fn deleteAll(&self) -> binder::Result<()> {
2224 self.0.deleteAll()
2225 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002226
2227 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2228 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2229 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2230 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2231 // use this API from the proxy.
2232 Err(ExceptionCode::SECURITY.into())
2233 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002234}
2235
2236struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2237
2238impl Interface for AuthGraphKeyExchangeProxy {}
2239
2240impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2241 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2242 self.0.create()
2243 }
2244
2245 fn init(
2246 &self,
2247 peer_pub_key: &PubKey,
2248 peer_id: &Identity,
2249 peer_nonce: &[u8],
2250 peer_version: i32,
2251 ) -> binder::Result<KeInitResult> {
2252 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2253 }
2254
2255 fn finish(
2256 &self,
2257 peer_pub_key: &PubKey,
2258 peer_id: &Identity,
2259 peer_signature: &SessionIdSignature,
2260 peer_nonce: &[u8],
2261 peer_version: i32,
2262 own_key: &Key,
2263 ) -> binder::Result<SessionInfo> {
2264 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2265 }
2266
2267 fn authenticationComplete(
2268 &self,
2269 peer_signature: &SessionIdSignature,
2270 shared_keys: &[AuthgraphArc; 2],
2271 ) -> binder::Result<[AuthgraphArc; 2]> {
2272 self.0.authenticationComplete(peer_signature, shared_keys)
2273 }
2274}
2275
Inseob Kimecde8c02024-09-03 13:11:08 +09002276// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002277#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002278struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002279 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002280 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002281 path: String,
2282}
2283
2284#[derive(Debug, Default, Deserialize)]
2285struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002286 early_vm: Vec<EarlyVm>,
2287}
2288
Inseob Kim7e1877b2024-11-07 17:28:56 +09002289static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2290 LazyLock::new(|| Mutex::new(HashMap::new()));
2291
Inseob Kimecde8c02024-09-03 13:11:08 +09002292fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2293 match partition {
2294 "system" => Ok(100..200),
2295 "system_ext" | "product" => Ok(200..300),
Inseob Kime3e932d2024-12-16 20:06:57 +09002296 "vendor" | "odm" => Ok(300..400),
Inseob Kimecde8c02024-09-03 13:11:08 +09002297 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2298 }
2299}
2300
Inseob Kim7e1877b2024-11-07 17:28:56 +09002301fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002302 if !xml_path.exists() {
2303 bail!("{} doesn't exist", xml_path.display());
2304 }
2305
2306 let xml =
2307 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2308 let xml = String::from_utf8(xml)
2309 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2310 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2311 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2312
Inseob Kim7e1877b2024-11-07 17:28:56 +09002313 Ok(early_vms.early_vm)
2314}
Inseob Kimecde8c02024-09-03 13:11:08 +09002315
Inseob Kim7e1877b2024-11-07 17:28:56 +09002316fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2317 for early_vm in early_vms {
2318 let cid = early_vm
2319 .cid
2320 .try_into()
2321 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2322
2323 ensure!(
2324 cid_range.contains(&cid),
2325 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2326 early_vm.name
2327 );
2328 }
2329 Ok(())
2330}
2331
2332fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2333 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2334
2335 if let Some(result) = cache.get(partition) {
2336 return Ok(result.clone());
2337 }
2338
2339 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2340 let mut early_vms = Vec::new();
2341 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2342 match entry {
2343 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2344 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2345 }
2346 }
2347
2348 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2349 .with_context(|| format!("CID validation for {partition} failed"))?;
2350
2351 cache.insert(partition.to_owned(), early_vms.clone());
2352
2353 Ok(early_vms)
2354}
2355
2356fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2357 let mut found_vm: Option<&EarlyVm> = None;
2358
2359 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002360 if early_vm.name != name {
2361 continue;
2362 }
2363
Inseob Kimecde8c02024-09-03 13:11:08 +09002364 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002365 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002366 }
2367
2368 found_vm = Some(early_vm);
2369 }
2370
Inseob Kim7e1877b2024-11-07 17:28:56 +09002371 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002372}
2373
2374fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002375 let early_vms = get_early_vms_in_partition(partition)
2376 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2377
2378 Ok(find_early_vm(&early_vms, name)
2379 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2380 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002381}
2382
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002383#[cfg(test)]
2384mod tests {
2385 use super::*;
2386
2387 #[test]
2388 fn test_is_allowed_label_for_partition() -> Result<()> {
2389 let expected_results = vec![
2390 ("u:object_r:system_file:s0", true),
2391 ("u:object_r:apk_data_file:s0", true),
2392 ("u:object_r:app_data_file:s0", false),
2393 ("u:object_r:app_data_file:s0:c512,c768", false),
2394 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2395 ("invalid", false),
2396 ("user:role:apk_data_file:severity:categories", true),
2397 ("user:role:apk_data_file:severity:categories:extraneous", false),
2398 ];
2399
2400 for (label, expected_valid) in expected_results {
2401 let context = SeContext::new(label)?;
2402 let result = check_label_is_allowed(&context);
2403 if expected_valid {
2404 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2405 } else if result.is_ok() {
2406 bail!("Expected label {} to be disallowed", label);
2407 }
2408 }
2409 Ok(())
2410 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002411
2412 #[test]
2413 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2414 let apk = tempfile::tempfile().unwrap();
2415 let idsig = tempfile::tempfile().unwrap();
2416
2417 let ret = create_or_update_idsig_file(
2418 &ParcelFileDescriptor::new(apk),
2419 &ParcelFileDescriptor::new(idsig),
2420 );
2421 assert!(ret.is_err(), "should fail");
2422 Ok(())
2423 }
2424
2425 #[test]
2426 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2427 let tmp_dir = tempfile::TempDir::new().unwrap();
2428 let apk = File::open(tmp_dir.path()).unwrap();
2429 let idsig = tempfile::tempfile().unwrap();
2430
2431 let ret = create_or_update_idsig_file(
2432 &ParcelFileDescriptor::new(apk),
2433 &ParcelFileDescriptor::new(idsig),
2434 );
2435 assert!(ret.is_err(), "should fail");
2436 Ok(())
2437 }
2438
2439 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2440 /// on ext4 filesystem is passed.
2441 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2442 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2443 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2444 #[test]
2445 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2446 // APEXes are backed by the ext4.
2447 let apk = File::open("/apex/com.android.virt/").unwrap();
2448 let idsig = tempfile::tempfile().unwrap();
2449
2450 let ret = create_or_update_idsig_file(
2451 &ParcelFileDescriptor::new(apk),
2452 &ParcelFileDescriptor::new(idsig),
2453 );
2454 assert!(ret.is_err(), "should fail");
2455 Ok(())
2456 }
Jiyong Park8d192952023-06-26 14:29:51 +09002457
2458 #[test]
2459 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2460 use std::io::Seek;
2461
2462 // Pick any APK
2463 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2464 let mut idsig = tempfile::tempfile().unwrap();
2465
2466 create_or_update_idsig_file(
2467 &ParcelFileDescriptor::new(apk.try_clone()?),
2468 &ParcelFileDescriptor::new(idsig.try_clone()?),
2469 )?;
2470 let modified_orig = idsig.metadata()?.modified()?;
2471 apk.rewind()?;
2472 idsig.rewind()?;
2473
2474 // Call the function again
2475 create_or_update_idsig_file(
2476 &ParcelFileDescriptor::new(apk.try_clone()?),
2477 &ParcelFileDescriptor::new(idsig.try_clone()?),
2478 )?;
2479 let modified_new = idsig.metadata()?.modified()?;
2480 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2481 Ok(())
2482 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002483
2484 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002485 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2486 use std::io::Read;
2487
2488 // Pick any APK
2489 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2490 let idsig_empty = tempfile::tempfile().unwrap();
2491 let mut idsig_invalid = tempfile::tempfile().unwrap();
2492 idsig_invalid.write_all(b"Oops")?;
2493
2494 // Create new idsig
2495 create_or_update_idsig_file(
2496 &ParcelFileDescriptor::new(apk.try_clone()?),
2497 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2498 )?;
2499 apk.rewind()?;
2500
2501 // Update idsig_invalid
2502 create_or_update_idsig_file(
2503 &ParcelFileDescriptor::new(apk.try_clone()?),
2504 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2505 )?;
2506
2507 // Ensure the 2 idsig files have same size!
2508 assert!(
2509 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2510 "idsig files differ in size"
2511 );
2512 // Ensure the 2 idsig files have same content!
2513 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2514 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2515 }
2516 Ok(())
2517 }
2518 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002519 fn test_append_kernel_param_first_param() {
2520 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2521 append_kernel_param("foo=1", &mut vm_config);
2522 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2523 }
2524
2525 #[test]
2526 fn test_append_kernel_param() {
2527 let mut vm_config =
2528 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2529 append_kernel_param("bar=42", &mut vm_config);
2530 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2531 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002532
Inseob Kim46257382024-01-03 15:41:22 +09002533 fn test_extract_os_name_from_config_path(
2534 path: &Path,
2535 expected_result: Option<&str>,
2536 ) -> Result<()> {
2537 let result = extract_os_name_from_config_path(path);
2538 if result.as_deref() != expected_result {
2539 bail!("Expected {:?} but was {:?}", expected_result, &result)
2540 }
2541 Ok(())
2542 }
2543
2544 #[test]
2545 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2546 test_extract_os_name_from_config_path(
2547 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2548 Some("microdroid"),
2549 )
2550 }
2551
2552 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002553 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2554 test_extract_os_name_from_config_path(
2555 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2556 Some("microdroid_16k"),
2557 )
2558 }
2559
2560 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002561 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2562 test_extract_os_name_from_config_path(
2563 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2564 Some("microdroid_gki-android14-6.1"),
2565 )
2566 }
2567
2568 #[test]
2569 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2570 test_extract_os_name_from_config_path(
2571 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2572 None,
2573 )
2574 }
2575
2576 #[test]
2577 fn test_extract_os_name_from_configs() -> Result<()> {
2578 let tmp_dir = tempfile::TempDir::new()?;
2579 let tmp_dir_path = tmp_dir.path().to_owned();
2580
2581 let mut os_names: HashSet<String> = HashSet::new();
2582 os_names.insert("microdroid".to_owned());
2583 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2584 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2585
2586 // config files
2587 for os_name in &os_names {
2588 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2589 }
2590
2591 // fake files not related to configs
2592 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2593 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2594
2595 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2596 Some(s) => s.to_owned(),
2597 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2598 };
2599
2600 let result = extract_os_names_from_configs(&glob_pattern)?;
2601 if result != os_names {
2602 bail!("Expected {:?} but was {:?}", os_names, result);
2603 }
2604 Ok(())
2605 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002606
2607 #[test]
2608 fn test_find_early_vms_from_xml() -> Result<()> {
2609 let tmp_dir = tempfile::TempDir::new()?;
2610 let tmp_dir_path = tmp_dir.path().to_owned();
2611 let xml_path = tmp_dir_path.join("early_vms.xml");
2612
2613 std::fs::write(
2614 &xml_path,
2615 br#"<?xml version="1.0" encoding="utf-8"?>
2616 <early_vms>
2617 <early_vm>
2618 <name>vm_demo_native_early</name>
2619 <cid>123</cid>
2620 <path>/system/bin/vm_demo_native_early</path>
2621 </early_vm>
2622 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002623 <name>vm_demo_native_early_2</name>
2624 <cid>456</cid>
2625 <path>/system/bin/vm_demo_native_early_2</path>
2626 </early_vm>
2627 </early_vms>
2628 "#,
2629 )?;
2630
2631 let cid_range = 100..1000;
2632
2633 let early_vms = get_early_vms_in_path(&xml_path)?;
2634 validate_cid_range(&early_vms, &cid_range)?;
2635
2636 let test_cases = [
2637 (
2638 "vm_demo_native_early",
2639 EarlyVm {
2640 name: "vm_demo_native_early".to_owned(),
2641 cid: 123,
2642 path: "/system/bin/vm_demo_native_early".to_owned(),
2643 },
2644 ),
2645 (
2646 "vm_demo_native_early_2",
2647 EarlyVm {
2648 name: "vm_demo_native_early_2".to_owned(),
2649 cid: 456,
2650 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2651 },
2652 ),
2653 ];
2654
2655 for (name, expected) in test_cases {
2656 let result = find_early_vm(&early_vms, name)?;
2657 assert_eq!(result, &expected);
2658 }
2659
2660 Ok(())
2661 }
2662
2663 #[test]
2664 fn test_invalid_cid_validation() -> Result<()> {
2665 let tmp_dir = tempfile::TempDir::new()?;
2666 let xml_path = tmp_dir.path().join("early_vms.xml");
2667
2668 let cid_range = 100..1000;
2669
2670 for cid in [-1, 999999] {
2671 std::fs::write(
2672 &xml_path,
2673 format!(
2674 r#"<?xml version="1.0" encoding="utf-8"?>
2675 <early_vms>
2676 <early_vm>
2677 <name>vm_demo_invalid_cid</name>
2678 <cid>{cid}</cid>
2679 <path>/system/bin/vm_demo_invalid_cid</path>
2680 </early_vm>
2681 </early_vms>
2682 "#
2683 ),
2684 )?;
2685
2686 let early_vms = get_early_vms_in_path(&xml_path)?;
2687 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2688 }
2689
2690 Ok(())
2691 }
2692
2693 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002694 fn test_symlink_to_system_ext_supported() -> Result<()> {
2695 let link_path = Path::new("/system/system_ext/file");
2696 let partition = find_partition(Some(link_path)).unwrap();
2697 assert_eq!("system_ext", partition);
2698 Ok(())
2699 }
2700
2701 #[test]
2702 fn test_symlink_to_product_supported() -> Result<()> {
2703 let link_path = Path::new("/system/product/file");
2704 let partition = find_partition(Some(link_path)).unwrap();
2705 assert_eq!("product", partition);
2706 Ok(())
2707 }
2708
2709 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002710 fn test_duplicated_early_vms() -> Result<()> {
2711 let tmp_dir = tempfile::TempDir::new()?;
2712 let tmp_dir_path = tmp_dir.path().to_owned();
2713 let xml_path = tmp_dir_path.join("early_vms.xml");
2714
2715 std::fs::write(
2716 &xml_path,
2717 br#"<?xml version="1.0" encoding="utf-8"?>
2718 <early_vms>
2719 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002720 <name>vm_demo_duplicated_name</name>
2721 <cid>456</cid>
2722 <path>/system/bin/vm_demo_duplicated_name_1</path>
2723 </early_vm>
2724 <early_vm>
2725 <name>vm_demo_duplicated_name</name>
2726 <cid>789</cid>
2727 <path>/system/bin/vm_demo_duplicated_name_2</path>
2728 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002729 </early_vms>
2730 "#,
2731 )?;
2732
2733 let cid_range = 100..1000;
2734
Inseob Kim7e1877b2024-11-07 17:28:56 +09002735 let early_vms = get_early_vms_in_path(&xml_path)?;
2736 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002737
Inseob Kim7e1877b2024-11-07 17:28:56 +09002738 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002739
2740 Ok(())
2741 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002742}