blob: cc6141e5cdb7f046b41b93eb886a8fd820fdd9a0 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Seungjae Yoo13af0b62024-05-20 14:15:13 +090017use crate::{get_calling_pid, get_calling_uid, get_this_pid};
Alan Stokesfda70842023-12-20 17:50:14 +000018use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use crate::composite::make_composite_image;
Akilesh Kailash05515dc2024-10-22 21:42:52 -070020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, SharedPathConfig, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
Jaewan Kimabd328b2024-12-10 15:59:33 +090021use crate::debug_config::{DebugConfig, DebugPolicy};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Inseob Kimf79c5722024-12-16 17:29:57 +090023use crate::payload::{ApexInfoList, add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Nikita Ioffe13748d22024-10-23 15:10:39 +000024use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Jaewan Kimf43372b2024-12-13 18:33:58 +090032 AssignedDevices::AssignedDevices,
Inseob Kim53d0b212023-07-20 16:58:37 +090033 AssignableDevice::AssignableDevice,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Akilesh Kailash05515dc2024-10-22 21:42:52 -070035 SharedPath::SharedPath,
Jeongik Chac181be72024-03-27 00:18:30 +090036 InputDevice::InputDevice,
Devin Moore407df8f2024-08-27 19:39:16 +000037 IVirtualMachine::{self, BnVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000038 IVirtualMachineCallback::IVirtualMachineCallback,
39 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090040 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000041 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090042 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090043 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000044 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010045 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090046 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000047 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090048};
Inseob Kimecde8c02024-09-03 13:11:08 +090049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000052 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053};
Shikha Panware45e9422024-02-28 21:18:10 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +000056use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000057use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
58 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
59 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
60 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
61 SessionInitiationInfo::SessionInitiationInfo,
62};
Inseob Kim7e1877b2024-11-07 17:28:56 +090063use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090065use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010066use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000067 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
68 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000069};
Inseob Kim46257382024-01-03 15:41:22 +090070use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000071use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000072use log::{debug, error, info, warn};
Nikita Ioffe901083f2025-01-20 01:54:28 +000073use microdroid_payload_config::{ApexConfig, ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090074use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000075use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000076use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090077use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090078use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090079use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000080use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000081use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090082use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090083use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000084use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090085use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000086use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090087use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090088use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000089use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010091use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090092use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010093use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000094use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090095use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096
David Brazdil41d1a872022-10-05 14:44:19 +010097/// The unique ID of a VM used (together with a port number) for vsock communication.
98pub type Cid = u32;
99
David Brazdil4b4c5102022-12-19 22:56:20 +0000100pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
101
Devin Moore407df8f2024-08-27 19:39:16 +0000102/// Vsock privileged ports are below this number.
103const VSOCK_PRIV_PORT_MAX: u32 = 1024;
104
Jooyung Han95884632021-07-06 22:27:54 +0900105/// The size of zero.img.
106/// Gaps in composite disk images are filled with a shared zero.img.
107const ZERO_FILLER_SIZE: u64 = 4096;
108
David Brazdilf50c7a62023-04-19 14:22:42 +0000109/// Magic string for the instance image
110const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
111
112/// Version of the instance image format
113const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
114
Alan Stokes0d1ef782022-09-27 13:46:35 +0100115const MICRODROID_OS_NAME: &str = "microdroid";
116
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000117const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000118 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000119
David Brazdilf50c7a62023-04-19 14:22:42 +0000120const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
121
122/// crosvm requires all partitions to be a multiple of 4KiB.
123const PARTITION_GRANULARITY_BYTES: u64 = 4096;
124
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000125const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
126
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100127pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
128 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900129 if cfg!(early) {
130 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
131 } else {
132 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
133 .expect("Could not connect to VirtualizationServiceInternal")
134 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100135 });
136static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
137 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000138
Inseob Kime3e932d2024-12-16 20:06:57 +0900139static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
140 let calling_exe_link = format!("/proc/{}/exe", get_calling_pid());
141 match fs::read_link(&calling_exe_link) {
142 Ok(calling_exe_path) => Some(calling_exe_path),
143 Err(e) => {
144 // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we
145 // discourage vendor apps, regarding such cases as system is safer.
146 // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of
147 // apps.
148 warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system");
149 None
150 }
151 }
152});
153
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000154fn create_or_update_idsig_file(
155 input_fd: &ParcelFileDescriptor,
156 idsig_fd: &ParcelFileDescriptor,
157) -> Result<()> {
158 let mut input = clone_file(input_fd)?;
159 let metadata = input.metadata().context("failed to get input metadata")?;
160 if !metadata.is_file() {
161 bail!("input is not a regular file");
162 }
Alan Stokes25f69362023-03-06 16:51:54 +0000163 let mut sig =
164 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
165 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000166
167 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900168
169 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
170 // if the idsig file already has the same APK digest.
171 if output.metadata()?.len() > 0 {
172 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
173 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
174 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
175 return Ok(());
176 }
177 }
178 // if we fail to read v4signature from output, that's fine. User can pass a random file.
179 // We will anyway overwrite the file to the v4signature generated from input_fd.
180 }
181
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000182 output
183 .seek(SeekFrom::Start(0))
184 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000185 output.set_len(0).context("failed to set_len on the idsig output")?;
186 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000187 Ok(())
188}
189
Alan Stokes25f69362023-03-06 16:51:54 +0000190fn get_current_sdk() -> Result<u32> {
191 let current_sdk = system_properties::read("ro.build.version.sdk")?;
192 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
193 current_sdk.parse().context("Malformed SDK version")
194}
195
David Brazdil4b4c5102022-12-19 22:56:20 +0000196pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
197 for dir_entry in read_dir(path)? {
198 remove_file(dir_entry?.path())?;
199 }
200 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100201}
202
David Brazdil528e0472022-10-10 15:06:02 +0100203/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000204#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000205pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900206 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000207}
208
Shikha Panward8e35422021-10-11 13:51:27 +0000209impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000210 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000211 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
212 let state = &mut *self.state.lock().unwrap();
213 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000214 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000215 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000216 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
217 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000218 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000219 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000220 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000221 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
222 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000223 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000224 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000225 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000226 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000227 .or(Err(StatusCode::UNKNOWN_ERROR))?;
228 }
229 Ok(())
230 }
231}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000232impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000233 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
234 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000235 ///
236 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000237 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000238 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000239 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900240 console_out_fd: Option<&ParcelFileDescriptor>,
241 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000242 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000243 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000244 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000245 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900246 let ret = self.create_vm_internal(
247 config,
248 console_out_fd,
249 console_in_fd,
250 log_fd,
251 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000252 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900253 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000254 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000255 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000256 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000257
Shikha Panwar61a74b52024-02-16 13:17:01 +0000258 /// Allocate a new instance_id to the VM
259 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000260 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000261 GLOBAL_SERVICE.allocateInstanceId()
262 }
263
Andrew Walbrandff3b942021-06-09 15:20:36 +0000264 /// Initialise an empty partition image of the given size to be used as a writable partition.
265 fn initializeWritablePartition(
266 &self,
267 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000268 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900269 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000270 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900271 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900272 let size_bytes = size_bytes
273 .try_into()
274 .with_context(|| format!("Invalid size: {}", size_bytes))
275 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000276 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000277 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000278 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000279 image
280 .seek(SeekFrom::Start(0))
281 .context("failed to move cursor to start")
282 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900283 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700284 // Set the file length. In most filesystems, this will not allocate any physical disk
285 // space, it will only change the logical size.
286 image
287 .set_len(size_bytes)
288 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900289 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000290
291 match partition_type {
292 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700293 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
294 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000295 _ => Err(Error::new(
296 ErrorKind::Unsupported,
297 format!("Unsupported partition type {:?}", partition_type),
298 )),
299 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900300 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
301 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000302
303 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000304 }
305
Jiyong Park0a248432021-08-20 23:32:39 +0900306 /// Creates or update the idsig file by digesting the input APK file.
307 fn createOrUpdateIdsigFile(
308 &self,
309 input_fd: &ParcelFileDescriptor,
310 idsig_fd: &ParcelFileDescriptor,
311 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900312 check_manage_access()?;
313
Jiyong Park2227eaa2023-08-04 11:59:18 +0900314 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900315 Ok(())
316 }
317
Andrew Walbran320b5602021-03-04 16:11:12 +0000318 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
319 /// and as such is only permitted from the shell user.
320 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000321 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000322 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000323 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900324
325 /// Get a list of assignable device types.
326 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
327 // Delegate to the global service, including checking the permission.
328 GLOBAL_SERVICE.getAssignableDevices()
329 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100330
Inseob Kim46257382024-01-03 15:41:22 +0900331 /// Get a list of supported OSes.
332 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
333 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
334 }
335
Jaewan Kimabd328b2024-12-10 15:59:33 +0900336 /// Get printable debug policy for testing and debugging
337 fn getDebugPolicy(&self) -> binder::Result<String> {
338 let debug_policy = DebugPolicy::from_host();
339 Ok(format!("{debug_policy:?}"))
340 }
341
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100342 /// Returns whether given feature is enabled
343 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
344 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000345 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100346 }
Alice Wange64dd182024-01-17 15:57:55 +0000347
348 fn enableTestAttestation(&self) -> binder::Result<()> {
349 GLOBAL_SERVICE.enableTestAttestation()
350 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000351
352 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
353 check_manage_access()?;
354 GLOBAL_SERVICE.isRemoteAttestationSupported()
355 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000356
357 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
358 // The response is specific to Microdroid. Updatable VMs are only possible if device
359 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
360 // this, however other guest OSes may do things differently.
361 check_manage_access()?;
362 Ok(is_secretkeeper_supported())
363 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000364
Shikha Panwar07d701c2024-03-28 14:43:52 +0000365 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
366 check_manage_access()?;
367 GLOBAL_SERVICE.removeVmInstance(instance_id)
368 }
369
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000370 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
371 check_manage_access()?;
372 GLOBAL_SERVICE.claimVmInstance(instance_id)
373 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000374}
375
Inseob Kimecde8c02024-09-03 13:11:08 +0900376/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
377#[derive(Debug, Default)]
378struct EarlyVmContext {
379 /// The unique CID assigned to the VM for vsock communication.
380 cid: Cid,
381 /// Temporary directory for this VM instance.
382 temp_dir: PathBuf,
383}
384
385impl EarlyVmContext {
386 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
387 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
388 // should trust clients, e.g. they won't run two VMs at the same time
389 let _ = remove_dir_all(&temp_dir);
390 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
391
392 Ok(Self { cid, temp_dir })
393 }
394}
395
396impl Interface for EarlyVmContext {}
397
398impl Drop for EarlyVmContext {
399 fn drop(&mut self) {
400 if let Err(e) = remove_dir_all(&self.temp_dir) {
401 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
402 }
403 }
404}
405
406impl IGlobalVmContext for EarlyVmContext {
407 fn getCid(&self) -> binder::Result<i32> {
408 Ok(self.cid as i32)
409 }
410
411 fn getTemporaryDirectory(&self) -> binder::Result<String> {
412 Ok(self.temp_dir.to_string_lossy().to_string())
413 }
414
415 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
416 Err(Status::new_exception_str(
417 ExceptionCode::UNSUPPORTED_OPERATION,
418 Some("Early VM doesn't support setting host console name"),
419 ))
420 }
421}
422
Frederick Mayle3a46b272025-02-10 21:55:49 -0800423#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
424enum CallingPartition {
425 Odm,
426 Product,
427 System,
428 SystemExt,
429 Vendor,
430 Unknown,
431}
432
433impl CallingPartition {
434 fn as_str(&self) -> &'static str {
435 match self {
436 CallingPartition::Odm => "odm",
437 CallingPartition::Product => "product",
438 CallingPartition::System => "system",
439 CallingPartition::SystemExt => "system_ext",
440 CallingPartition::Vendor => "vendor",
441 CallingPartition::Unknown => "[unknown]",
442 }
443 }
444}
445
446impl std::fmt::Display for CallingPartition {
447 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448 write!(f, "{}", self.as_str())
449 }
450}
451
452fn find_partition(path: Option<&Path>) -> binder::Result<CallingPartition> {
Frederick Maylecc9862f2025-02-10 20:42:59 -0800453 let Some(path) = path else {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800454 return Ok(CallingPartition::System);
Inseob Kime3e932d2024-12-16 20:06:57 +0900455 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000456 if path.starts_with("/system/system_ext/") {
Frederick Mayle3a46b272025-02-10 21:55:49 -0800457 return Ok(CallingPartition::SystemExt);
Armelle Laine1a25d982025-01-31 06:39:54 +0000458 }
Frederick Mayle3a46b272025-02-10 21:55:49 -0800459 if path.starts_with("/system/product/") {
460 return Ok(CallingPartition::Product);
461 }
462 let partition = {
463 let mut components = path.components();
464 let Some(std::path::Component::Normal(partition)) = components.nth(1) else {
465 return Err(anyhow!("Can't find partition in '{}'", path.display()))
Frederick Maylecc9862f2025-02-10 20:42:59 -0800466 .or_service_specific_exception(-1);
467 };
Frederick Maylecc9862f2025-02-10 20:42:59 -0800468
Frederick Mayle3a46b272025-02-10 21:55:49 -0800469 // If path is under /apex, find a partition of the preinstalled .apex path
470 if partition == "apex" {
471 let Some(std::path::Component::Normal(apex_name)) = components.next() else {
472 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
473 .or_service_specific_exception(-1);
474 };
475 let apex_info_list = ApexInfoList::load()
476 .context("Failed to get apex info list")
477 .or_service_specific_exception(-1)?;
478 apex_info_list
479 .list
480 .iter()
481 .find(|apex_info| apex_info.name.as_str() == apex_name)
482 .map(|apex_info| apex_info.partition.to_lowercase())
483 .ok_or(anyhow!("Can't find apex info for {apex_name:?}"))
484 .or_service_specific_exception(-1)?
485 } else {
486 partition.to_string_lossy().into_owned()
487 }
488 };
489 Ok(match partition.as_str() {
490 "odm" => CallingPartition::Odm,
491 "product" => CallingPartition::Product,
492 "system" => CallingPartition::System,
493 "system_ext" => CallingPartition::SystemExt,
494 "vendor" => CallingPartition::Vendor,
495 _ => {
496 warn!("unknown partition for '{}'", path.display());
497 CallingPartition::Unknown
498 }
499 })
Inseob Kimecde8c02024-09-03 13:11:08 +0900500}
501
Jiyong Park8611a6c2021-07-09 18:17:44 +0900502impl VirtualizationService {
503 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000504 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900505 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000506
Inseob Kimecde8c02024-09-03 13:11:08 +0900507 fn create_early_vm_context(
508 &self,
509 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900510 calling_exe_path: Option<&Path>,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800511 calling_partition: CallingPartition,
Inseob Kimecde8c02024-09-03 13:11:08 +0900512 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900513 let name = match config {
514 VirtualMachineConfig::RawConfig(config) => &config.name,
515 VirtualMachineConfig::AppConfig(config) => &config.name,
516 };
Frederick Mayle3a46b272025-02-10 21:55:49 -0800517 let early_vm = find_early_vm_for_partition(calling_partition, name)
Inseob Kime3e932d2024-12-16 20:06:57 +0900518 .or_service_specific_exception(-1)?;
519 let calling_exe_path = match calling_exe_path {
520 Some(path) => path,
521 None => {
522 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
523 .or_service_specific_exception(-1)
524 }
525 };
Armelle Laine1a25d982025-01-31 06:39:54 +0000526 let expected_exe_path = Path::new(&early_vm.path);
527 if expected_exe_path != calling_exe_path
528 && Path::new("/system").join(expected_exe_path) != calling_exe_path
529 {
Inseob Kimecde8c02024-09-03 13:11:08 +0900530 return Err(anyhow!(
Inseob Kime3e932d2024-12-16 20:06:57 +0900531 "VM '{name}' in partition '{calling_partition}' must be created with '{}', not '{}'",
Inseob Kimecde8c02024-09-03 13:11:08 +0900532 &early_vm.path,
Inseob Kime3e932d2024-12-16 20:06:57 +0900533 calling_exe_path.display()
Inseob Kimecde8c02024-09-03 13:11:08 +0900534 ))
535 .or_service_specific_exception(-1);
536 }
537
538 let cid = early_vm.cid as Cid;
539 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
540
541 let context = EarlyVmContext::new(cid, temp_dir.clone())
542 .context(format!("Can't create early vm contexts for {cid}"))
543 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900544
Jiyong Park690c1ca2024-11-28 18:06:50 +0900545 if requires_vm_service(config) {
546 // Start VM service listening for connections from the new CID on port=CID.
547 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
548 let port = cid;
549 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
550 .context(format!("Could not start RpcServer on port {port}"))
551 .or_service_specific_exception(-1)?;
552 vm_server.start();
553 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
554 } else {
555 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
556 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900557 }
558
David Brazdil209074a2023-01-12 16:44:51 +0000559 fn create_vm_context(
560 &self,
561 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900562 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000563 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000564 const NUM_ATTEMPTS: usize = 5;
565
566 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000567 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000568 let cid = vm_context.getCid()? as Cid;
569 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900570
571 // We don't need to start the VM service for custom VMs.
572 if !requires_vm_service(config) {
573 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
574 }
575
David Brazdil8cf8f482022-11-23 14:21:26 +0000576 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
577
578 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000579 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000580 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000581 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000582 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900583 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000584 }
585 Err(err) => {
586 warn!("Could not start RpcServer on port {}: {}", port, err);
587 }
588 }
589 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900590 Err(anyhow!("Too many attempts to create VM context failed"))
591 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000592 }
593
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000594 fn create_vm_internal(
595 &self,
596 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900597 console_out_fd: Option<&ParcelFileDescriptor>,
598 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000599 log_fd: Option<&ParcelFileDescriptor>,
600 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000601 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000602 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000603 let requester_uid = get_calling_uid();
604 let requester_debug_pid = get_calling_pid();
605
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800606 let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?;
607
Nikita Ioffe631717e2023-09-05 13:38:07 +0100608 check_config_features(config)?;
609
Inseob Kimecde8c02024-09-03 13:11:08 +0900610 if cfg!(early) {
611 check_config_allowed_for_early_vms(config)?;
612 }
613
Nikita Ioffeb1416122024-10-22 12:18:49 +0000614 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
615 info!("callers secontext: {}", caller_secontext);
616
David Brazdil209074a2023-01-12 16:44:51 +0000617 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900618 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800619 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref(), calling_partition)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900620 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900621 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900622 };
Inseob Kim1119d702022-05-02 18:01:58 +0900623
Alan Stokesfda70842023-12-20 17:50:14 +0000624 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100625 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900626 }
627
Nikita Ioffe5776f082023-02-10 21:38:26 +0000628 let gdb_port = extract_gdb_port(config);
629
630 // Additional permission checks if caller request gdb.
631 if gdb_port.is_some() {
632 check_gdb_allowed(config)?;
633 }
634
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800635 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900636 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800637 if let Some(dt_overlay) =
638 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
639 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900640 device_tree_overlays.push(dt_overlay);
641 }
642 if let Some(dtbo) = get_dtbo(config) {
643 let dtbo = File::from(
644 dtbo.as_ref()
645 .try_clone()
646 .context("Failed to create VM DTBO from ParcelFileDescriptor")
647 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
648 );
649 device_tree_overlays.push(dtbo);
650 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900651
Jaewan Kimf3143242024-03-15 06:56:31 +0000652 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000653 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900654 Some(prepare_ramdump_file(&temporary_directory)?)
655 } else {
656 None
657 };
658
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000659 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900660 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100661 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900662 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100663 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100664 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
665 Some(clone_file(fd)?)
666 } else if debug_config.dump_device_tree {
667 Some(prepare_dump_dt_file(&temporary_directory)?)
668 } else {
669 None
670 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000671
672 // Counter to generate unique IDs for temporary image files.
673 let mut next_temporary_image_id = 0;
674 // Files which are referred to from composite images. These must be mapped to the crosvm
675 // child process, and not closed before it is started.
676 let mut indirect_files = vec![];
677
Alan Stokes7bc146c2022-10-20 17:10:32 +0100678 let (is_app_config, config) = match config {
679 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
680 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900681 let config = load_app_config(config, &debug_config, &temporary_directory)
682 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900683 *is_protected = config.protectedVm;
684 let message = format!("Failed to load app config: {:?}", e);
685 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900686 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900687 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100688 (true, BorrowedOrOwned::Owned(config))
689 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000690 };
691 let config = config.as_ref();
692 *is_protected = config.protectedVm;
693
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000694 if !config.teeServices.is_empty() {
695 check_tee_service_permission(&caller_secontext, &config.teeServices)
696 .with_log()
697 .or_binder_exception(ExceptionCode::SECURITY)?;
698 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000699
Jiyong Park3051ffe2024-11-26 14:41:58 +0900700 let kernel = maybe_clone_file(&config.kernel)?;
701 let initrd = maybe_clone_file(&config.initrd)?;
702
703 if config.protectedVm {
704 // Fail fast with a meaningful error message in case device doesn't support pVMs.
705 check_protected_vm_is_supported()?;
706
707 // In a protected VM, we require custom kernels to come from a trusted source
708 // (b/237054515).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800709 check_label_for_kernel_files(&kernel, &initrd, calling_partition)
710 .or_service_specific_exception(-1)?;
Jiyong Park3051ffe2024-11-26 14:41:58 +0900711
712 // Check if partition images are labeled incorrectly. This is to prevent random images
713 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
714 // from being loaded in a pVM. This applies to everything but the instance image in the
715 // raw config, and everything but the non-executable, generated partitions in the app
716 // config.
717 config
718 .disks
719 .iter()
Frederick Mayle9539fb52025-02-13 13:08:15 -0800720 .flat_map(|disk| disk.image.as_ref())
721 .try_for_each(|image| check_label_for_file(image, "disk image", calling_partition))
722 .or_service_specific_exception(-1)?;
723 config
724 .disks
725 .iter()
Jiyong Park3051ffe2024-11-26 14:41:58 +0900726 .flat_map(|disk| disk.partitions.iter())
727 .filter(|partition| {
728 if is_app_config {
729 !is_safe_app_partition(&partition.label)
730 } else {
731 !is_safe_raw_partition(&partition.label)
732 }
733 })
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800734 .try_for_each(|partition| check_label_for_partition(partition, calling_partition))
Jiyong Park3051ffe2024-11-26 14:41:58 +0900735 .or_service_specific_exception(-1)?;
736 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000737
Inseob Kimff48a7c2024-02-26 22:07:21 +0900738 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
739 // have unstable interfaces.
740 // TODO(b/316431494): remove once Treble interfaces are stabilized.
Frederick Mayle50c2b6a2025-02-11 18:26:04 -0800741 check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900742
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000743 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900744 write_zero_filler(&zero_filler_path)
745 .context("Failed to make composite image")
746 .with_log()
747 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000748
749 // Assemble disk images if needed.
750 let disks = config
751 .disks
752 .iter()
753 .map(|disk| {
754 assemble_disk_image(
755 disk,
756 &zero_filler_path,
757 &temporary_directory,
758 &mut next_temporary_image_id,
759 &mut indirect_files,
760 )
761 })
762 .collect::<Result<Vec<DiskFile>, _>>()?;
763
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700764 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
765
Jaewan Kimf43372b2024-12-13 18:33:58 +0900766 let (vfio_devices, dtbo) = match &config.devices {
767 AssignedDevices::Devices(devices) if !devices.is_empty() => {
768 let mut set = HashSet::new();
769 for device in devices.iter() {
770 let path = canonicalize(device)
771 .with_context(|| format!("can't canonicalize {device}"))
772 .or_service_specific_exception(-1)?;
773 if !set.insert(path) {
774 return Err(anyhow!("duplicated device {device}"))
775 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
776 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900777 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900778 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
779 let dtbo_file = File::from(
780 GLOBAL_SERVICE
781 .getDtboFile()?
782 .as_ref()
783 .try_clone()
784 .context("Failed to create VM DTBO from ParcelFileDescriptor")
785 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
786 );
787 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900788 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900789 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900790 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900791 let display_config = if cfg!(paravirtualized_devices) {
792 config
793 .displayConfig
794 .as_ref()
795 .map(DisplayConfig::new)
796 .transpose()
797 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
798 } else {
799 None
800 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700801 let gpu_config = if cfg!(paravirtualized_devices) {
802 config
803 .gpuConfig
804 .as_ref()
805 .map(GpuConfig::new)
806 .transpose()
807 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
808 } else {
809 None
810 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900811
Jeongik Chac181be72024-03-27 00:18:30 +0900812 let input_device_options = if cfg!(paravirtualized_devices) {
813 config
814 .inputDevices
815 .iter()
816 .map(to_input_device_option_from)
817 .collect::<Result<Vec<InputDeviceOption>, _>>()
818 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
819 } else {
820 vec![]
821 };
822
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900823 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900824 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900825 if *is_protected {
826 return Err(anyhow!("Network feature is not supported for pVM yet"))
827 .with_log()
828 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
829 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900830 Some(File::from(
831 GLOBAL_SERVICE
832 .createTapInterface(&get_this_pid().to_string())?
833 .as_ref()
834 .try_clone()
835 .context("Failed to get TAP interface from ParcelFileDescriptor")
836 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
837 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900838 } else {
839 None
840 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800841
842 let audio_config = if cfg!(paravirtualized_devices) {
843 config.audioConfig.as_ref().map(AudioConfig::new)
844 } else {
845 None
846 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900847
Elie Kheirallah29d72912024-08-07 20:17:26 +0000848 let usb_config = config
849 .usbConfig
850 .as_ref()
851 .map(UsbConfig::new)
852 .unwrap_or(Ok(UsbConfig { controller: false }))
853 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
854
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000855 let detect_hangup = is_app_config && gdb_port.is_none();
856
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800857 let custom_memory_backing_files = config
858 .customMemoryBackingFiles
859 .iter()
860 .map(|memory_backing_file| {
861 Ok((
862 clone_file(
863 memory_backing_file
864 .file
865 .as_ref()
866 .context("missing CustomMemoryBackingFile FD")
867 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
868 )?
869 .into(),
870 memory_backing_file.rangeStart as u64,
871 memory_backing_file.size as u64,
872 ))
873 })
874 .collect::<binder::Result<_>>()?;
875
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000876 // Actually start the VM.
877 let crosvm_config = CrosvmConfig {
878 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000879 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000880 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000881 kernel,
882 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000883 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700884 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000885 params: config.params.to_owned(),
886 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900887 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700888 memory_mib: config
889 .memoryMib
890 .try_into()
891 .ok()
892 .and_then(NonZeroU32::new)
893 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800894 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000895 cpus: config.cpuOptions.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900896 console_out_fd,
897 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000898 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900899 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000900 indirect_files,
901 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000902 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000903 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900904 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000905 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900906 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900907 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900908 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000909 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900910 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800911 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000912 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700913 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800914 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800915 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000916 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000917 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800918 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
919 instance_id,
Frederick Mayle31cc5b22024-12-19 14:42:43 -0800920 custom_memory_backing_files,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000921 };
922 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100923 VmInstance::new(
924 crosvm_config,
925 temporary_directory,
926 requester_uid,
927 requester_debug_pid,
928 vm_context,
929 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900930 .with_context(|| format!("Failed to create VM with config {:?}", config))
931 .with_log()
932 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000933 );
934 state.add_vm(Arc::downgrade(&instance));
935 Ok(VirtualMachine::create(instance))
936 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900937}
938
Alan Stokesfda70842023-12-20 17:50:14 +0000939/// Returns whether a VM config represents a "custom" virtual machine, which requires the
940/// USE_CUSTOM_VIRTUAL_MACHINE.
941fn is_custom_config(config: &VirtualMachineConfig) -> bool {
942 match config {
943 // Any raw (non-Microdroid) VM is considered custom.
944 VirtualMachineConfig::RawConfig(_) => true,
945 VirtualMachineConfig::AppConfig(config) => {
946 // Some features are reserved for platform apps only, even when using
947 // VirtualMachineAppConfig. Almost all of these features are grouped in the
948 // CustomConfig struct:
949 // - controlling CPUs;
950 // - gdbPort is set, meaning that crosvm will start a gdb server;
951 // - using anything other than the default kernel;
952 // - specifying devices to be assigned.
953 if config.customConfig.is_some() {
954 true
955 } else {
956 // Additional custom features not included in CustomConfig:
957 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000958 // - specifying extra APKs;
959 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900960 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000961 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900962 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
963 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000964 }
965 }
966 }
967}
968
Jiyong Park690c1ca2024-11-28 18:06:50 +0900969/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
970/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
971/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
972/// "microdroid" we run VirtualMachineService
973fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
974 match config {
975 VirtualMachineConfig::AppConfig(_) => true,
976 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
977 }
978}
979
Seungjae Yoo14e60182024-02-21 13:28:31 +0900980fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
981 let VirtualMachineConfig::AppConfig(config) = config else {
982 return Ok(None);
983 };
984 let Some(custom_config) = &config.customConfig else {
985 return Ok(None);
986 };
987 let Some(file) = custom_config.vendorImage.as_ref() else {
988 return Ok(None);
989 };
990
991 let file = clone_file(file)?;
992 let size =
993 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
994 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
995 .context("Failed to get vbmeta from microdroid-vendor.img")?;
996
997 for descriptor in vbmeta.descriptors()?.iter() {
998 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
999 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
1000 return Ok(Some(root_digest.as_bytes().to_vec()));
1001 }
1002 }
1003 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
1004}
1005
Jaewan Kimf43372b2024-12-13 18:33:58 +09001006fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001007 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -08001008 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001009 temporary_directory: &Path,
1010) -> binder::Result<Option<File>> {
1011 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
1012 // (e.g. instance-id)
1013 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
1014 let host_ref_dt = if host_ref_dt.exists()
1015 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
1016 {
1017 Some(host_ref_dt)
1018 } else {
1019 warn!("VM reference DT doesn't exist in host DT");
1020 None
1021 };
1022
1023 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
1024 .context("Failed to extract vendor hashtree digest")
1025 .or_service_specific_exception(-1)?;
1026
Matt Gilbrideaade4272024-12-05 13:52:42 +00001027 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001028 info!(
1029 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
1030 match the trusted digest in the pvmfw config, causing the VM to fail to start."
1031 );
Alan Stokesf46a17c2025-01-05 15:50:18 +00001032 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001033 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +00001034 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001035 };
1036
Matt Gilbrideaade4272024-12-05 13:52:42 +00001037 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001038 let mut untrusted_props = Vec::with_capacity(2);
1039 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001040 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001041 let want_updatable = extract_want_updatable(config);
1042 if want_updatable && is_secretkeeper_supported() {
1043 // Let guest know that it can defer rollback protection to Secretkeeper by setting
1044 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001045 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001046 let sk: Strong<dyn ISecretkeeper> =
1047 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1048 if sk.getInterfaceVersion()? >= 2 {
1049 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
1050 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001051 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001052 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001053 }
1054 }
1055
1056 let device_tree_overlay = if host_ref_dt.is_some()
1057 || !untrusted_props.is_empty()
1058 || !trusted_props.is_empty()
1059 {
1060 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1061 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1062 let fdt =
1063 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1064 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1065 .or_service_specific_exception(-1)?;
1066 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1067 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1068 } else {
1069 None
1070 };
1071 Ok(device_tree_overlay)
1072}
1073
Jaewan Kimf43372b2024-12-13 18:33:58 +09001074fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1075 let VirtualMachineConfig::RawConfig(config) = config else {
1076 return None;
1077 };
1078 match &config.devices {
1079 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1080 _ => None,
1081 }
1082}
1083
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001084fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001085 let file = OpenOptions::new()
1086 .create_new(true)
1087 .read(true)
1088 .write(true)
1089 .open(zero_filler_path)
1090 .with_context(|| "Failed to create zero.img")?;
1091 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001092 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001093}
1094
David Brazdilf50c7a62023-04-19 14:22:42 +00001095fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1096 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1097 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1098 part.flush()
1099}
1100
1101fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1102 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1103 part.flush()
1104}
1105
1106fn round_up(input: u64, granularity: u64) -> u64 {
1107 if granularity == 0 {
1108 return input;
1109 }
1110 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1111 let result = input.checked_add(granularity - 1).unwrap_or(input);
1112 (result / granularity) * granularity
1113}
1114
Jeongik Chac181be72024-03-27 00:18:30 +09001115fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1116 Ok(match input_device {
1117 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1118 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1119 height: u32::try_from(single_touch.height)?,
1120 width: u32::try_from(single_touch.width)?,
1121 name: if !single_touch.name.is_empty() {
1122 Some(single_touch.name.clone())
1123 } else {
1124 None
1125 },
1126 },
1127 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1128 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1129 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001130 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1131 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1132 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001133 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1134 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1135 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001136 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1137 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1138 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001139 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1140 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1141 height: u32::try_from(trackpad.height)?,
1142 width: u32::try_from(trackpad.width)?,
1143 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1144 },
Jeongik Cha10494912024-07-16 11:19:50 +09001145 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1146 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1147 height: u32::try_from(multi_touch.height)?,
1148 width: u32::try_from(multi_touch.width)?,
1149 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1150 },
Jeongik Chac181be72024-03-27 00:18:30 +09001151 })
1152}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001153
1154fn assemble_shared_paths(
1155 shared_paths: &[SharedPath],
1156 temporary_directory: &Path,
1157) -> Result<Vec<SharedPathConfig>, Status> {
1158 if shared_paths.is_empty() {
1159 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1160 }
1161
1162 shared_paths
1163 .iter()
1164 .map(|path| {
1165 Ok(SharedPathConfig {
1166 path: path.sharedPath.clone(),
1167 host_uid: path.hostUid,
1168 host_gid: path.hostGid,
1169 guest_uid: path.guestUid,
1170 guest_gid: path.guestGid,
1171 mask: path.mask,
1172 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001173 socket_path: temporary_directory
1174 .join(&path.socketPath)
1175 .to_string_lossy()
1176 .to_string(),
1177 socket_fd: maybe_clone_file(&path.socketFd)?,
1178 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001179 })
1180 })
1181 .collect()
1182}
1183
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001184/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1185///
1186/// This may involve assembling a composite disk from a set of partition images.
1187fn assemble_disk_image(
1188 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001189 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001190 temporary_directory: &Path,
1191 next_temporary_image_id: &mut u64,
1192 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001193) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001194 let image = if !disk.partitions.is_empty() {
1195 if disk.image.is_some() {
1196 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001197 return Err(anyhow!("DiskImage contains both image and partitions"))
1198 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001199 }
1200
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001201 let composite_image_filenames =
1202 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1203 let (image, partition_files) = make_composite_image(
1204 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001205 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001206 &composite_image_filenames.composite,
1207 &composite_image_filenames.header,
1208 &composite_image_filenames.footer,
1209 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001210 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1211 .with_log()
1212 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001213
1214 // Pass the file descriptors for the various partition files to crosvm when it
1215 // is run.
1216 indirect_files.extend(partition_files);
1217
1218 image
1219 } else if let Some(image) = &disk.image {
1220 clone_file(image)?
1221 } else {
1222 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001223 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1224 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001225 };
1226
1227 Ok(DiskFile { image, writable: disk.writable })
1228}
1229
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001230fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1231 if let Some(ref mut params) = vm_config.params {
1232 params.push(' ');
1233 params.push_str(param)
1234 } else {
1235 vm_config.params = Some(param.to_owned())
1236 }
1237}
1238
Inseob Kim46257382024-01-03 15:41:22 +09001239fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1240 if config.extension()?.to_str()? != "json" {
1241 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001242 }
Inseob Kim46257382024-01-03 15:41:22 +09001243
1244 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1245}
1246
1247fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1248 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1249 let os_names =
1250 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1251
1252 Ok(os_names)
1253}
1254
1255fn get_supported_os_names() -> Result<HashSet<String>> {
1256 if !cfg!(vendor_modules) {
1257 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1258 }
1259
1260 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1261}
1262
1263fn is_valid_os(os_name: &str) -> bool {
1264 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001265}
1266
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001267fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1268 if !cfg!(vendor_modules) {
1269 return false;
1270 }
1271 match config {
1272 VirtualMachineConfig::RawConfig(_) => false,
1273 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1274 }
1275}
1276
Jooyung Han21e9b922021-06-26 04:14:16 +09001277fn load_app_config(
1278 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001279 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001280 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001281) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001282 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1283 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001284 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001285
Shikha Panwar22e70452022-10-10 18:32:55 +00001286 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1287 Some(clone_file(file)?)
1288 } else {
1289 None
1290 };
1291
Alan Stokesfda70842023-12-20 17:50:14 +00001292 let vm_payload_config;
1293 let extra_apk_files: Vec<_>;
1294 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001295 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001296 vm_payload_config =
1297 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1298 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1299 extra_apk_files = vm_payload_config
1300 .extra_apks
1301 .iter()
1302 .enumerate()
1303 .map(|(i, apk)| {
1304 File::open(PathBuf::from(&apk.path))
1305 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1306 })
1307 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001308 }
Alan Stokesfda70842023-12-20 17:50:14 +00001309 Payload::PayloadConfig(payload_config) => {
1310 vm_payload_config = create_vm_payload_config(payload_config)?;
1311 extra_apk_files =
1312 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1313 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001314 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001315
Inseob Kim89b24592024-02-23 18:59:43 +09001316 let payload_config_os = vm_payload_config.os.name.as_str();
1317 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1318 bail!("'os' in payload config is deprecated");
1319 }
1320
Inseob Kim172f9eb2023-11-06 17:02:08 +09001321 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001322 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001323 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001324 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001325 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001326
1327 // It is safe to construct a filename based on the os_name because we've already checked that it
1328 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001329 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1330 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001331 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001332
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001333 if let Some(custom_config) = &config.customConfig {
1334 if let Some(file) = custom_config.customKernelImage.as_ref() {
1335 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1336 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001337 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001338
1339 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001340 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001341 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001342 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001343
Jaewan Kimf43372b2024-12-13 18:33:58 +09001344 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001345 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001346
1347 for param in custom_config.extraKernelCmdlineParams.iter() {
1348 append_kernel_param(param, &mut vm_config);
1349 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001350
1351 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001352 }
1353
Andrew Walbrancc045902021-07-27 16:06:17 +00001354 if config.memoryMib > 0 {
1355 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001356 }
1357
Chris Wailes6177c662024-05-09 14:37:44 -07001358 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001359 vm_config.protectedVm = config.protectedVm;
Elie Kheirallahb4b2f242025-01-23 03:38:07 +00001360 vm_config.cpuOptions = config.cpuOptions.clone();
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001361 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001362 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001363
Shikha Panwar22e70452022-10-10 18:32:55 +00001364 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001365 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001366
1367 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1368 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001369 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001370 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001371 temporary_directory,
1372 apk_file,
1373 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001374 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001375 &vm_payload_config,
1376 &mut vm_config,
1377 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001378
Andrew Walbrancc0db522021-07-12 17:03:42 +00001379 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001380}
1381
Frederick Mayle3a46b272025-02-10 21:55:49 -08001382fn check_partition_for_file(
1383 fd: &ParcelFileDescriptor,
1384 calling_partition: CallingPartition,
1385) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001386 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1387 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1388
1389 // microdroid vendor image is OK
1390 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1391 {
1392 return Ok(());
1393 }
1394
Inseob Kime3e932d2024-12-16 20:06:57 +09001395 let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm");
Frederick Mayle3a46b272025-02-10 21:55:49 -08001396 let is_caller_vendor =
1397 calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm;
Inseob Kime3e932d2024-12-16 20:06:57 +09001398
1399 if is_fd_vendor != is_caller_vendor {
1400 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001401 }
1402
1403 Ok(())
1404}
1405
Inseob Kime3e932d2024-12-16 20:06:57 +09001406fn check_partitions_for_files(
1407 config: &VirtualMachineRawConfig,
Frederick Mayle3a46b272025-02-10 21:55:49 -08001408 calling_partition: CallingPartition,
Inseob Kime3e932d2024-12-16 20:06:57 +09001409) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001410 config
1411 .disks
1412 .iter()
1413 .flat_map(|disk| disk.partitions.iter())
1414 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001415 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001416
Inseob Kime3e932d2024-12-16 20:06:57 +09001417 config
1418 .disks
1419 .iter()
1420 .filter_map(|disk| disk.image.as_ref())
1421 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1422
1423 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1424 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1425 config
1426 .bootloader
1427 .as_ref()
1428 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001429
1430 Ok(())
1431}
1432
Alan Stokes0d1ef782022-09-27 13:46:35 +01001433fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1434 let mut apk_zip = ZipArchive::new(apk_file)?;
1435 let config_file = apk_zip.by_name(config_path)?;
1436 Ok(serde_json::from_reader(config_file)?)
1437}
1438
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001439fn create_vm_payload_config(
1440 payload_config: &VirtualMachinePayloadConfig,
1441) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001442 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1443 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1444 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001445
1446 let payload_binary_name = &payload_config.payloadBinaryName;
1447 if payload_binary_name.contains('/') {
1448 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1449 }
1450
1451 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001452
1453 // The VM only cares about how many there are, these names are actually ignored.
1454 let extra_apk_count = payload_config.extraApks.len();
1455 let extra_apks =
1456 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1457
Nikita Ioffe901083f2025-01-20 01:54:28 +00001458 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1459 // The only payload delivered via Mainline module in this release requires
1460 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1461 // APIs, so we use the fact that the payload is granted
1462 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1463 // com.android.i18n APEX.
1464 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1465 // Microdroid pVMs.
1466 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1467 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1468 } else {
1469 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1470 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001471}
1472
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001473/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001474fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001475 temporary_directory: &Path,
1476 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001477) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001478 let id = *next_temporary_image_id;
1479 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001480 CompositeImageFilenames {
1481 composite: temporary_directory.join(format!("composite-{}.img", id)),
1482 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1483 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1484 }
1485}
1486
1487/// Filenames for a composite disk image, including header and footer partitions.
1488#[derive(Clone, Debug, Eq, PartialEq)]
1489struct CompositeImageFilenames {
1490 /// The composite disk image itself.
1491 composite: PathBuf,
1492 /// The header partition image.
1493 header: PathBuf,
1494 /// The footer partition image.
1495 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001496}
1497
Jiyong Park753553b2021-07-12 21:21:09 +09001498/// Checks whether the caller has a specific permission
1499fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001500 if cfg!(early) {
1501 // Skip permission check for early VMs, in favor of SELinux
1502 return Ok(());
1503 }
David Brazdil1f530702022-10-03 12:18:10 +01001504 let calling_pid = get_calling_pid();
1505 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001506 // Root can do anything
1507 if calling_uid == 0 {
1508 return Ok(());
1509 }
1510 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001511 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001512 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001513 Ok(())
1514 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001515 Err(anyhow!("does not have the {} permission", perm))
1516 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001517 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001518}
1519
Jiyong Park753553b2021-07-12 21:21:09 +09001520/// Check whether the caller of the current Binder method is allowed to manage VMs
1521fn check_manage_access() -> binder::Result<()> {
1522 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1523}
1524
Inseob Kim1119d702022-05-02 18:01:58 +09001525/// Check whether the caller of the current Binder method is allowed to create custom VMs
1526fn check_use_custom_virtual_machine() -> binder::Result<()> {
1527 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1528}
1529
Nikita Ioffe901083f2025-01-20 01:54:28 +00001530/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1531/// rollback protection schema.
1532fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1533 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1534}
1535
Alan Stokes185fe112023-01-10 16:20:55 +00001536/// Return whether a partition is exempt from selinux label checks, because we know that it does
1537/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001538fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001539 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001540 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001541 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001542 || label == "microdroid-apk-idsig"
1543 || label == "payload-metadata"
1544 || label.starts_with("extra-idsig-")
1545}
1546
Alice Wangc206b9b2023-08-28 14:13:51 +00001547/// Returns whether a partition with the given label is safe for a raw config VM.
1548fn is_safe_raw_partition(label: &str) -> bool {
1549 label == "vm-instance"
1550}
1551
Alan Stokes185fe112023-01-10 16:20:55 +00001552/// Check that a file SELinux label is acceptable.
1553///
1554/// 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 +09001555/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001556///
1557/// Note that sepolicy must also grant read access for these types to both virtualization
1558/// service and crosvm.
1559///
1560/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1561/// user devices (W^X).
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001562fn check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001563 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001564 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001565 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001566 | "staging_data_file" // updated/staged APEX images
1567 | "system_file" // immutable dm-verity protected partition
1568 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001569 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001570 => Ok(()),
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001571 // It is difficult to require specific label types for vendor initiated VM's files, so we
1572 // allow anything with a vendor prefix.
1573 t if calling_partition == CallingPartition::Vendor && t.starts_with("vendor_") => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001574 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001575 }
1576}
1577
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001578fn check_label_for_partition(
1579 partition: &Partition,
1580 calling_partition: CallingPartition,
1581) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001582 let file = partition.image.as_ref().unwrap().as_ref();
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001583 check_label_is_allowed(&getfilecon(file)?, calling_partition)
Alan Stokes185fe112023-01-10 16:20:55 +00001584 .with_context(|| format!("Partition {} invalid", &partition.label))
1585}
1586
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001587fn check_label_for_kernel_files(
1588 kernel: &Option<File>,
1589 initrd: &Option<File>,
1590 calling_partition: CallingPartition,
1591) -> Result<()> {
Alan Stokes185fe112023-01-10 16:20:55 +00001592 if let Some(f) = kernel {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001593 check_label_for_file(f, "kernel", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001594 }
1595 if let Some(f) = initrd {
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001596 check_label_for_file(f, "initrd", calling_partition)?;
Alan Stokes185fe112023-01-10 16:20:55 +00001597 }
1598 Ok(())
1599}
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001600fn check_label_for_file(
Frederick Mayle9539fb52025-02-13 13:08:15 -08001601 file: &impl AsRawFd,
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08001602 name: &str,
1603 calling_partition: CallingPartition,
1604) -> Result<()> {
1605 check_label_is_allowed(&getfilecon(file)?, calling_partition)
1606 .with_context(|| format!("{} file invalid", name))
Alan Stokes185fe112023-01-10 16:20:55 +00001607}
1608
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001609/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1610#[derive(Debug)]
1611struct VirtualMachine {
1612 instance: Arc<VmInstance>,
1613}
1614
1615impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001616 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001617 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001618 }
1619}
1620
1621impl Interface for VirtualMachine {}
1622
Devin Moore407df8f2024-08-27 19:39:16 +00001623impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001624 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001625 // Don't check permission. The owner of the VM might have passed this binder object to
1626 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001627 Ok(self.instance.cid as i32)
1628 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001629
Andrew Walbran6b650662021-09-07 13:13:23 +00001630 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001631 // Don't check permission. The owner of the VM might have passed this binder object to
1632 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001633 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001634 }
1635
1636 fn registerCallback(
1637 &self,
1638 callback: &Strong<dyn IVirtualMachineCallback>,
1639 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001640 // Don't check permission. The owner of the VM might have passed this binder object to
1641 // others.
Jaewan Kim27ac1832025-02-03 23:42:08 +09001642
1643 // Only register callback if it may be notified.
1644 // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1645 let vm_state = self.instance.vm_state.lock().unwrap();
1646 if matches!(*vm_state, VmState::Dead) {
1647 warn!("Ignoring registerCallback() after VM is died");
1648 } else {
1649 self.instance.callbacks.add(callback.clone());
1650 }
1651 drop(vm_state);
1652
Andrew Walbrandae07162021-03-12 17:05:20 +00001653 Ok(())
1654 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001655
Andrew Walbranf8d94112021-09-07 11:45:36 +00001656 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001657 self.instance
1658 .start()
1659 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1660 .with_log()
1661 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001662 }
1663
Inseob Kima446f802022-07-11 19:46:37 +09001664 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001665 self.instance
1666 .kill()
1667 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1668 .with_log()
1669 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001670 }
1671
Keir Fraser48221ba2024-07-12 14:05:02 +00001672 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1673 let balloon = self
1674 .instance
1675 .get_memory_balloon()
1676 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1677 .with_log()
1678 .or_service_specific_exception(-1)?;
1679 Ok(balloon.try_into().unwrap())
1680 }
1681
1682 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001683 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001684 .set_memory_balloon(num_bytes.try_into().unwrap())
1685 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001686 .with_log()
1687 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001688 }
1689
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001690 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001691 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001692 return Err(Status::new_service_specific_error_str(
1693 IVirtualMachine::ERROR_UNEXPECTED,
1694 Some("Virtual Machine is not running"),
1695 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001696 }
Alan Stokes10c47672022-12-13 17:17:08 +00001697 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001698 if port < VSOCK_PRIV_PORT_MAX {
1699 return Err(Status::new_service_specific_error_str(
1700 IVirtualMachine::ERROR_UNEXPECTED,
1701 Some("Can't connect to privileged port {port}"),
1702 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001703 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001704 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1705 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001706 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001707 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001708 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001709
Devin Moore407df8f2024-08-27 19:39:16 +00001710 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1711 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1712 return Err(Status::new_service_specific_error_str(
1713 IVirtualMachine::ERROR_UNEXPECTED,
1714 Some("Virtual Machine is not running"),
1715 ));
1716 }
1717 let port = port as u32;
1718 if port < VSOCK_PRIV_PORT_MAX {
1719 return Err(Status::new_service_specific_error_str(
1720 IVirtualMachine::ERROR_UNEXPECTED,
1721 Some("Can't connect to privileged port {port}"),
1722 ));
1723 }
1724 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001725 let addr = sockaddr_vm {
1726 svm_family: AF_VSOCK as sa_family_t,
1727 svm_reserved1: 0,
1728 svm_port: port,
1729 svm_cid: cid,
1730 svm_zero: [0u8; 4],
1731 };
1732 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001733 let accessor = Accessor::new(name, get_connection_info);
1734 accessor
1735 .as_binder()
1736 .context("The newly created Accessor should always have a binder")
1737 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1738 }
1739
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001740 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1741 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1742 }
Jiyong Park23b67392024-07-04 13:51:42 +09001743
1744 fn suspend(&self) -> binder::Result<()> {
1745 self.instance
1746 .suspend()
1747 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1748 .with_log()
1749 .or_service_specific_exception(-1)
1750 }
1751
1752 fn resume(&self) -> binder::Result<()> {
1753 self.instance
1754 .resume()
1755 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1756 .with_log()
1757 .or_service_specific_exception(-1)
1758 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001759}
1760
1761impl Drop for VirtualMachine {
1762 fn drop(&mut self) {
1763 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001764 if let Err(e) = self.instance.kill() {
1765 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1766 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001767 }
1768}
1769
1770/// A set of Binders to be called back in response to various events on the VM, such as when it
1771/// dies.
1772#[derive(Debug, Default)]
1773pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1774
1775impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001776 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001777 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001778 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001779 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001780 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001781 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001782 }
1783 }
1784 }
1785
Inseob Kim14cb8692021-08-31 21:50:39 +09001786 /// Call all registered callbacks to notify that the payload is ready to serve.
1787 pub fn notify_payload_ready(&self, cid: Cid) {
1788 let callbacks = &*self.0.lock().unwrap();
1789 for callback in callbacks {
1790 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001791 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001792 }
1793 }
1794 }
1795
Inseob Kim2444af92021-08-31 01:22:50 +09001796 /// Call all registered callbacks to notify that the payload has finished.
1797 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1798 let callbacks = &*self.0.lock().unwrap();
1799 for callback in callbacks {
1800 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001801 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001802 }
1803 }
1804 }
1805
Jooyung Handd0a1732021-11-23 15:26:20 +09001806 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001807 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001808 let callbacks = &*self.0.lock().unwrap();
1809 for callback in callbacks {
1810 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001811 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001812 }
1813 }
1814 }
1815
Andrew Walbrandae07162021-03-12 17:05:20 +00001816 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001817 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Jaewan Kim27ac1832025-02-03 23:42:08 +09001818 let mut callbacks = self.0.lock().unwrap();
1819 for callback in &*callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001820 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001821 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001822 }
1823 }
Jaewan Kim27ac1832025-02-03 23:42:08 +09001824
1825 // Nothing to notify afterward because VM cannot be restarted.
1826 // Explicitly clear callbacks to prevent potential cyclic references
1827 // between callback and VmInstance.
1828 (*callbacks).clear();
Andrew Walbrandae07162021-03-12 17:05:20 +00001829 }
1830
1831 /// Add a new callback to the set.
1832 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1833 self.0.lock().unwrap().push(callback);
1834 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001835}
1836
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001837/// The mutable state of the VirtualizationService. There should only be one instance of this
1838/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001839#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001840struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001841 /// The VMs which have been started. When VMs are started a weak reference is added to this
1842 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1843 /// the Binder client are dropped the weak reference here will become invalid, and will be
1844 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001845 vms: Vec<Weak<VmInstance>>,
1846}
1847
1848impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001849 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001850 fn vms(&self) -> Vec<Arc<VmInstance>> {
1851 // Attempt to upgrade the weak pointers to strong pointers.
1852 self.vms.iter().filter_map(Weak::upgrade).collect()
1853 }
1854
1855 /// Add a new VM to the list.
1856 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1857 // Garbage collect any entries from the stored list which no longer exist.
1858 self.vms.retain(|vm| vm.strong_count() > 0);
1859
1860 // Actually add the new VM.
1861 self.vms.push(vm);
1862 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001863
Jiyong Park8611a6c2021-07-09 18:17:44 +09001864 /// Get a VM that corresponds to the given cid
1865 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1866 self.vms().into_iter().find(|vm| vm.cid == cid)
1867 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001868}
1869
Andrew Walbran6b650662021-09-07 13:13:23 +00001870/// Gets the `VirtualMachineState` of the given `VmInstance`.
1871fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001872 match &*instance.vm_state.lock().unwrap() {
1873 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1874 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001875 PayloadState::Starting => VirtualMachineState::STARTING,
1876 PayloadState::Started => VirtualMachineState::STARTED,
1877 PayloadState::Ready => VirtualMachineState::READY,
1878 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001879 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001880 },
1881 VmState::Dead => VirtualMachineState::DEAD,
1882 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001883 }
1884}
1885
David Brazdilf50c7a62023-04-19 14:22:42 +00001886/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001887pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1888 file.as_ref()
1889 .try_clone()
1890 .context("Failed to clone File from ParcelFileDescriptor")
1891 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001892 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001893}
1894
Andrew Walbrand3a84182021-09-07 14:48:52 +00001895/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001896fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001897 file.as_ref().map(clone_file).transpose()
1898}
1899
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001900/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001901fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1902 // SAFETY: ownership is transferred from stream to f
1903 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1904 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001905}
1906
Jiyong Parkdcf17412022-02-08 15:07:23 +09001907/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001908fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1909 VersionReq::parse(s)
1910 .with_context(|| format!("Invalid platform version requirement {}", s))
1911 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001912}
1913
Jiyong Parked180932023-02-24 19:55:41 +09001914/// Create the empty ramdump file
1915fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1916 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1917 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1918 // owner) for readout.
1919 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001920 let ramdump = File::create(ramdump_path)
1921 .context("Failed to prepare ramdump file")
1922 .with_log()
1923 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001924 Ok(ramdump)
1925}
1926
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001927/// Create the empty device tree dump file
1928fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1929 let path = temporary_directory.join("device_tree.dtb");
1930 let file = File::create(path)
1931 .context("Failed to prepare device tree dump file")
1932 .with_log()
1933 .or_service_specific_exception(-1)?;
1934 Ok(file)
1935}
1936
Nikita Ioffe5776f082023-02-10 21:38:26 +00001937fn is_protected(config: &VirtualMachineConfig) -> bool {
1938 match config {
1939 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1940 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1941 }
1942}
1943
1944fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1945 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001946 return Err(anyhow!("Can't use gdb with protected VMs"))
1947 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001948 }
1949
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001950 if get_debug_level(config) == Some(DebugLevel::NONE) {
1951 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1952 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001953 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001954
1955 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001956}
1957
Shikha Panwar61a74b52024-02-16 13:17:01 +00001958fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1959 match config {
1960 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1961 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1962 }
1963}
1964
Alan Stokesc96b35e2024-05-03 13:21:20 +01001965fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1966 match config {
1967 VirtualMachineConfig::RawConfig(_) => true,
1968 VirtualMachineConfig::AppConfig(config) => {
1969 let Some(custom) = &config.customConfig else { return true };
1970 custom.wantUpdatable
1971 }
1972 }
1973}
1974
Nikita Ioffe5776f082023-02-10 21:38:26 +00001975fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1976 match config {
1977 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001978 VirtualMachineConfig::AppConfig(config) => {
1979 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1980 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001981 }
1982}
1983
Nikita Ioffe631717e2023-09-05 13:38:07 +01001984fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1985 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1986 if let Some(custom_config) = &config.customConfig {
1987 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1988 return Err(anyhow!("vendor modules feature is disabled"))
1989 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1990 }
1991 }
1992 Ok(())
1993}
1994
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001995fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1996 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1997 if let Some(custom_config) = &config.customConfig {
1998 if !custom_config.devices.is_empty() {
1999 return Err(anyhow!("device assignment feature is disabled"))
2000 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2001 }
2002 }
2003 Ok(())
2004}
2005
Alan Stokesfda70842023-12-20 17:50:14 +00002006fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
2007 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2008 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
2009 if !payload_config.extraApks.is_empty() {
2010 return Err(anyhow!("multi-tenant feature is disabled"))
2011 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2012 }
2013 Ok(())
2014}
2015
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002016fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
2017 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2018 if let Some(custom_config) = &config.customConfig {
2019 if !custom_config.extraKernelCmdlineParams.is_empty() {
2020 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
2021 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2022 }
2023 }
2024 Ok(())
2025}
2026
Nikita Ioffe99548382024-10-21 15:54:46 +00002027fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
2028 match config {
2029 VirtualMachineConfig::RawConfig(config) => {
2030 if !config.teeServices.is_empty() {
2031 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2032 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2033 }
2034 }
2035 VirtualMachineConfig::AppConfig(config) => {
2036 if let Some(custom_config) = &config.customConfig {
2037 if !custom_config.teeServices.is_empty() {
2038 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2039 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2040 }
2041 }
2042 }
2043 };
2044 Ok(())
2045}
2046
Nikita Ioffef934e812024-07-05 15:44:41 +00002047fn check_protected_vm_is_supported() -> binder::Result<()> {
2048 let is_pvm_supported =
2049 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
2050 if is_pvm_supported {
2051 Ok(())
2052 } else {
2053 Err(anyhow!("pVM is not supported"))
2054 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
2055 }
2056}
2057
Nikita Ioffe631717e2023-09-05 13:38:07 +01002058fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
2059 if !cfg!(vendor_modules) {
2060 check_no_vendor_modules(config)?;
2061 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00002062 if !cfg!(device_assignment) {
2063 check_no_devices(config)?;
2064 }
Alan Stokesfda70842023-12-20 17:50:14 +00002065 if !cfg!(multi_tenant) {
2066 check_no_extra_apks(config)?;
2067 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00002068 if !cfg!(debuggable_vms_improvements) {
2069 check_no_extra_kernel_cmdline_params(config)?;
2070 }
Nikita Ioffe99548382024-10-21 15:54:46 +00002071 if !cfg!(tee_services_allowlist) {
2072 check_no_tee_services(config)?;
2073 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002074 Ok(())
2075}
2076
Inseob Kimecde8c02024-09-03 13:11:08 +09002077fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2078 check_no_vendor_modules(config)?;
2079 check_no_devices(config)?;
2080
2081 Ok(())
2082}
2083
Inseob Kim0168b462022-12-27 14:54:35 +09002084fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002085 fd: Option<&ParcelFileDescriptor>,
2086 tag: String,
2087) -> Result<Option<File>, Status> {
2088 if let Some(fd) = fd {
2089 return Ok(Some(clone_file(fd)?));
2090 }
2091
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002092 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002093 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002094
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002095 let mut reader = BufReader::new(File::from(read_fd));
2096 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002097
Frederick Mayle26e41af2025-02-05 18:30:29 -08002098 let mut buf = vec![];
Inseob Kim0168b462022-12-27 14:54:35 +09002099 std::thread::spawn(move || loop {
Frederick Mayle26e41af2025-02-05 18:30:29 -08002100 buf.clear();
2101 buf.shrink_to(1024);
Inseob Kim0168b462022-12-27 14:54:35 +09002102 match reader.read_until(b'\n', &mut buf) {
2103 Ok(0) => {
2104 // EOF
2105 return;
2106 }
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002107 Ok(_size) => {
2108 if buf.last() == Some(&b'\n') {
Inseob Kim0168b462022-12-27 14:54:35 +09002109 buf.pop();
Frederick Mayle690ec2c2025-02-05 18:31:33 -08002110 // Logs sent via TTY usually end lines with "\r\n".
2111 if buf.last() == Some(&b'\r') {
2112 buf.pop();
2113 }
Inseob Kim0168b462022-12-27 14:54:35 +09002114 }
2115 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2116 }
2117 Err(e) => {
2118 error!("Could not read console pipe: {:?}", e);
2119 return;
2120 }
2121 };
2122 });
2123
2124 Ok(Some(write_fd))
2125}
2126
Jooyung Han35edb8f2021-07-01 16:17:16 +09002127/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2128/// it doesn't require that T implements Clone.
2129enum BorrowedOrOwned<'a, T> {
2130 Borrowed(&'a T),
2131 Owned(T),
2132}
2133
Chris Wailes73a1eb72025-01-15 11:56:43 -08002134impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002135 fn as_ref(&self) -> &T {
2136 match self {
2137 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002138 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002139 }
2140 }
2141}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002142
2143/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2144#[derive(Debug, Default)]
2145struct VirtualMachineService {
2146 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002147 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002148}
2149
2150impl Interface for VirtualMachineService {}
2151
2152impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002153 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2154 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002155 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002156 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002157 vm.update_payload_state(PayloadState::Started)
2158 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002159 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002160
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002161 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2162 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002163 Ok(())
2164 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002165 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002166 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002167 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002168 }
Inseob Kim2444af92021-08-31 01:22:50 +09002169
Inseob Kimc7d28c72021-10-25 14:28:10 +00002170 fn notifyPayloadReady(&self) -> binder::Result<()> {
2171 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002172 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002173 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002174 vm.update_payload_state(PayloadState::Ready)
2175 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002176 vm.callbacks.notify_payload_ready(cid);
2177 Ok(())
2178 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002179 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002180 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002181 }
2182 }
2183
Inseob Kimc7d28c72021-10-25 14:28:10 +00002184 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2185 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002186 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002187 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002188 vm.update_payload_state(PayloadState::Finished)
2189 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002190 vm.callbacks.notify_payload_finished(cid, exit_code);
2191 Ok(())
2192 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002193 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002194 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002195 }
2196 }
2197
Alan Stokes2bead0d2022-09-05 16:58:34 +01002198 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002199 let cid = self.cid;
2200 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002201 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002202 vm.update_payload_state(PayloadState::Finished)
2203 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002204 vm.callbacks.notify_error(cid, error_code, message);
2205 Ok(())
2206 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002207 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002208 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002209 }
2210 }
Alice Wangc2fec932023-02-23 16:24:02 +00002211
Shikha Panware45e9422024-02-28 21:18:10 +00002212 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2213 if !is_secretkeeper_supported() {
2214 return Err(StatusCode::NAME_NOT_FOUND)?;
2215 }
2216 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2217 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002218 }
2219
Alice Wange64dd182024-01-17 15:57:55 +00002220 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2221 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002222 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002223}
2224
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002225fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002226 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2227 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002228}
2229
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002230impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002231 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002232 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002233 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002234 BinderFeatures::default(),
2235 )
2236 }
2237}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002238
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002239struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2240
2241impl Interface for SecretkeeperProxy {}
2242
2243impl ISecretkeeper for SecretkeeperProxy {
2244 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2245 // Pass the request to the channel, and read the response.
2246 self.0.processSecretManagementRequest(req)
2247 }
2248
2249 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2250 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2251 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2252 }
2253
2254 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2255 self.0.deleteIds(ids)
2256 }
2257
2258 fn deleteAll(&self) -> binder::Result<()> {
2259 self.0.deleteAll()
2260 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002261
2262 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2263 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2264 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2265 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2266 // use this API from the proxy.
2267 Err(ExceptionCode::SECURITY.into())
2268 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002269}
2270
2271struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2272
2273impl Interface for AuthGraphKeyExchangeProxy {}
2274
2275impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2276 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2277 self.0.create()
2278 }
2279
2280 fn init(
2281 &self,
2282 peer_pub_key: &PubKey,
2283 peer_id: &Identity,
2284 peer_nonce: &[u8],
2285 peer_version: i32,
2286 ) -> binder::Result<KeInitResult> {
2287 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2288 }
2289
2290 fn finish(
2291 &self,
2292 peer_pub_key: &PubKey,
2293 peer_id: &Identity,
2294 peer_signature: &SessionIdSignature,
2295 peer_nonce: &[u8],
2296 peer_version: i32,
2297 own_key: &Key,
2298 ) -> binder::Result<SessionInfo> {
2299 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2300 }
2301
2302 fn authenticationComplete(
2303 &self,
2304 peer_signature: &SessionIdSignature,
2305 shared_keys: &[AuthgraphArc; 2],
2306 ) -> binder::Result<[AuthgraphArc; 2]> {
2307 self.0.authenticationComplete(peer_signature, shared_keys)
2308 }
2309}
2310
Inseob Kimecde8c02024-09-03 13:11:08 +09002311// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002312#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002313struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002314 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002315 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002316 path: String,
2317}
2318
2319#[derive(Debug, Default, Deserialize)]
2320struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002321 early_vm: Vec<EarlyVm>,
2322}
2323
Frederick Mayle3a46b272025-02-10 21:55:49 -08002324static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> =
Inseob Kim7e1877b2024-11-07 17:28:56 +09002325 LazyLock::new(|| Mutex::new(HashMap::new()));
2326
Frederick Mayle3a46b272025-02-10 21:55:49 -08002327fn range_for_partition(partition: CallingPartition) -> Range<Cid> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002328 match partition {
Frederick Mayle3a46b272025-02-10 21:55:49 -08002329 CallingPartition::System => 100..200,
2330 CallingPartition::SystemExt | CallingPartition::Product => 200..300,
2331 CallingPartition::Vendor | CallingPartition::Odm => 300..400,
2332 CallingPartition::Unknown => 0..0,
Inseob Kimecde8c02024-09-03 13:11:08 +09002333 }
2334}
2335
Inseob Kim7e1877b2024-11-07 17:28:56 +09002336fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002337 if !xml_path.exists() {
2338 bail!("{} doesn't exist", xml_path.display());
2339 }
2340
2341 let xml =
2342 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2343 let xml = String::from_utf8(xml)
2344 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2345 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2346 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2347
Inseob Kim7e1877b2024-11-07 17:28:56 +09002348 Ok(early_vms.early_vm)
2349}
Inseob Kimecde8c02024-09-03 13:11:08 +09002350
Inseob Kim7e1877b2024-11-07 17:28:56 +09002351fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2352 for early_vm in early_vms {
2353 let cid = early_vm
2354 .cid
2355 .try_into()
2356 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2357
2358 ensure!(
2359 cid_range.contains(&cid),
2360 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2361 early_vm.name
2362 );
2363 }
2364 Ok(())
2365}
2366
Frederick Mayle3a46b272025-02-10 21:55:49 -08002367fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002368 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2369
Frederick Mayle3a46b272025-02-10 21:55:49 -08002370 if let Some(result) = cache.get(&partition) {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002371 return Ok(result.clone());
2372 }
2373
2374 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2375 let mut early_vms = Vec::new();
2376 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2377 match entry {
2378 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2379 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2380 }
2381 }
2382
Frederick Mayle3a46b272025-02-10 21:55:49 -08002383 validate_cid_range(&early_vms, &range_for_partition(partition))
Inseob Kim7e1877b2024-11-07 17:28:56 +09002384 .with_context(|| format!("CID validation for {partition} failed"))?;
2385
Frederick Mayle3a46b272025-02-10 21:55:49 -08002386 cache.insert(partition, early_vms.clone());
Inseob Kim7e1877b2024-11-07 17:28:56 +09002387
2388 Ok(early_vms)
2389}
2390
2391fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2392 let mut found_vm: Option<&EarlyVm> = None;
2393
2394 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002395 if early_vm.name != name {
2396 continue;
2397 }
2398
Inseob Kimecde8c02024-09-03 13:11:08 +09002399 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002400 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002401 }
2402
2403 found_vm = Some(early_vm);
2404 }
2405
Inseob Kim7e1877b2024-11-07 17:28:56 +09002406 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002407}
2408
Frederick Mayle3a46b272025-02-10 21:55:49 -08002409fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002410 let early_vms = get_early_vms_in_partition(partition)
2411 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2412
2413 Ok(find_early_vm(&early_vms, name)
2414 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2415 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002416}
2417
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002418#[cfg(test)]
2419mod tests {
2420 use super::*;
2421
2422 #[test]
2423 fn test_is_allowed_label_for_partition() -> Result<()> {
2424 let expected_results = vec![
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002425 (CallingPartition::System, "u:object_r:system_file:s0", true),
2426 (CallingPartition::System, "u:object_r:apk_data_file:s0", true),
2427 (CallingPartition::System, "u:object_r:app_data_file:s0", false),
2428 (CallingPartition::System, "u:object_r:app_data_file:s0:c512,c768", false),
2429 (CallingPartition::System, "u:object_r:privapp_data_file:s0:c512,c768", false),
2430 (CallingPartition::System, "invalid", false),
2431 (CallingPartition::System, "user:role:apk_data_file:severity:categories", true),
2432 (
2433 CallingPartition::System,
2434 "user:role:apk_data_file:severity:categories:extraneous",
2435 false,
2436 ),
2437 (CallingPartition::System, "u:object_r:vendor_unknowable:s0", false),
2438 (CallingPartition::Vendor, "u:object_r:vendor_unknowable:s0", true),
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002439 ];
2440
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002441 for (calling_partition, label, expected_valid) in expected_results {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002442 let context = SeContext::new(label)?;
Frederick Mayle50c2b6a2025-02-11 18:26:04 -08002443 let result = check_label_is_allowed(&context, calling_partition);
2444 if expected_valid != result.is_ok() {
2445 bail!(
2446 "Expected label {label} to be {} for {calling_partition} partition",
2447 if expected_valid { "allowed" } else { "disallowed" }
2448 );
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002449 }
2450 }
2451 Ok(())
2452 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002453
2454 #[test]
2455 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2456 let apk = tempfile::tempfile().unwrap();
2457 let idsig = tempfile::tempfile().unwrap();
2458
2459 let ret = create_or_update_idsig_file(
2460 &ParcelFileDescriptor::new(apk),
2461 &ParcelFileDescriptor::new(idsig),
2462 );
2463 assert!(ret.is_err(), "should fail");
2464 Ok(())
2465 }
2466
2467 #[test]
2468 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2469 let tmp_dir = tempfile::TempDir::new().unwrap();
2470 let apk = File::open(tmp_dir.path()).unwrap();
2471 let idsig = tempfile::tempfile().unwrap();
2472
2473 let ret = create_or_update_idsig_file(
2474 &ParcelFileDescriptor::new(apk),
2475 &ParcelFileDescriptor::new(idsig),
2476 );
2477 assert!(ret.is_err(), "should fail");
2478 Ok(())
2479 }
2480
2481 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2482 /// on ext4 filesystem is passed.
2483 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2484 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2485 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2486 #[test]
2487 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2488 // APEXes are backed by the ext4.
2489 let apk = File::open("/apex/com.android.virt/").unwrap();
2490 let idsig = tempfile::tempfile().unwrap();
2491
2492 let ret = create_or_update_idsig_file(
2493 &ParcelFileDescriptor::new(apk),
2494 &ParcelFileDescriptor::new(idsig),
2495 );
2496 assert!(ret.is_err(), "should fail");
2497 Ok(())
2498 }
Jiyong Park8d192952023-06-26 14:29:51 +09002499
2500 #[test]
2501 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2502 use std::io::Seek;
2503
2504 // Pick any APK
2505 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2506 let mut idsig = tempfile::tempfile().unwrap();
2507
2508 create_or_update_idsig_file(
2509 &ParcelFileDescriptor::new(apk.try_clone()?),
2510 &ParcelFileDescriptor::new(idsig.try_clone()?),
2511 )?;
2512 let modified_orig = idsig.metadata()?.modified()?;
2513 apk.rewind()?;
2514 idsig.rewind()?;
2515
2516 // Call the function again
2517 create_or_update_idsig_file(
2518 &ParcelFileDescriptor::new(apk.try_clone()?),
2519 &ParcelFileDescriptor::new(idsig.try_clone()?),
2520 )?;
2521 let modified_new = idsig.metadata()?.modified()?;
2522 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2523 Ok(())
2524 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002525
2526 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002527 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2528 use std::io::Read;
2529
2530 // Pick any APK
2531 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2532 let idsig_empty = tempfile::tempfile().unwrap();
2533 let mut idsig_invalid = tempfile::tempfile().unwrap();
2534 idsig_invalid.write_all(b"Oops")?;
2535
2536 // Create new idsig
2537 create_or_update_idsig_file(
2538 &ParcelFileDescriptor::new(apk.try_clone()?),
2539 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2540 )?;
2541 apk.rewind()?;
2542
2543 // Update idsig_invalid
2544 create_or_update_idsig_file(
2545 &ParcelFileDescriptor::new(apk.try_clone()?),
2546 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2547 )?;
2548
2549 // Ensure the 2 idsig files have same size!
2550 assert!(
2551 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2552 "idsig files differ in size"
2553 );
2554 // Ensure the 2 idsig files have same content!
2555 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2556 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2557 }
2558 Ok(())
2559 }
2560 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002561 fn test_append_kernel_param_first_param() {
2562 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2563 append_kernel_param("foo=1", &mut vm_config);
2564 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2565 }
2566
2567 #[test]
2568 fn test_append_kernel_param() {
2569 let mut vm_config =
2570 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2571 append_kernel_param("bar=42", &mut vm_config);
2572 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2573 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002574
Inseob Kim46257382024-01-03 15:41:22 +09002575 fn test_extract_os_name_from_config_path(
2576 path: &Path,
2577 expected_result: Option<&str>,
2578 ) -> Result<()> {
2579 let result = extract_os_name_from_config_path(path);
2580 if result.as_deref() != expected_result {
2581 bail!("Expected {:?} but was {:?}", expected_result, &result)
2582 }
2583 Ok(())
2584 }
2585
2586 #[test]
2587 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2588 test_extract_os_name_from_config_path(
2589 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2590 Some("microdroid"),
2591 )
2592 }
2593
2594 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002595 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2596 test_extract_os_name_from_config_path(
2597 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2598 Some("microdroid_16k"),
2599 )
2600 }
2601
2602 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002603 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2604 test_extract_os_name_from_config_path(
2605 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2606 Some("microdroid_gki-android14-6.1"),
2607 )
2608 }
2609
2610 #[test]
2611 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2612 test_extract_os_name_from_config_path(
2613 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2614 None,
2615 )
2616 }
2617
2618 #[test]
2619 fn test_extract_os_name_from_configs() -> Result<()> {
2620 let tmp_dir = tempfile::TempDir::new()?;
2621 let tmp_dir_path = tmp_dir.path().to_owned();
2622
2623 let mut os_names: HashSet<String> = HashSet::new();
2624 os_names.insert("microdroid".to_owned());
2625 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2626 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2627
2628 // config files
2629 for os_name in &os_names {
2630 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2631 }
2632
2633 // fake files not related to configs
2634 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2635 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2636
2637 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2638 Some(s) => s.to_owned(),
2639 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2640 };
2641
2642 let result = extract_os_names_from_configs(&glob_pattern)?;
2643 if result != os_names {
2644 bail!("Expected {:?} but was {:?}", os_names, result);
2645 }
2646 Ok(())
2647 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002648
2649 #[test]
2650 fn test_find_early_vms_from_xml() -> Result<()> {
2651 let tmp_dir = tempfile::TempDir::new()?;
2652 let tmp_dir_path = tmp_dir.path().to_owned();
2653 let xml_path = tmp_dir_path.join("early_vms.xml");
2654
2655 std::fs::write(
2656 &xml_path,
2657 br#"<?xml version="1.0" encoding="utf-8"?>
2658 <early_vms>
2659 <early_vm>
2660 <name>vm_demo_native_early</name>
2661 <cid>123</cid>
2662 <path>/system/bin/vm_demo_native_early</path>
2663 </early_vm>
2664 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002665 <name>vm_demo_native_early_2</name>
2666 <cid>456</cid>
2667 <path>/system/bin/vm_demo_native_early_2</path>
2668 </early_vm>
2669 </early_vms>
2670 "#,
2671 )?;
2672
2673 let cid_range = 100..1000;
2674
2675 let early_vms = get_early_vms_in_path(&xml_path)?;
2676 validate_cid_range(&early_vms, &cid_range)?;
2677
2678 let test_cases = [
2679 (
2680 "vm_demo_native_early",
2681 EarlyVm {
2682 name: "vm_demo_native_early".to_owned(),
2683 cid: 123,
2684 path: "/system/bin/vm_demo_native_early".to_owned(),
2685 },
2686 ),
2687 (
2688 "vm_demo_native_early_2",
2689 EarlyVm {
2690 name: "vm_demo_native_early_2".to_owned(),
2691 cid: 456,
2692 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2693 },
2694 ),
2695 ];
2696
2697 for (name, expected) in test_cases {
2698 let result = find_early_vm(&early_vms, name)?;
2699 assert_eq!(result, &expected);
2700 }
2701
2702 Ok(())
2703 }
2704
2705 #[test]
2706 fn test_invalid_cid_validation() -> Result<()> {
2707 let tmp_dir = tempfile::TempDir::new()?;
2708 let xml_path = tmp_dir.path().join("early_vms.xml");
2709
2710 let cid_range = 100..1000;
2711
2712 for cid in [-1, 999999] {
2713 std::fs::write(
2714 &xml_path,
2715 format!(
2716 r#"<?xml version="1.0" encoding="utf-8"?>
2717 <early_vms>
2718 <early_vm>
2719 <name>vm_demo_invalid_cid</name>
2720 <cid>{cid}</cid>
2721 <path>/system/bin/vm_demo_invalid_cid</path>
2722 </early_vm>
2723 </early_vms>
2724 "#
2725 ),
2726 )?;
2727
2728 let early_vms = get_early_vms_in_path(&xml_path)?;
2729 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2730 }
2731
2732 Ok(())
2733 }
2734
2735 #[test]
Armelle Laine1a25d982025-01-31 06:39:54 +00002736 fn test_symlink_to_system_ext_supported() -> Result<()> {
2737 let link_path = Path::new("/system/system_ext/file");
2738 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002739 assert_eq!(CallingPartition::SystemExt, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002740 Ok(())
2741 }
2742
2743 #[test]
2744 fn test_symlink_to_product_supported() -> Result<()> {
2745 let link_path = Path::new("/system/product/file");
2746 let partition = find_partition(Some(link_path)).unwrap();
Frederick Mayle3a46b272025-02-10 21:55:49 -08002747 assert_eq!(CallingPartition::Product, partition);
Armelle Laine1a25d982025-01-31 06:39:54 +00002748 Ok(())
2749 }
2750
2751 #[test]
Inseob Kim7e1877b2024-11-07 17:28:56 +09002752 fn test_duplicated_early_vms() -> Result<()> {
2753 let tmp_dir = tempfile::TempDir::new()?;
2754 let tmp_dir_path = tmp_dir.path().to_owned();
2755 let xml_path = tmp_dir_path.join("early_vms.xml");
2756
2757 std::fs::write(
2758 &xml_path,
2759 br#"<?xml version="1.0" encoding="utf-8"?>
2760 <early_vms>
2761 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002762 <name>vm_demo_duplicated_name</name>
2763 <cid>456</cid>
2764 <path>/system/bin/vm_demo_duplicated_name_1</path>
2765 </early_vm>
2766 <early_vm>
2767 <name>vm_demo_duplicated_name</name>
2768 <cid>789</cid>
2769 <path>/system/bin/vm_demo_duplicated_name_2</path>
2770 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002771 </early_vms>
2772 "#,
2773 )?;
2774
2775 let cid_range = 100..1000;
2776
Inseob Kim7e1877b2024-11-07 17:28:56 +09002777 let early_vms = get_early_vms_in_path(&xml_path)?;
2778 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002779
Inseob Kim7e1877b2024-11-07 17:28:56 +09002780 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002781
2782 Ok(())
2783 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002784}