blob: 2d31b873b8debb1403d504560d8e78a18b5c5541 [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,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000034 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000035 DiskImage::DiskImage,
Akilesh Kailash05515dc2024-10-22 21:42:52 -070036 SharedPath::SharedPath,
Jeongik Chac181be72024-03-27 00:18:30 +090037 InputDevice::InputDevice,
Devin Moore407df8f2024-08-27 19:39:16 +000038 IVirtualMachine::{self, BnVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000039 IVirtualMachineCallback::IVirtualMachineCallback,
40 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090041 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000042 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090043 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090044 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000045 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010046 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090047 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000048 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090049};
Inseob Kimecde8c02024-09-03 13:11:08 +090050use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000051use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090052use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000053 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090054};
Shikha Panware45e9422024-02-28 21:18:10 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000056use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
Matt Gilbrideb57abcc2024-10-12 15:26:45 +000057use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000058use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
59 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
60 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
61 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
62 SessionInitiationInfo::SessionInitiationInfo,
63};
Inseob Kim7e1877b2024-11-07 17:28:56 +090064use anyhow::{anyhow, bail, ensure, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090065use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090066use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010067use binder::{
Devin Moore407df8f2024-08-27 19:39:16 +000068 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
69 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000070};
Inseob Kim46257382024-01-03 15:41:22 +090071use glob::glob;
Devin Moorec8800a12024-10-17 17:56:18 +000072use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000073use log::{debug, error, info, warn};
Nikita Ioffe901083f2025-01-20 01:54:28 +000074use microdroid_payload_config::{ApexConfig, ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090075use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000076use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000077use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090078use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090079use serde::Deserialize;
Inseob Kim7e1877b2024-11-07 17:28:56 +090080use std::collections::{HashSet, HashMap};
Andrew Walbrandff3b942021-06-09 15:20:36 +000081use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000082use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090083use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090084use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000085use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090086use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000087use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090088use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090089use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000090use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000091use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010092use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090093use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010094use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000095use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090096use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000097
David Brazdil41d1a872022-10-05 14:44:19 +010098/// The unique ID of a VM used (together with a port number) for vsock communication.
99pub type Cid = u32;
100
David Brazdil4b4c5102022-12-19 22:56:20 +0000101pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
102
Devin Moore407df8f2024-08-27 19:39:16 +0000103/// Vsock privileged ports are below this number.
104const VSOCK_PRIV_PORT_MAX: u32 = 1024;
105
Jooyung Han95884632021-07-06 22:27:54 +0900106/// The size of zero.img.
107/// Gaps in composite disk images are filled with a shared zero.img.
108const ZERO_FILLER_SIZE: u64 = 4096;
109
David Brazdilf50c7a62023-04-19 14:22:42 +0000110/// Magic string for the instance image
111const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
112
113/// Version of the instance image format
114const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
115
Alan Stokes0d1ef782022-09-27 13:46:35 +0100116const MICRODROID_OS_NAME: &str = "microdroid";
117
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000118const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000119 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000120
David Brazdilf50c7a62023-04-19 14:22:42 +0000121const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
122
123/// crosvm requires all partitions to be a multiple of 4KiB.
124const PARTITION_GRANULARITY_BYTES: u64 = 4096;
125
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000126const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
127
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100128pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
129 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900130 if cfg!(early) {
131 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
132 } else {
133 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
134 .expect("Could not connect to VirtualizationServiceInternal")
135 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100136 });
137static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
138 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000139
Inseob Kime3e932d2024-12-16 20:06:57 +0900140static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
141 let calling_exe_link = format!("/proc/{}/exe", get_calling_pid());
142 match fs::read_link(&calling_exe_link) {
143 Ok(calling_exe_path) => Some(calling_exe_path),
144 Err(e) => {
145 // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we
146 // discourage vendor apps, regarding such cases as system is safer.
147 // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of
148 // apps.
149 warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system");
150 None
151 }
152 }
153});
154
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000155fn create_or_update_idsig_file(
156 input_fd: &ParcelFileDescriptor,
157 idsig_fd: &ParcelFileDescriptor,
158) -> Result<()> {
159 let mut input = clone_file(input_fd)?;
160 let metadata = input.metadata().context("failed to get input metadata")?;
161 if !metadata.is_file() {
162 bail!("input is not a regular file");
163 }
Alan Stokes25f69362023-03-06 16:51:54 +0000164 let mut sig =
165 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
166 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000167
168 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900169
170 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
171 // if the idsig file already has the same APK digest.
172 if output.metadata()?.len() > 0 {
173 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
174 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
175 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
176 return Ok(());
177 }
178 }
179 // if we fail to read v4signature from output, that's fine. User can pass a random file.
180 // We will anyway overwrite the file to the v4signature generated from input_fd.
181 }
182
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000183 output
184 .seek(SeekFrom::Start(0))
185 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000186 output.set_len(0).context("failed to set_len on the idsig output")?;
187 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000188 Ok(())
189}
190
Alan Stokes25f69362023-03-06 16:51:54 +0000191fn get_current_sdk() -> Result<u32> {
192 let current_sdk = system_properties::read("ro.build.version.sdk")?;
193 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
194 current_sdk.parse().context("Malformed SDK version")
195}
196
David Brazdil4b4c5102022-12-19 22:56:20 +0000197pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
198 for dir_entry in read_dir(path)? {
199 remove_file(dir_entry?.path())?;
200 }
201 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100202}
203
David Brazdil528e0472022-10-10 15:06:02 +0100204/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000205#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000206pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900207 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000208}
209
Shikha Panward8e35422021-10-11 13:51:27 +0000210impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000211 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000212 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
213 let state = &mut *self.state.lock().unwrap();
214 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000215 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000216 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000217 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
218 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000219 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000220 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000221 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000222 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
223 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000224 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000225 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000226 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000227 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000228 .or(Err(StatusCode::UNKNOWN_ERROR))?;
229 }
230 Ok(())
231 }
232}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000233impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000234 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
235 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000236 ///
237 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000238 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000239 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000240 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900241 console_out_fd: Option<&ParcelFileDescriptor>,
242 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000243 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000244 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000245 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000246 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900247 let ret = self.create_vm_internal(
248 config,
249 console_out_fd,
250 console_in_fd,
251 log_fd,
252 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000253 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900254 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000255 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000256 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000257 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000258
Shikha Panwar61a74b52024-02-16 13:17:01 +0000259 /// Allocate a new instance_id to the VM
260 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000261 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000262 GLOBAL_SERVICE.allocateInstanceId()
263 }
264
Andrew Walbrandff3b942021-06-09 15:20:36 +0000265 /// Initialise an empty partition image of the given size to be used as a writable partition.
266 fn initializeWritablePartition(
267 &self,
268 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000269 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900270 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000271 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900272 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900273 let size_bytes = size_bytes
274 .try_into()
275 .with_context(|| format!("Invalid size: {}", size_bytes))
276 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000277 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000278 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000279 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000280 image
281 .seek(SeekFrom::Start(0))
282 .context("failed to move cursor to start")
283 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900284 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700285 // Set the file length. In most filesystems, this will not allocate any physical disk
286 // space, it will only change the logical size.
287 image
288 .set_len(size_bytes)
289 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900290 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000291
292 match partition_type {
293 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700294 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
295 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000296 _ => Err(Error::new(
297 ErrorKind::Unsupported,
298 format!("Unsupported partition type {:?}", partition_type),
299 )),
300 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900301 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
302 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000303
304 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000305 }
306
Jiyong Park0a248432021-08-20 23:32:39 +0900307 /// Creates or update the idsig file by digesting the input APK file.
308 fn createOrUpdateIdsigFile(
309 &self,
310 input_fd: &ParcelFileDescriptor,
311 idsig_fd: &ParcelFileDescriptor,
312 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900313 check_manage_access()?;
314
Jiyong Park2227eaa2023-08-04 11:59:18 +0900315 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900316 Ok(())
317 }
318
Andrew Walbran320b5602021-03-04 16:11:12 +0000319 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
320 /// and as such is only permitted from the shell user.
321 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000322 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000323 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000324 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900325
326 /// Get a list of assignable device types.
327 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
328 // Delegate to the global service, including checking the permission.
329 GLOBAL_SERVICE.getAssignableDevices()
330 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100331
Inseob Kim46257382024-01-03 15:41:22 +0900332 /// Get a list of supported OSes.
333 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
334 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
335 }
336
Jaewan Kimabd328b2024-12-10 15:59:33 +0900337 /// Get printable debug policy for testing and debugging
338 fn getDebugPolicy(&self) -> binder::Result<String> {
339 let debug_policy = DebugPolicy::from_host();
340 Ok(format!("{debug_policy:?}"))
341 }
342
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100343 /// Returns whether given feature is enabled
344 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
345 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000346 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100347 }
Alice Wange64dd182024-01-17 15:57:55 +0000348
349 fn enableTestAttestation(&self) -> binder::Result<()> {
350 GLOBAL_SERVICE.enableTestAttestation()
351 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000352
353 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
354 check_manage_access()?;
355 GLOBAL_SERVICE.isRemoteAttestationSupported()
356 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000357
358 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
359 // The response is specific to Microdroid. Updatable VMs are only possible if device
360 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
361 // this, however other guest OSes may do things differently.
362 check_manage_access()?;
363 Ok(is_secretkeeper_supported())
364 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000365
Shikha Panwar07d701c2024-03-28 14:43:52 +0000366 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
367 check_manage_access()?;
368 GLOBAL_SERVICE.removeVmInstance(instance_id)
369 }
370
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000371 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
372 check_manage_access()?;
373 GLOBAL_SERVICE.claimVmInstance(instance_id)
374 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000375}
376
Inseob Kimecde8c02024-09-03 13:11:08 +0900377/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
378#[derive(Debug, Default)]
379struct EarlyVmContext {
380 /// The unique CID assigned to the VM for vsock communication.
381 cid: Cid,
382 /// Temporary directory for this VM instance.
383 temp_dir: PathBuf,
384}
385
386impl EarlyVmContext {
387 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
388 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
389 // should trust clients, e.g. they won't run two VMs at the same time
390 let _ = remove_dir_all(&temp_dir);
391 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
392
393 Ok(Self { cid, temp_dir })
394 }
395}
396
397impl Interface for EarlyVmContext {}
398
399impl Drop for EarlyVmContext {
400 fn drop(&mut self) {
401 if let Err(e) = remove_dir_all(&self.temp_dir) {
402 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
403 }
404 }
405}
406
407impl IGlobalVmContext for EarlyVmContext {
408 fn getCid(&self) -> binder::Result<i32> {
409 Ok(self.cid as i32)
410 }
411
412 fn getTemporaryDirectory(&self) -> binder::Result<String> {
413 Ok(self.temp_dir.to_string_lossy().to_string())
414 }
415
416 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
417 Err(Status::new_exception_str(
418 ExceptionCode::UNSUPPORTED_OPERATION,
419 Some("Early VM doesn't support setting host console name"),
420 ))
421 }
422}
423
Inseob Kime3e932d2024-12-16 20:06:57 +0900424fn find_partition(path: Option<&Path>) -> binder::Result<String> {
425 let path = match path {
426 Some(path) => path,
427 None => return Ok("system".to_owned()),
428 };
Inseob Kimf79c5722024-12-16 17:29:57 +0900429 let mut components = path.components();
430 match components.nth(1) {
Inseob Kimecde8c02024-09-03 13:11:08 +0900431 Some(std::path::Component::Normal(partition)) => {
Inseob Kimf79c5722024-12-16 17:29:57 +0900432 if partition != "apex" {
433 return Ok(partition.to_string_lossy().into_owned());
434 }
435
436 // If path is under /apex, find a partition of the preinstalled .apex path
437 let apex_name = match components.next() {
438 Some(std::path::Component::Normal(name)) => name.to_string_lossy(),
439 _ => {
440 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
441 .or_service_specific_exception(-1)
442 }
443 };
444
445 let apex_info_list = ApexInfoList::load()
446 .context("Failed to get apex info list")
447 .or_service_specific_exception(-1)?;
448
449 for apex_info in apex_info_list.list.iter() {
450 if apex_info.name == apex_name {
451 return Ok(apex_info.partition.to_lowercase());
452 }
453 }
454
455 Err(anyhow!("Can't find apex info for '{apex_name}'")).or_service_specific_exception(-1)
Inseob Kimecde8c02024-09-03 13:11:08 +0900456 }
457 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
458 .or_service_specific_exception(-1),
459 }
460}
461
Jiyong Park8611a6c2021-07-09 18:17:44 +0900462impl VirtualizationService {
463 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000464 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900465 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000466
Inseob Kimecde8c02024-09-03 13:11:08 +0900467 fn create_early_vm_context(
468 &self,
469 config: &VirtualMachineConfig,
Inseob Kime3e932d2024-12-16 20:06:57 +0900470 calling_exe_path: Option<&Path>,
Inseob Kimecde8c02024-09-03 13:11:08 +0900471 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
Inseob Kimecde8c02024-09-03 13:11:08 +0900472 let name = match config {
473 VirtualMachineConfig::RawConfig(config) => &config.name,
474 VirtualMachineConfig::AppConfig(config) => &config.name,
475 };
Inseob Kime3e932d2024-12-16 20:06:57 +0900476 let calling_partition = find_partition(calling_exe_path)?;
477 let early_vm = find_early_vm_for_partition(&calling_partition, name)
478 .or_service_specific_exception(-1)?;
479 let calling_exe_path = match calling_exe_path {
480 Some(path) => path,
481 None => {
482 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
483 .or_service_specific_exception(-1)
484 }
485 };
486 if Path::new(&early_vm.path) != calling_exe_path {
Inseob Kimecde8c02024-09-03 13:11:08 +0900487 return Err(anyhow!(
Inseob Kime3e932d2024-12-16 20:06:57 +0900488 "VM '{name}' in partition '{calling_partition}' must be created with '{}', not '{}'",
Inseob Kimecde8c02024-09-03 13:11:08 +0900489 &early_vm.path,
Inseob Kime3e932d2024-12-16 20:06:57 +0900490 calling_exe_path.display()
Inseob Kimecde8c02024-09-03 13:11:08 +0900491 ))
492 .or_service_specific_exception(-1);
493 }
494
495 let cid = early_vm.cid as Cid;
496 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
497
498 let context = EarlyVmContext::new(cid, temp_dir.clone())
499 .context(format!("Can't create early vm contexts for {cid}"))
500 .or_service_specific_exception(-1)?;
Inseob Kimecde8c02024-09-03 13:11:08 +0900501
Jiyong Park690c1ca2024-11-28 18:06:50 +0900502 if requires_vm_service(config) {
503 // Start VM service listening for connections from the new CID on port=CID.
504 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
505 let port = cid;
506 let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
507 .context(format!("Could not start RpcServer on port {port}"))
508 .or_service_specific_exception(-1)?;
509 vm_server.start();
510 Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
511 } else {
512 Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
513 }
Inseob Kimecde8c02024-09-03 13:11:08 +0900514 }
515
David Brazdil209074a2023-01-12 16:44:51 +0000516 fn create_vm_context(
517 &self,
518 requester_debug_pid: pid_t,
Jiyong Park690c1ca2024-11-28 18:06:50 +0900519 config: &VirtualMachineConfig,
David Brazdil209074a2023-01-12 16:44:51 +0000520 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000521 const NUM_ATTEMPTS: usize = 5;
522
523 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000524 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000525 let cid = vm_context.getCid()? as Cid;
526 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900527
528 // We don't need to start the VM service for custom VMs.
529 if !requires_vm_service(config) {
530 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
531 }
532
David Brazdil8cf8f482022-11-23 14:21:26 +0000533 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
534
535 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000536 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000537 match RpcServer::new_vsock(service, cid, port) {
Devin Moore068e6742024-10-28 18:16:25 +0000538 Ok((vm_server, _)) => {
David Brazdil8cf8f482022-11-23 14:21:26 +0000539 vm_server.start();
Jiyong Park690c1ca2024-11-28 18:06:50 +0900540 return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000541 }
542 Err(err) => {
543 warn!("Could not start RpcServer on port {}: {}", port, err);
544 }
545 }
546 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900547 Err(anyhow!("Too many attempts to create VM context failed"))
548 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000549 }
550
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000551 fn create_vm_internal(
552 &self,
553 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900554 console_out_fd: Option<&ParcelFileDescriptor>,
555 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000556 log_fd: Option<&ParcelFileDescriptor>,
557 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000558 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000559 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000560 let requester_uid = get_calling_uid();
561 let requester_debug_pid = get_calling_pid();
562
Nikita Ioffe631717e2023-09-05 13:38:07 +0100563 check_config_features(config)?;
564
Inseob Kimecde8c02024-09-03 13:11:08 +0900565 if cfg!(early) {
566 check_config_allowed_for_early_vms(config)?;
567 }
568
Nikita Ioffeb1416122024-10-22 12:18:49 +0000569 let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
570 info!("callers secontext: {}", caller_secontext);
571
David Brazdil209074a2023-01-12 16:44:51 +0000572 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900573 let (vm_context, cid, temporary_directory) = if cfg!(early) {
Inseob Kime3e932d2024-12-16 20:06:57 +0900574 self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref())?
Inseob Kimecde8c02024-09-03 13:11:08 +0900575 } else {
Jiyong Park690c1ca2024-11-28 18:06:50 +0900576 self.create_vm_context(requester_debug_pid, config)?
Inseob Kimecde8c02024-09-03 13:11:08 +0900577 };
Inseob Kim1119d702022-05-02 18:01:58 +0900578
Alan Stokesfda70842023-12-20 17:50:14 +0000579 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100580 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900581 }
582
Nikita Ioffe5776f082023-02-10 21:38:26 +0000583 let gdb_port = extract_gdb_port(config);
584
585 // Additional permission checks if caller request gdb.
586 if gdb_port.is_some() {
587 check_gdb_allowed(config)?;
588 }
589
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800590 let instance_id = extract_instance_id(config);
Jaewan Kimf43372b2024-12-13 18:33:58 +0900591 let mut device_tree_overlays = vec![];
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800592 if let Some(dt_overlay) =
593 maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
594 {
Jaewan Kimf43372b2024-12-13 18:33:58 +0900595 device_tree_overlays.push(dt_overlay);
596 }
597 if let Some(dtbo) = get_dtbo(config) {
598 let dtbo = File::from(
599 dtbo.as_ref()
600 .try_clone()
601 .context("Failed to create VM DTBO from ParcelFileDescriptor")
602 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
603 );
604 device_tree_overlays.push(dtbo);
605 }
Seungjae Yooec3bc522023-11-09 10:14:30 +0900606
Jaewan Kimf3143242024-03-15 06:56:31 +0000607 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000608 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900609 Some(prepare_ramdump_file(&temporary_directory)?)
610 } else {
611 None
612 };
613
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000614 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900615 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100616 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900617 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100618 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +0100619 let dump_dt_fd = if let Some(fd) = dump_dt_fd {
620 Some(clone_file(fd)?)
621 } else if debug_config.dump_device_tree {
622 Some(prepare_dump_dt_file(&temporary_directory)?)
623 } else {
624 None
625 };
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000626
627 // Counter to generate unique IDs for temporary image files.
628 let mut next_temporary_image_id = 0;
629 // Files which are referred to from composite images. These must be mapped to the crosvm
630 // child process, and not closed before it is started.
631 let mut indirect_files = vec![];
632
Alan Stokes7bc146c2022-10-20 17:10:32 +0100633 let (is_app_config, config) = match config {
634 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
635 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900636 let config = load_app_config(config, &debug_config, &temporary_directory)
637 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900638 *is_protected = config.protectedVm;
639 let message = format!("Failed to load app config: {:?}", e);
640 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900641 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900642 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100643 (true, BorrowedOrOwned::Owned(config))
644 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000645 };
646 let config = config.as_ref();
647 *is_protected = config.protectedVm;
648
Nikita Ioffe9951e4b2024-11-14 17:30:50 +0000649 if !config.teeServices.is_empty() {
650 check_tee_service_permission(&caller_secontext, &config.teeServices)
651 .with_log()
652 .or_binder_exception(ExceptionCode::SECURITY)?;
653 }
Nikita Ioffe13748d22024-10-23 15:10:39 +0000654
Jiyong Park3051ffe2024-11-26 14:41:58 +0900655 let kernel = maybe_clone_file(&config.kernel)?;
656 let initrd = maybe_clone_file(&config.initrd)?;
657
658 if config.protectedVm {
659 // Fail fast with a meaningful error message in case device doesn't support pVMs.
660 check_protected_vm_is_supported()?;
661
662 // In a protected VM, we require custom kernels to come from a trusted source
663 // (b/237054515).
664 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
665
666 // Check if partition images are labeled incorrectly. This is to prevent random images
667 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
668 // from being loaded in a pVM. This applies to everything but the instance image in the
669 // raw config, and everything but the non-executable, generated partitions in the app
670 // config.
671 config
672 .disks
673 .iter()
674 .flat_map(|disk| disk.partitions.iter())
675 .filter(|partition| {
676 if is_app_config {
677 !is_safe_app_partition(&partition.label)
678 } else {
679 !is_safe_raw_partition(&partition.label)
680 }
681 })
682 .try_for_each(check_label_for_partition)
683 .or_service_specific_exception(-1)?;
684 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000685
Inseob Kimff48a7c2024-02-26 22:07:21 +0900686 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
687 // have unstable interfaces.
688 // TODO(b/316431494): remove once Treble interfaces are stabilized.
Inseob Kime3e932d2024-12-16 20:06:57 +0900689 check_partitions_for_files(config, &find_partition(CALLING_EXE_PATH.as_deref())?)
690 .or_service_specific_exception(-1)?;
Inseob Kimff48a7c2024-02-26 22:07:21 +0900691
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000692 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900693 write_zero_filler(&zero_filler_path)
694 .context("Failed to make composite image")
695 .with_log()
696 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000697
698 // Assemble disk images if needed.
699 let disks = config
700 .disks
701 .iter()
702 .map(|disk| {
703 assemble_disk_image(
704 disk,
705 &zero_filler_path,
706 &temporary_directory,
707 &mut next_temporary_image_id,
708 &mut indirect_files,
709 )
710 })
711 .collect::<Result<Vec<DiskFile>, _>>()?;
712
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700713 let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
714
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000715 let (cpus, host_cpu_topology) = match config.cpuTopology {
716 CpuTopology::MATCH_HOST => (None, true),
717 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
Frederick Mayle681254c2024-12-11 19:20:06 -0800718 CpuTopology::CUSTOM => (
719 NonZeroU32::new(
720 u32::try_from(config.customVcpuCount)
721 .context("bad customVcpuCount")
722 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
723 ),
724 false,
725 ),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000726 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900727 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
728 .with_log()
729 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000730 }
731 };
732
Jaewan Kimf43372b2024-12-13 18:33:58 +0900733 let (vfio_devices, dtbo) = match &config.devices {
734 AssignedDevices::Devices(devices) if !devices.is_empty() => {
735 let mut set = HashSet::new();
736 for device in devices.iter() {
737 let path = canonicalize(device)
738 .with_context(|| format!("can't canonicalize {device}"))
739 .or_service_specific_exception(-1)?;
740 if !set.insert(path) {
741 return Err(anyhow!("duplicated device {device}"))
742 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
743 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900744 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900745 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
746 let dtbo_file = File::from(
747 GLOBAL_SERVICE
748 .getDtboFile()?
749 .as_ref()
750 .try_clone()
751 .context("Failed to create VM DTBO from ParcelFileDescriptor")
752 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
753 );
754 (devices, Some(dtbo_file))
Inseob Kim6ef80972023-07-20 17:23:36 +0900755 }
Jaewan Kimf43372b2024-12-13 18:33:58 +0900756 _ => (vec![], None),
Inseob Kim7307a892023-09-14 13:37:58 +0900757 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900758 let display_config = if cfg!(paravirtualized_devices) {
759 config
760 .displayConfig
761 .as_ref()
762 .map(DisplayConfig::new)
763 .transpose()
764 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
765 } else {
766 None
767 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700768 let gpu_config = if cfg!(paravirtualized_devices) {
769 config
770 .gpuConfig
771 .as_ref()
772 .map(GpuConfig::new)
773 .transpose()
774 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
775 } else {
776 None
777 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900778
Jeongik Chac181be72024-03-27 00:18:30 +0900779 let input_device_options = if cfg!(paravirtualized_devices) {
780 config
781 .inputDevices
782 .iter()
783 .map(to_input_device_option_from)
784 .collect::<Result<Vec<InputDeviceOption>, _>>()
785 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
786 } else {
787 vec![]
788 };
789
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900790 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900791 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900792 if *is_protected {
793 return Err(anyhow!("Network feature is not supported for pVM yet"))
794 .with_log()
795 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
796 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900797 Some(File::from(
798 GLOBAL_SERVICE
799 .createTapInterface(&get_this_pid().to_string())?
800 .as_ref()
801 .try_clone()
802 .context("Failed to get TAP interface from ParcelFileDescriptor")
803 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
804 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900805 } else {
806 None
807 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800808
809 let audio_config = if cfg!(paravirtualized_devices) {
810 config.audioConfig.as_ref().map(AudioConfig::new)
811 } else {
812 None
813 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900814
Elie Kheirallah29d72912024-08-07 20:17:26 +0000815 let usb_config = config
816 .usbConfig
817 .as_ref()
818 .map(UsbConfig::new)
819 .unwrap_or(Ok(UsbConfig { controller: false }))
820 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
821
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000822 let detect_hangup = is_app_config && gdb_port.is_none();
823
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000824 // Actually start the VM.
825 let crosvm_config = CrosvmConfig {
826 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000827 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000828 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000829 kernel,
830 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000831 disks,
Akilesh Kailash05515dc2024-10-22 21:42:52 -0700832 shared_paths,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000833 params: config.params.to_owned(),
834 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900835 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700836 memory_mib: config
837 .memoryMib
838 .try_into()
839 .ok()
840 .and_then(NonZeroU32::new)
841 .unwrap_or(NonZeroU32::new(256).unwrap()),
Frederick Mayle384f5b52024-12-06 16:23:23 -0800842 swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000843 cpus,
844 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900845 console_out_fd,
846 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000847 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900848 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000849 indirect_files,
850 platform_version: parse_platform_version_req(&config.platformVersion)?,
Pierre-Clément Tosi3d70d462025-01-07 16:03:24 +0000851 detect_hangup,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000852 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900853 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000854 dtbo,
Jaewan Kimf43372b2024-12-13 18:33:58 +0900855 device_tree_overlays,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900856 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900857 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000858 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900859 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800860 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000861 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700862 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800863 audio_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800864 balloon: config.balloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000865 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000866 dump_dt_fd,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800867 enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
868 instance_id,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000869 };
870 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100871 VmInstance::new(
872 crosvm_config,
873 temporary_directory,
874 requester_uid,
875 requester_debug_pid,
876 vm_context,
877 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900878 .with_context(|| format!("Failed to create VM with config {:?}", config))
879 .with_log()
880 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000881 );
882 state.add_vm(Arc::downgrade(&instance));
883 Ok(VirtualMachine::create(instance))
884 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900885}
886
Alan Stokesfda70842023-12-20 17:50:14 +0000887/// Returns whether a VM config represents a "custom" virtual machine, which requires the
888/// USE_CUSTOM_VIRTUAL_MACHINE.
889fn is_custom_config(config: &VirtualMachineConfig) -> bool {
890 match config {
891 // Any raw (non-Microdroid) VM is considered custom.
892 VirtualMachineConfig::RawConfig(_) => true,
893 VirtualMachineConfig::AppConfig(config) => {
894 // Some features are reserved for platform apps only, even when using
895 // VirtualMachineAppConfig. Almost all of these features are grouped in the
896 // CustomConfig struct:
897 // - controlling CPUs;
898 // - gdbPort is set, meaning that crosvm will start a gdb server;
899 // - using anything other than the default kernel;
900 // - specifying devices to be assigned.
901 if config.customConfig.is_some() {
902 true
903 } else {
904 // Additional custom features not included in CustomConfig:
905 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000906 // - specifying extra APKs;
907 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900908 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000909 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900910 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
911 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000912 }
913 }
914 }
915}
916
Jiyong Park690c1ca2024-11-28 18:06:50 +0900917/// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
918/// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
919/// VM. To handle the exceptional case, we use name as a second criteria; if the name is
920/// "microdroid" we run VirtualMachineService
921fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
922 match config {
923 VirtualMachineConfig::AppConfig(_) => true,
924 VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
925 }
926}
927
Seungjae Yoo14e60182024-02-21 13:28:31 +0900928fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
929 let VirtualMachineConfig::AppConfig(config) = config else {
930 return Ok(None);
931 };
932 let Some(custom_config) = &config.customConfig else {
933 return Ok(None);
934 };
935 let Some(file) = custom_config.vendorImage.as_ref() else {
936 return Ok(None);
937 };
938
939 let file = clone_file(file)?;
940 let size =
941 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
942 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
943 .context("Failed to get vbmeta from microdroid-vendor.img")?;
944
945 for descriptor in vbmeta.descriptors()?.iter() {
946 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
947 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
948 return Ok(Some(root_digest.as_bytes().to_vec()));
949 }
950 }
951 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
952}
953
Jaewan Kimf43372b2024-12-13 18:33:58 +0900954fn maybe_create_reference_dt_overlay(
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000955 config: &VirtualMachineConfig,
Frederick Mayle196ca2b2024-12-18 15:27:43 -0800956 instance_id: &[u8; 64],
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000957 temporary_directory: &Path,
958) -> binder::Result<Option<File>> {
959 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
960 // (e.g. instance-id)
961 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
962 let host_ref_dt = if host_ref_dt.exists()
963 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
964 {
965 Some(host_ref_dt)
966 } else {
967 warn!("VM reference DT doesn't exist in host DT");
968 None
969 };
970
971 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
972 .context("Failed to extract vendor hashtree digest")
973 .or_service_specific_exception(-1)?;
974
Matt Gilbrideaade4272024-12-05 13:52:42 +0000975 let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000976 info!(
977 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
978 match the trusted digest in the pvmfw config, causing the VM to fail to start."
979 );
Alan Stokesf46a17c2025-01-05 15:50:18 +0000980 vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000981 } else {
Matt Gilbrideaade4272024-12-05 13:52:42 +0000982 vec![]
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000983 };
984
Matt Gilbrideaade4272024-12-05 13:52:42 +0000985 let key_material;
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000986 let mut untrusted_props = Vec::with_capacity(2);
987 if cfg!(llpvm_changes) {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000988 untrusted_props.push((c"instance-id", &instance_id[..]));
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000989 let want_updatable = extract_want_updatable(config);
990 if want_updatable && is_secretkeeper_supported() {
991 // Let guest know that it can defer rollback protection to Secretkeeper by setting
992 // an empty property in untrusted node in DT. This enables Updatable VMs.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000993 untrusted_props.push((c"defer-rollback-protection", &[]));
Matt Gilbrideaade4272024-12-05 13:52:42 +0000994 let sk: Strong<dyn ISecretkeeper> =
995 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
996 if sk.getInterfaceVersion()? >= 2 {
997 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
998 key_material = keyMaterial;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000999 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
Matt Gilbrideaade4272024-12-05 13:52:42 +00001000 }
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +00001001 }
1002 }
1003
1004 let device_tree_overlay = if host_ref_dt.is_some()
1005 || !untrusted_props.is_empty()
1006 || !trusted_props.is_empty()
1007 {
1008 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1009 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1010 let fdt =
1011 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1012 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1013 .or_service_specific_exception(-1)?;
1014 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1015 Some(File::open(dt_output).or_service_specific_exception(-1)?)
1016 } else {
1017 None
1018 };
1019 Ok(device_tree_overlay)
1020}
1021
Jaewan Kimf43372b2024-12-13 18:33:58 +09001022fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1023 let VirtualMachineConfig::RawConfig(config) = config else {
1024 return None;
1025 };
1026 match &config.devices {
1027 AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1028 _ => None,
1029 }
1030}
1031
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001032fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +09001033 let file = OpenOptions::new()
1034 .create_new(true)
1035 .read(true)
1036 .write(true)
1037 .open(zero_filler_path)
1038 .with_context(|| "Failed to create zero.img")?;
1039 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +00001040 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +09001041}
1042
David Brazdilf50c7a62023-04-19 14:22:42 +00001043fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1044 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1045 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1046 part.flush()
1047}
1048
1049fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1050 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1051 part.flush()
1052}
1053
1054fn round_up(input: u64, granularity: u64) -> u64 {
1055 if granularity == 0 {
1056 return input;
1057 }
1058 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1059 let result = input.checked_add(granularity - 1).unwrap_or(input);
1060 (result / granularity) * granularity
1061}
1062
Jeongik Chac181be72024-03-27 00:18:30 +09001063fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1064 Ok(match input_device {
1065 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1066 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1067 height: u32::try_from(single_touch.height)?,
1068 width: u32::try_from(single_touch.width)?,
1069 name: if !single_touch.name.is_empty() {
1070 Some(single_touch.name.clone())
1071 } else {
1072 None
1073 },
1074 },
1075 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1076 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1077 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +09001078 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1079 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1080 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +09001081 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1082 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1083 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +09001084 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1085 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1086 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +09001087 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1088 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1089 height: u32::try_from(trackpad.height)?,
1090 width: u32::try_from(trackpad.width)?,
1091 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1092 },
Jeongik Cha10494912024-07-16 11:19:50 +09001093 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1094 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1095 height: u32::try_from(multi_touch.height)?,
1096 width: u32::try_from(multi_touch.width)?,
1097 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1098 },
Jeongik Chac181be72024-03-27 00:18:30 +09001099 })
1100}
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001101
1102fn assemble_shared_paths(
1103 shared_paths: &[SharedPath],
1104 temporary_directory: &Path,
1105) -> Result<Vec<SharedPathConfig>, Status> {
1106 if shared_paths.is_empty() {
1107 return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1108 }
1109
1110 shared_paths
1111 .iter()
1112 .map(|path| {
1113 Ok(SharedPathConfig {
1114 path: path.sharedPath.clone(),
1115 host_uid: path.hostUid,
1116 host_gid: path.hostGid,
1117 guest_uid: path.guestUid,
1118 guest_gid: path.guestGid,
1119 mask: path.mask,
1120 tag: path.tag.clone(),
Akilesh Kailashc9aa0682024-11-25 10:27:24 -08001121 socket_path: temporary_directory
1122 .join(&path.socketPath)
1123 .to_string_lossy()
1124 .to_string(),
1125 socket_fd: maybe_clone_file(&path.socketFd)?,
1126 app_domain: path.appDomain,
Akilesh Kailash05515dc2024-10-22 21:42:52 -07001127 })
1128 })
1129 .collect()
1130}
1131
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001132/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1133///
1134/// This may involve assembling a composite disk from a set of partition images.
1135fn assemble_disk_image(
1136 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +09001137 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001138 temporary_directory: &Path,
1139 next_temporary_image_id: &mut u64,
1140 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +00001141) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001142 let image = if !disk.partitions.is_empty() {
1143 if disk.image.is_some() {
1144 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001145 return Err(anyhow!("DiskImage contains both image and partitions"))
1146 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001147 }
1148
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001149 let composite_image_filenames =
1150 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1151 let (image, partition_files) = make_composite_image(
1152 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +09001153 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001154 &composite_image_filenames.composite,
1155 &composite_image_filenames.header,
1156 &composite_image_filenames.footer,
1157 )
Jiyong Park2227eaa2023-08-04 11:59:18 +09001158 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1159 .with_log()
1160 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001161
1162 // Pass the file descriptors for the various partition files to crosvm when it
1163 // is run.
1164 indirect_files.extend(partition_files);
1165
1166 image
1167 } else if let Some(image) = &disk.image {
1168 clone_file(image)?
1169 } else {
1170 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001171 return Err(anyhow!("DiskImage didn't contain image or partitions."))
1172 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001173 };
1174
1175 Ok(DiskFile { image, writable: disk.writable })
1176}
1177
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001178fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1179 if let Some(ref mut params) = vm_config.params {
1180 params.push(' ');
1181 params.push_str(param)
1182 } else {
1183 vm_config.params = Some(param.to_owned())
1184 }
1185}
1186
Inseob Kim46257382024-01-03 15:41:22 +09001187fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1188 if config.extension()?.to_str()? != "json" {
1189 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001190 }
Inseob Kim46257382024-01-03 15:41:22 +09001191
1192 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1193}
1194
1195fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1196 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1197 let os_names =
1198 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1199
1200 Ok(os_names)
1201}
1202
1203fn get_supported_os_names() -> Result<HashSet<String>> {
1204 if !cfg!(vendor_modules) {
1205 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1206 }
1207
1208 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1209}
1210
1211fn is_valid_os(os_name: &str) -> bool {
1212 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001213}
1214
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001215fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1216 if !cfg!(vendor_modules) {
1217 return false;
1218 }
1219 match config {
1220 VirtualMachineConfig::RawConfig(_) => false,
1221 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1222 }
1223}
1224
Jooyung Han21e9b922021-06-26 04:14:16 +09001225fn load_app_config(
1226 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001227 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001228 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001229) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001230 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1231 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001232 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001233
Shikha Panwar22e70452022-10-10 18:32:55 +00001234 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1235 Some(clone_file(file)?)
1236 } else {
1237 None
1238 };
1239
Alan Stokesfda70842023-12-20 17:50:14 +00001240 let vm_payload_config;
1241 let extra_apk_files: Vec<_>;
1242 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001243 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001244 vm_payload_config =
1245 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1246 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1247 extra_apk_files = vm_payload_config
1248 .extra_apks
1249 .iter()
1250 .enumerate()
1251 .map(|(i, apk)| {
1252 File::open(PathBuf::from(&apk.path))
1253 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1254 })
1255 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001256 }
Alan Stokesfda70842023-12-20 17:50:14 +00001257 Payload::PayloadConfig(payload_config) => {
1258 vm_payload_config = create_vm_payload_config(payload_config)?;
1259 extra_apk_files =
1260 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1261 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001262 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001263
Inseob Kim89b24592024-02-23 18:59:43 +09001264 let payload_config_os = vm_payload_config.os.name.as_str();
1265 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1266 bail!("'os' in payload config is deprecated");
1267 }
1268
Inseob Kim172f9eb2023-11-06 17:02:08 +09001269 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001270 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001271 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001272 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001273 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001274
1275 // It is safe to construct a filename based on the os_name because we've already checked that it
1276 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001277 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1278 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001279 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001280
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001281 if let Some(custom_config) = &config.customConfig {
1282 if let Some(file) = custom_config.customKernelImage.as_ref() {
1283 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1284 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001285 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001286
1287 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001288 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001289 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001290 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001291
Jaewan Kimf43372b2024-12-13 18:33:58 +09001292 vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001293 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001294
1295 for param in custom_config.extraKernelCmdlineParams.iter() {
1296 append_kernel_param(param, &mut vm_config);
1297 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001298
1299 vm_config.teeServices.clone_from(&custom_config.teeServices);
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001300 }
1301
Nikita Ioffed5846dc2024-11-01 18:44:45 +00001302 // Unfortunately specifying page_shift = 14 in bootconfig doesn't enable 16k pages emulation,
1303 // so we need to provide it in the kernel cmdline.
1304 // TODO(b/376901009): remove this after passing page_shift in bootconfig is supported.
1305 if os_name.ends_with("_16k") && cfg!(target_arch = "x86_64") {
1306 append_kernel_param("page_shift=14", &mut vm_config);
1307 }
1308
Andrew Walbrancc045902021-07-27 16:06:17 +00001309 if config.memoryMib > 0 {
1310 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001311 }
1312
Chris Wailes6177c662024-05-09 14:37:44 -07001313 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001314 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001315 vm_config.cpuTopology = config.cpuTopology;
Frederick Mayle681254c2024-12-11 19:20:06 -08001316 if config.cpuTopology == CpuTopology::CUSTOM {
1317 bail!("AppConfig doesn't support CpuTopology::CUSTOM");
1318 }
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001319 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001320 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001321
Shikha Panwar22e70452022-10-10 18:32:55 +00001322 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001323 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001324
1325 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1326 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001327 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001328 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001329 temporary_directory,
1330 apk_file,
1331 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001332 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001333 &vm_payload_config,
1334 &mut vm_config,
1335 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001336
Andrew Walbrancc0db522021-07-12 17:03:42 +00001337 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001338}
1339
Inseob Kime3e932d2024-12-16 20:06:57 +09001340fn check_partition_for_file(fd: &ParcelFileDescriptor, calling_partition: &str) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001341 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1342 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1343
1344 // microdroid vendor image is OK
1345 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1346 {
1347 return Ok(());
1348 }
1349
Inseob Kime3e932d2024-12-16 20:06:57 +09001350 let is_fd_vendor = link.starts_with("/vendor") || link.starts_with("/odm");
1351 let is_caller_vendor = calling_partition == "vendor" || calling_partition == "odm";
1352
1353 if is_fd_vendor != is_caller_vendor {
1354 bail!("{} can't be used for VM client in {calling_partition}", link.display());
Inseob Kimff48a7c2024-02-26 22:07:21 +09001355 }
1356
1357 Ok(())
1358}
1359
Inseob Kime3e932d2024-12-16 20:06:57 +09001360fn check_partitions_for_files(
1361 config: &VirtualMachineRawConfig,
1362 calling_partition: &str,
1363) -> Result<()> {
Inseob Kimff48a7c2024-02-26 22:07:21 +09001364 config
1365 .disks
1366 .iter()
1367 .flat_map(|disk| disk.partitions.iter())
1368 .filter_map(|partition| partition.image.as_ref())
Inseob Kime3e932d2024-12-16 20:06:57 +09001369 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001370
Inseob Kime3e932d2024-12-16 20:06:57 +09001371 config
1372 .disks
1373 .iter()
1374 .filter_map(|disk| disk.image.as_ref())
1375 .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1376
1377 config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1378 config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1379 config
1380 .bootloader
1381 .as_ref()
1382 .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
Inseob Kimff48a7c2024-02-26 22:07:21 +09001383
1384 Ok(())
1385}
1386
Alan Stokes0d1ef782022-09-27 13:46:35 +01001387fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1388 let mut apk_zip = ZipArchive::new(apk_file)?;
1389 let config_file = apk_zip.by_name(config_path)?;
1390 Ok(serde_json::from_reader(config_file)?)
1391}
1392
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001393fn create_vm_payload_config(
1394 payload_config: &VirtualMachinePayloadConfig,
1395) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001396 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1397 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1398 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001399
1400 let payload_binary_name = &payload_config.payloadBinaryName;
1401 if payload_binary_name.contains('/') {
1402 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1403 }
1404
1405 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001406
1407 // The VM only cares about how many there are, these names are actually ignored.
1408 let extra_apk_count = payload_config.extraApks.len();
1409 let extra_apks =
1410 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1411
Nikita Ioffe901083f2025-01-20 01:54:28 +00001412 if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1413 // The only payload delivered via Mainline module in this release requires
1414 // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1415 // APIs, so we use the fact that the payload is granted
1416 // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1417 // com.android.i18n APEX.
1418 // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1419 // Microdroid pVMs.
1420 let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1421 Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1422 } else {
1423 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1424 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001425}
1426
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001427/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001428fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001429 temporary_directory: &Path,
1430 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001431) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001432 let id = *next_temporary_image_id;
1433 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001434 CompositeImageFilenames {
1435 composite: temporary_directory.join(format!("composite-{}.img", id)),
1436 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1437 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1438 }
1439}
1440
1441/// Filenames for a composite disk image, including header and footer partitions.
1442#[derive(Clone, Debug, Eq, PartialEq)]
1443struct CompositeImageFilenames {
1444 /// The composite disk image itself.
1445 composite: PathBuf,
1446 /// The header partition image.
1447 header: PathBuf,
1448 /// The footer partition image.
1449 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001450}
1451
Jiyong Park753553b2021-07-12 21:21:09 +09001452/// Checks whether the caller has a specific permission
1453fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001454 if cfg!(early) {
1455 // Skip permission check for early VMs, in favor of SELinux
1456 return Ok(());
1457 }
David Brazdil1f530702022-10-03 12:18:10 +01001458 let calling_pid = get_calling_pid();
1459 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001460 // Root can do anything
1461 if calling_uid == 0 {
1462 return Ok(());
1463 }
1464 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001465 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001466 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001467 Ok(())
1468 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001469 Err(anyhow!("does not have the {} permission", perm))
1470 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001471 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001472}
1473
Jiyong Park753553b2021-07-12 21:21:09 +09001474/// Check whether the caller of the current Binder method is allowed to manage VMs
1475fn check_manage_access() -> binder::Result<()> {
1476 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1477}
1478
Inseob Kim1119d702022-05-02 18:01:58 +09001479/// Check whether the caller of the current Binder method is allowed to create custom VMs
1480fn check_use_custom_virtual_machine() -> binder::Result<()> {
1481 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1482}
1483
Nikita Ioffe901083f2025-01-20 01:54:28 +00001484/// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1485/// rollback protection schema.
1486fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1487 check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1488}
1489
Alan Stokes185fe112023-01-10 16:20:55 +00001490/// Return whether a partition is exempt from selinux label checks, because we know that it does
1491/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001492fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001493 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001494 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001495 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001496 || label == "microdroid-apk-idsig"
1497 || label == "payload-metadata"
1498 || label.starts_with("extra-idsig-")
1499}
1500
Alice Wangc206b9b2023-08-28 14:13:51 +00001501/// Returns whether a partition with the given label is safe for a raw config VM.
1502fn is_safe_raw_partition(label: &str) -> bool {
1503 label == "vm-instance"
1504}
1505
Alan Stokes185fe112023-01-10 16:20:55 +00001506/// Check that a file SELinux label is acceptable.
1507///
1508/// 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 +09001509/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001510///
1511/// Note that sepolicy must also grant read access for these types to both virtualization
1512/// service and crosvm.
1513///
1514/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1515/// user devices (W^X).
1516fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1517 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001518 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001519 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001520 | "staging_data_file" // updated/staged APEX images
1521 | "system_file" // immutable dm-verity protected partition
1522 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001523 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001524 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001525 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001526 }
1527}
1528
Alan Stokes185fe112023-01-10 16:20:55 +00001529fn check_label_for_partition(partition: &Partition) -> Result<()> {
1530 let file = partition.image.as_ref().unwrap().as_ref();
1531 check_label_is_allowed(&getfilecon(file)?)
1532 .with_context(|| format!("Partition {} invalid", &partition.label))
1533}
1534
1535fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1536 if let Some(f) = kernel {
1537 check_label_for_file(f, "kernel")?;
1538 }
1539 if let Some(f) = initrd {
1540 check_label_for_file(f, "initrd")?;
1541 }
1542 Ok(())
1543}
1544fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1545 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1546}
1547
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001548/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1549#[derive(Debug)]
1550struct VirtualMachine {
1551 instance: Arc<VmInstance>,
1552}
1553
1554impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001555 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001556 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001557 }
1558}
1559
1560impl Interface for VirtualMachine {}
1561
Devin Moore407df8f2024-08-27 19:39:16 +00001562impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001563 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001564 // Don't check permission. The owner of the VM might have passed this binder object to
1565 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001566 Ok(self.instance.cid as i32)
1567 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001568
Andrew Walbran6b650662021-09-07 13:13:23 +00001569 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001570 // Don't check permission. The owner of the VM might have passed this binder object to
1571 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001572 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001573 }
1574
1575 fn registerCallback(
1576 &self,
1577 callback: &Strong<dyn IVirtualMachineCallback>,
1578 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001579 // Don't check permission. The owner of the VM might have passed this binder object to
1580 // others.
1581 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001582 // TODO: Should this give an error if the VM is already dead?
1583 self.instance.callbacks.add(callback.clone());
1584 Ok(())
1585 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001586
Andrew Walbranf8d94112021-09-07 11:45:36 +00001587 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001588 self.instance
1589 .start()
1590 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1591 .with_log()
1592 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001593 }
1594
Inseob Kima446f802022-07-11 19:46:37 +09001595 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001596 self.instance
1597 .kill()
1598 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1599 .with_log()
1600 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001601 }
1602
Keir Fraser48221ba2024-07-12 14:05:02 +00001603 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1604 let balloon = self
1605 .instance
1606 .get_memory_balloon()
1607 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1608 .with_log()
1609 .or_service_specific_exception(-1)?;
1610 Ok(balloon.try_into().unwrap())
1611 }
1612
1613 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001614 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001615 .set_memory_balloon(num_bytes.try_into().unwrap())
1616 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001617 .with_log()
1618 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001619 }
1620
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001621 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001622 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001623 return Err(Status::new_service_specific_error_str(
1624 IVirtualMachine::ERROR_UNEXPECTED,
1625 Some("Virtual Machine is not running"),
1626 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001627 }
Alan Stokes10c47672022-12-13 17:17:08 +00001628 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001629 if port < VSOCK_PRIV_PORT_MAX {
1630 return Err(Status::new_service_specific_error_str(
1631 IVirtualMachine::ERROR_UNEXPECTED,
1632 Some("Can't connect to privileged port {port}"),
1633 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001634 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001635 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1636 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001637 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001638 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001639 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001640
Devin Moore407df8f2024-08-27 19:39:16 +00001641 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1642 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1643 return Err(Status::new_service_specific_error_str(
1644 IVirtualMachine::ERROR_UNEXPECTED,
1645 Some("Virtual Machine is not running"),
1646 ));
1647 }
1648 let port = port as u32;
1649 if port < VSOCK_PRIV_PORT_MAX {
1650 return Err(Status::new_service_specific_error_str(
1651 IVirtualMachine::ERROR_UNEXPECTED,
1652 Some("Can't connect to privileged port {port}"),
1653 ));
1654 }
1655 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001656 let addr = sockaddr_vm {
1657 svm_family: AF_VSOCK as sa_family_t,
1658 svm_reserved1: 0,
1659 svm_port: port,
1660 svm_cid: cid,
1661 svm_zero: [0u8; 4],
1662 };
1663 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001664 let accessor = Accessor::new(name, get_connection_info);
1665 accessor
1666 .as_binder()
1667 .context("The newly created Accessor should always have a binder")
1668 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1669 }
1670
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001671 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1672 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1673 }
Jiyong Park23b67392024-07-04 13:51:42 +09001674
1675 fn suspend(&self) -> binder::Result<()> {
1676 self.instance
1677 .suspend()
1678 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1679 .with_log()
1680 .or_service_specific_exception(-1)
1681 }
1682
1683 fn resume(&self) -> binder::Result<()> {
1684 self.instance
1685 .resume()
1686 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1687 .with_log()
1688 .or_service_specific_exception(-1)
1689 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001690}
1691
1692impl Drop for VirtualMachine {
1693 fn drop(&mut self) {
1694 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001695 if let Err(e) = self.instance.kill() {
1696 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1697 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001698 }
1699}
1700
1701/// A set of Binders to be called back in response to various events on the VM, such as when it
1702/// dies.
1703#[derive(Debug, Default)]
1704pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1705
1706impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001707 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001708 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001709 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001710 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001711 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001712 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001713 }
1714 }
1715 }
1716
Inseob Kim14cb8692021-08-31 21:50:39 +09001717 /// Call all registered callbacks to notify that the payload is ready to serve.
1718 pub fn notify_payload_ready(&self, cid: Cid) {
1719 let callbacks = &*self.0.lock().unwrap();
1720 for callback in callbacks {
1721 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001722 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001723 }
1724 }
1725 }
1726
Inseob Kim2444af92021-08-31 01:22:50 +09001727 /// Call all registered callbacks to notify that the payload has finished.
1728 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1729 let callbacks = &*self.0.lock().unwrap();
1730 for callback in callbacks {
1731 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001732 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001733 }
1734 }
1735 }
1736
Jooyung Handd0a1732021-11-23 15:26:20 +09001737 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001738 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001739 let callbacks = &*self.0.lock().unwrap();
1740 for callback in callbacks {
1741 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001742 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001743 }
1744 }
1745 }
1746
Andrew Walbrandae07162021-03-12 17:05:20 +00001747 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001748 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001749 let callbacks = &*self.0.lock().unwrap();
1750 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001751 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001752 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001753 }
1754 }
1755 }
1756
1757 /// Add a new callback to the set.
1758 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1759 self.0.lock().unwrap().push(callback);
1760 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001761}
1762
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001763/// The mutable state of the VirtualizationService. There should only be one instance of this
1764/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001765#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001766struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001767 /// The VMs which have been started. When VMs are started a weak reference is added to this
1768 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1769 /// the Binder client are dropped the weak reference here will become invalid, and will be
1770 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001771 vms: Vec<Weak<VmInstance>>,
1772}
1773
1774impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001775 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001776 fn vms(&self) -> Vec<Arc<VmInstance>> {
1777 // Attempt to upgrade the weak pointers to strong pointers.
1778 self.vms.iter().filter_map(Weak::upgrade).collect()
1779 }
1780
1781 /// Add a new VM to the list.
1782 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1783 // Garbage collect any entries from the stored list which no longer exist.
1784 self.vms.retain(|vm| vm.strong_count() > 0);
1785
1786 // Actually add the new VM.
1787 self.vms.push(vm);
1788 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001789
Jiyong Park8611a6c2021-07-09 18:17:44 +09001790 /// Get a VM that corresponds to the given cid
1791 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1792 self.vms().into_iter().find(|vm| vm.cid == cid)
1793 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001794}
1795
Andrew Walbran6b650662021-09-07 13:13:23 +00001796/// Gets the `VirtualMachineState` of the given `VmInstance`.
1797fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001798 match &*instance.vm_state.lock().unwrap() {
1799 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1800 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001801 PayloadState::Starting => VirtualMachineState::STARTING,
1802 PayloadState::Started => VirtualMachineState::STARTED,
1803 PayloadState::Ready => VirtualMachineState::READY,
1804 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001805 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001806 },
1807 VmState::Dead => VirtualMachineState::DEAD,
1808 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001809 }
1810}
1811
David Brazdilf50c7a62023-04-19 14:22:42 +00001812/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001813pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1814 file.as_ref()
1815 .try_clone()
1816 .context("Failed to clone File from ParcelFileDescriptor")
1817 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001818 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001819}
1820
Andrew Walbrand3a84182021-09-07 14:48:52 +00001821/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001822fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001823 file.as_ref().map(clone_file).transpose()
1824}
1825
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001826/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001827fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1828 // SAFETY: ownership is transferred from stream to f
1829 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1830 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001831}
1832
Jiyong Parkdcf17412022-02-08 15:07:23 +09001833/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001834fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1835 VersionReq::parse(s)
1836 .with_context(|| format!("Invalid platform version requirement {}", s))
1837 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001838}
1839
Jiyong Parked180932023-02-24 19:55:41 +09001840/// Create the empty ramdump file
1841fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1842 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1843 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1844 // owner) for readout.
1845 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001846 let ramdump = File::create(ramdump_path)
1847 .context("Failed to prepare ramdump file")
1848 .with_log()
1849 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001850 Ok(ramdump)
1851}
1852
Pierre-Clément Tosi9515d0f2024-04-15 15:58:07 +01001853/// Create the empty device tree dump file
1854fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
1855 let path = temporary_directory.join("device_tree.dtb");
1856 let file = File::create(path)
1857 .context("Failed to prepare device tree dump file")
1858 .with_log()
1859 .or_service_specific_exception(-1)?;
1860 Ok(file)
1861}
1862
Nikita Ioffe5776f082023-02-10 21:38:26 +00001863fn is_protected(config: &VirtualMachineConfig) -> bool {
1864 match config {
1865 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1866 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1867 }
1868}
1869
1870fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1871 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001872 return Err(anyhow!("Can't use gdb with protected VMs"))
1873 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001874 }
1875
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001876 if get_debug_level(config) == Some(DebugLevel::NONE) {
1877 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1878 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001879 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001880
1881 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001882}
1883
Shikha Panwar61a74b52024-02-16 13:17:01 +00001884fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1885 match config {
1886 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1887 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1888 }
1889}
1890
Alan Stokesc96b35e2024-05-03 13:21:20 +01001891fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1892 match config {
1893 VirtualMachineConfig::RawConfig(_) => true,
1894 VirtualMachineConfig::AppConfig(config) => {
1895 let Some(custom) = &config.customConfig else { return true };
1896 custom.wantUpdatable
1897 }
1898 }
1899}
1900
Nikita Ioffe5776f082023-02-10 21:38:26 +00001901fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1902 match config {
1903 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001904 VirtualMachineConfig::AppConfig(config) => {
1905 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1906 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001907 }
1908}
1909
Nikita Ioffe631717e2023-09-05 13:38:07 +01001910fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1911 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1912 if let Some(custom_config) = &config.customConfig {
1913 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1914 return Err(anyhow!("vendor modules feature is disabled"))
1915 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1916 }
1917 }
1918 Ok(())
1919}
1920
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001921fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1922 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1923 if let Some(custom_config) = &config.customConfig {
1924 if !custom_config.devices.is_empty() {
1925 return Err(anyhow!("device assignment feature is disabled"))
1926 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1927 }
1928 }
1929 Ok(())
1930}
1931
Alan Stokesfda70842023-12-20 17:50:14 +00001932fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1933 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1934 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1935 if !payload_config.extraApks.is_empty() {
1936 return Err(anyhow!("multi-tenant feature is disabled"))
1937 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1938 }
1939 Ok(())
1940}
1941
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001942fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1943 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1944 if let Some(custom_config) = &config.customConfig {
1945 if !custom_config.extraKernelCmdlineParams.is_empty() {
1946 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1947 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1948 }
1949 }
1950 Ok(())
1951}
1952
Nikita Ioffe99548382024-10-21 15:54:46 +00001953fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
1954 match config {
1955 VirtualMachineConfig::RawConfig(config) => {
1956 if !config.teeServices.is_empty() {
1957 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1958 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1959 }
1960 }
1961 VirtualMachineConfig::AppConfig(config) => {
1962 if let Some(custom_config) = &config.customConfig {
1963 if !custom_config.teeServices.is_empty() {
1964 return Err(anyhow!("tee_services_allowlist feature is disabled"))
1965 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1966 }
1967 }
1968 }
1969 };
1970 Ok(())
1971}
1972
Nikita Ioffef934e812024-07-05 15:44:41 +00001973fn check_protected_vm_is_supported() -> binder::Result<()> {
1974 let is_pvm_supported =
1975 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1976 if is_pvm_supported {
1977 Ok(())
1978 } else {
1979 Err(anyhow!("pVM is not supported"))
1980 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1981 }
1982}
1983
Nikita Ioffe631717e2023-09-05 13:38:07 +01001984fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1985 if !cfg!(vendor_modules) {
1986 check_no_vendor_modules(config)?;
1987 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001988 if !cfg!(device_assignment) {
1989 check_no_devices(config)?;
1990 }
Alan Stokesfda70842023-12-20 17:50:14 +00001991 if !cfg!(multi_tenant) {
1992 check_no_extra_apks(config)?;
1993 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001994 if !cfg!(debuggable_vms_improvements) {
1995 check_no_extra_kernel_cmdline_params(config)?;
1996 }
Nikita Ioffe99548382024-10-21 15:54:46 +00001997 if !cfg!(tee_services_allowlist) {
1998 check_no_tee_services(config)?;
1999 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01002000 Ok(())
2001}
2002
Inseob Kimecde8c02024-09-03 13:11:08 +09002003fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2004 check_no_vendor_modules(config)?;
2005 check_no_devices(config)?;
2006
2007 Ok(())
2008}
2009
Inseob Kim0168b462022-12-27 14:54:35 +09002010fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09002011 fd: Option<&ParcelFileDescriptor>,
2012 tag: String,
2013) -> Result<Option<File>, Status> {
2014 if let Some(fd) = fd {
2015 return Ok(Some(clone_file(fd)?));
2016 }
2017
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002018 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09002019 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09002020
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07002021 let mut reader = BufReader::new(File::from(read_fd));
2022 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09002023
2024 std::thread::spawn(move || loop {
2025 let mut buf = vec![];
2026 match reader.read_until(b'\n', &mut buf) {
2027 Ok(0) => {
2028 // EOF
2029 return;
2030 }
2031 Ok(size) => {
2032 if buf[size - 1] == b'\n' {
2033 buf.pop();
2034 }
2035 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2036 }
2037 Err(e) => {
2038 error!("Could not read console pipe: {:?}", e);
2039 return;
2040 }
2041 };
2042 });
2043
2044 Ok(Some(write_fd))
2045}
2046
Jooyung Han35edb8f2021-07-01 16:17:16 +09002047/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2048/// it doesn't require that T implements Clone.
2049enum BorrowedOrOwned<'a, T> {
2050 Borrowed(&'a T),
2051 Owned(T),
2052}
2053
Chris Wailes73a1eb72025-01-15 11:56:43 -08002054impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
Jooyung Han35edb8f2021-07-01 16:17:16 +09002055 fn as_ref(&self) -> &T {
2056 match self {
2057 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07002058 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09002059 }
2060 }
2061}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002062
2063/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2064#[derive(Debug, Default)]
2065struct VirtualMachineService {
2066 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00002067 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002068}
2069
2070impl Interface for VirtualMachineService {}
2071
2072impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002073 fn notifyPayloadStarted(&self) -> binder::Result<()> {
2074 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09002075 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002076 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002077 vm.update_payload_state(PayloadState::Started)
2078 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01002079 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00002080
Seungjae Yoo6d265d92022-11-15 10:51:33 +09002081 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2082 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09002083 Ok(())
2084 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002085 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002086 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002087 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002088 }
Inseob Kim2444af92021-08-31 01:22:50 +09002089
Inseob Kimc7d28c72021-10-25 14:28:10 +00002090 fn notifyPayloadReady(&self) -> binder::Result<()> {
2091 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09002092 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002093 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002094 vm.update_payload_state(PayloadState::Ready)
2095 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09002096 vm.callbacks.notify_payload_ready(cid);
2097 Ok(())
2098 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002099 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002100 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09002101 }
2102 }
2103
Inseob Kimc7d28c72021-10-25 14:28:10 +00002104 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2105 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09002106 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002107 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002108 vm.update_payload_state(PayloadState::Finished)
2109 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09002110 vm.callbacks.notify_payload_finished(cid, exit_code);
2111 Ok(())
2112 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09002113 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002114 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09002115 }
2116 }
2117
Alan Stokes2bead0d2022-09-05 16:58:34 +01002118 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09002119 let cid = self.cid;
2120 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01002121 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002122 vm.update_payload_state(PayloadState::Finished)
2123 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09002124 vm.callbacks.notify_error(cid, error_code, message);
2125 Ok(())
2126 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00002127 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09002128 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09002129 }
2130 }
Alice Wangc2fec932023-02-23 16:24:02 +00002131
Shikha Panware45e9422024-02-28 21:18:10 +00002132 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2133 if !is_secretkeeper_supported() {
2134 return Err(StatusCode::NAME_NOT_FOUND)?;
2135 }
2136 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2137 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00002138 }
2139
Alice Wange64dd182024-01-17 15:57:55 +00002140 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2141 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00002142 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002143}
2144
Shikha Panwar8707f0f2024-02-28 20:40:42 +00002145fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00002146 binder::is_declared(SECRETKEEPER_IDENTIFIER)
2147 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00002148}
2149
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002150impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00002151 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002152 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00002153 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09002154 BinderFeatures::default(),
2155 )
2156 }
2157}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002158
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002159struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2160
2161impl Interface for SecretkeeperProxy {}
2162
2163impl ISecretkeeper for SecretkeeperProxy {
2164 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2165 // Pass the request to the channel, and read the response.
2166 self.0.processSecretManagementRequest(req)
2167 }
2168
2169 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2170 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2171 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2172 }
2173
2174 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2175 self.0.deleteIds(ids)
2176 }
2177
2178 fn deleteAll(&self) -> binder::Result<()> {
2179 self.0.deleteAll()
2180 }
Matt Gilbrideb57abcc2024-10-12 15:26:45 +00002181
2182 fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2183 // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2184 // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2185 // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2186 // use this API from the proxy.
2187 Err(ExceptionCode::SECURITY.into())
2188 }
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08002189}
2190
2191struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2192
2193impl Interface for AuthGraphKeyExchangeProxy {}
2194
2195impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
2196 fn create(&self) -> binder::Result<SessionInitiationInfo> {
2197 self.0.create()
2198 }
2199
2200 fn init(
2201 &self,
2202 peer_pub_key: &PubKey,
2203 peer_id: &Identity,
2204 peer_nonce: &[u8],
2205 peer_version: i32,
2206 ) -> binder::Result<KeInitResult> {
2207 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2208 }
2209
2210 fn finish(
2211 &self,
2212 peer_pub_key: &PubKey,
2213 peer_id: &Identity,
2214 peer_signature: &SessionIdSignature,
2215 peer_nonce: &[u8],
2216 peer_version: i32,
2217 own_key: &Key,
2218 ) -> binder::Result<SessionInfo> {
2219 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2220 }
2221
2222 fn authenticationComplete(
2223 &self,
2224 peer_signature: &SessionIdSignature,
2225 shared_keys: &[AuthgraphArc; 2],
2226 ) -> binder::Result<[AuthgraphArc; 2]> {
2227 self.0.authenticationComplete(peer_signature, shared_keys)
2228 }
2229}
2230
Inseob Kimecde8c02024-09-03 13:11:08 +09002231// KEEP IN SYNC WITH early_vms.xsd
Inseob Kim7e1877b2024-11-07 17:28:56 +09002232#[derive(Clone, Debug, Deserialize, PartialEq)]
Inseob Kimecde8c02024-09-03 13:11:08 +09002233struct EarlyVm {
Inseob Kimecde8c02024-09-03 13:11:08 +09002234 name: String,
Inseob Kimecde8c02024-09-03 13:11:08 +09002235 cid: i32,
Inseob Kimecde8c02024-09-03 13:11:08 +09002236 path: String,
2237}
2238
2239#[derive(Debug, Default, Deserialize)]
2240struct EarlyVms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002241 early_vm: Vec<EarlyVm>,
2242}
2243
Inseob Kim7e1877b2024-11-07 17:28:56 +09002244static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<String, Vec<EarlyVm>>>> =
2245 LazyLock::new(|| Mutex::new(HashMap::new()));
2246
Inseob Kimecde8c02024-09-03 13:11:08 +09002247fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
2248 match partition {
2249 "system" => Ok(100..200),
2250 "system_ext" | "product" => Ok(200..300),
Inseob Kime3e932d2024-12-16 20:06:57 +09002251 "vendor" | "odm" => Ok(300..400),
Inseob Kimecde8c02024-09-03 13:11:08 +09002252 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
2253 }
2254}
2255
Inseob Kim7e1877b2024-11-07 17:28:56 +09002256fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
Inseob Kimecde8c02024-09-03 13:11:08 +09002257 if !xml_path.exists() {
2258 bail!("{} doesn't exist", xml_path.display());
2259 }
2260
2261 let xml =
2262 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2263 let xml = String::from_utf8(xml)
2264 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2265 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2266 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2267
Inseob Kim7e1877b2024-11-07 17:28:56 +09002268 Ok(early_vms.early_vm)
2269}
Inseob Kimecde8c02024-09-03 13:11:08 +09002270
Inseob Kim7e1877b2024-11-07 17:28:56 +09002271fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2272 for early_vm in early_vms {
2273 let cid = early_vm
2274 .cid
2275 .try_into()
2276 .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2277
2278 ensure!(
2279 cid_range.contains(&cid),
2280 "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2281 early_vm.name
2282 );
2283 }
2284 Ok(())
2285}
2286
2287fn get_early_vms_in_partition(partition: &str) -> Result<Vec<EarlyVm>> {
2288 let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2289
2290 if let Some(result) = cache.get(partition) {
2291 return Ok(result.clone());
2292 }
2293
2294 let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2295 let mut early_vms = Vec::new();
2296 for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2297 match entry {
2298 Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2299 Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2300 }
2301 }
2302
2303 validate_cid_range(&early_vms, &range_for_partition(partition)?)
2304 .with_context(|| format!("CID validation for {partition} failed"))?;
2305
2306 cache.insert(partition.to_owned(), early_vms.clone());
2307
2308 Ok(early_vms)
2309}
2310
2311fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2312 let mut found_vm: Option<&EarlyVm> = None;
2313
2314 for early_vm in early_vms {
Inseob Kimecde8c02024-09-03 13:11:08 +09002315 if early_vm.name != name {
2316 continue;
2317 }
2318
Inseob Kimecde8c02024-09-03 13:11:08 +09002319 if found_vm.is_some() {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002320 bail!("Multiple VMs named '{name}' are found");
Inseob Kimecde8c02024-09-03 13:11:08 +09002321 }
2322
2323 found_vm = Some(early_vm);
2324 }
2325
Inseob Kim7e1877b2024-11-07 17:28:56 +09002326 found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
Inseob Kimecde8c02024-09-03 13:11:08 +09002327}
2328
2329fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
Inseob Kim7e1877b2024-11-07 17:28:56 +09002330 let early_vms = get_early_vms_in_partition(partition)
2331 .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2332
2333 Ok(find_early_vm(&early_vms, name)
2334 .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2335 .clone())
Inseob Kimecde8c02024-09-03 13:11:08 +09002336}
2337
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002338#[cfg(test)]
2339mod tests {
2340 use super::*;
2341
2342 #[test]
2343 fn test_is_allowed_label_for_partition() -> Result<()> {
2344 let expected_results = vec![
2345 ("u:object_r:system_file:s0", true),
2346 ("u:object_r:apk_data_file:s0", true),
2347 ("u:object_r:app_data_file:s0", false),
2348 ("u:object_r:app_data_file:s0:c512,c768", false),
2349 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2350 ("invalid", false),
2351 ("user:role:apk_data_file:severity:categories", true),
2352 ("user:role:apk_data_file:severity:categories:extraneous", false),
2353 ];
2354
2355 for (label, expected_valid) in expected_results {
2356 let context = SeContext::new(label)?;
2357 let result = check_label_is_allowed(&context);
2358 if expected_valid {
2359 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2360 } else if result.is_ok() {
2361 bail!("Expected label {} to be disallowed", label);
2362 }
2363 }
2364 Ok(())
2365 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002366
2367 #[test]
2368 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2369 let apk = tempfile::tempfile().unwrap();
2370 let idsig = tempfile::tempfile().unwrap();
2371
2372 let ret = create_or_update_idsig_file(
2373 &ParcelFileDescriptor::new(apk),
2374 &ParcelFileDescriptor::new(idsig),
2375 );
2376 assert!(ret.is_err(), "should fail");
2377 Ok(())
2378 }
2379
2380 #[test]
2381 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2382 let tmp_dir = tempfile::TempDir::new().unwrap();
2383 let apk = File::open(tmp_dir.path()).unwrap();
2384 let idsig = tempfile::tempfile().unwrap();
2385
2386 let ret = create_or_update_idsig_file(
2387 &ParcelFileDescriptor::new(apk),
2388 &ParcelFileDescriptor::new(idsig),
2389 );
2390 assert!(ret.is_err(), "should fail");
2391 Ok(())
2392 }
2393
2394 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2395 /// on ext4 filesystem is passed.
2396 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2397 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2398 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2399 #[test]
2400 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2401 // APEXes are backed by the ext4.
2402 let apk = File::open("/apex/com.android.virt/").unwrap();
2403 let idsig = tempfile::tempfile().unwrap();
2404
2405 let ret = create_or_update_idsig_file(
2406 &ParcelFileDescriptor::new(apk),
2407 &ParcelFileDescriptor::new(idsig),
2408 );
2409 assert!(ret.is_err(), "should fail");
2410 Ok(())
2411 }
Jiyong Park8d192952023-06-26 14:29:51 +09002412
2413 #[test]
2414 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2415 use std::io::Seek;
2416
2417 // Pick any APK
2418 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2419 let mut idsig = tempfile::tempfile().unwrap();
2420
2421 create_or_update_idsig_file(
2422 &ParcelFileDescriptor::new(apk.try_clone()?),
2423 &ParcelFileDescriptor::new(idsig.try_clone()?),
2424 )?;
2425 let modified_orig = idsig.metadata()?.modified()?;
2426 apk.rewind()?;
2427 idsig.rewind()?;
2428
2429 // Call the function again
2430 create_or_update_idsig_file(
2431 &ParcelFileDescriptor::new(apk.try_clone()?),
2432 &ParcelFileDescriptor::new(idsig.try_clone()?),
2433 )?;
2434 let modified_new = idsig.metadata()?.modified()?;
2435 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2436 Ok(())
2437 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002438
2439 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002440 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2441 use std::io::Read;
2442
2443 // Pick any APK
2444 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2445 let idsig_empty = tempfile::tempfile().unwrap();
2446 let mut idsig_invalid = tempfile::tempfile().unwrap();
2447 idsig_invalid.write_all(b"Oops")?;
2448
2449 // Create new idsig
2450 create_or_update_idsig_file(
2451 &ParcelFileDescriptor::new(apk.try_clone()?),
2452 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2453 )?;
2454 apk.rewind()?;
2455
2456 // Update idsig_invalid
2457 create_or_update_idsig_file(
2458 &ParcelFileDescriptor::new(apk.try_clone()?),
2459 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2460 )?;
2461
2462 // Ensure the 2 idsig files have same size!
2463 assert!(
2464 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2465 "idsig files differ in size"
2466 );
2467 // Ensure the 2 idsig files have same content!
2468 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2469 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2470 }
2471 Ok(())
2472 }
2473 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002474 fn test_append_kernel_param_first_param() {
2475 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2476 append_kernel_param("foo=1", &mut vm_config);
2477 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2478 }
2479
2480 #[test]
2481 fn test_append_kernel_param() {
2482 let mut vm_config =
2483 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2484 append_kernel_param("bar=42", &mut vm_config);
2485 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2486 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002487
Inseob Kim46257382024-01-03 15:41:22 +09002488 fn test_extract_os_name_from_config_path(
2489 path: &Path,
2490 expected_result: Option<&str>,
2491 ) -> Result<()> {
2492 let result = extract_os_name_from_config_path(path);
2493 if result.as_deref() != expected_result {
2494 bail!("Expected {:?} but was {:?}", expected_result, &result)
2495 }
2496 Ok(())
2497 }
2498
2499 #[test]
2500 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2501 test_extract_os_name_from_config_path(
2502 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2503 Some("microdroid"),
2504 )
2505 }
2506
2507 #[test]
Nikita Ioffef49350e2024-11-01 16:11:48 +00002508 fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2509 test_extract_os_name_from_config_path(
2510 Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2511 Some("microdroid_16k"),
2512 )
2513 }
2514
2515 #[test]
Inseob Kim46257382024-01-03 15:41:22 +09002516 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2517 test_extract_os_name_from_config_path(
2518 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2519 Some("microdroid_gki-android14-6.1"),
2520 )
2521 }
2522
2523 #[test]
2524 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2525 test_extract_os_name_from_config_path(
2526 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2527 None,
2528 )
2529 }
2530
2531 #[test]
2532 fn test_extract_os_name_from_configs() -> Result<()> {
2533 let tmp_dir = tempfile::TempDir::new()?;
2534 let tmp_dir_path = tmp_dir.path().to_owned();
2535
2536 let mut os_names: HashSet<String> = HashSet::new();
2537 os_names.insert("microdroid".to_owned());
2538 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2539 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2540
2541 // config files
2542 for os_name in &os_names {
2543 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2544 }
2545
2546 // fake files not related to configs
2547 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2548 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2549
2550 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2551 Some(s) => s.to_owned(),
2552 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2553 };
2554
2555 let result = extract_os_names_from_configs(&glob_pattern)?;
2556 if result != os_names {
2557 bail!("Expected {:?} but was {:?}", os_names, result);
2558 }
2559 Ok(())
2560 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002561
2562 #[test]
2563 fn test_find_early_vms_from_xml() -> Result<()> {
2564 let tmp_dir = tempfile::TempDir::new()?;
2565 let tmp_dir_path = tmp_dir.path().to_owned();
2566 let xml_path = tmp_dir_path.join("early_vms.xml");
2567
2568 std::fs::write(
2569 &xml_path,
2570 br#"<?xml version="1.0" encoding="utf-8"?>
2571 <early_vms>
2572 <early_vm>
2573 <name>vm_demo_native_early</name>
2574 <cid>123</cid>
2575 <path>/system/bin/vm_demo_native_early</path>
2576 </early_vm>
2577 <early_vm>
Inseob Kim7e1877b2024-11-07 17:28:56 +09002578 <name>vm_demo_native_early_2</name>
2579 <cid>456</cid>
2580 <path>/system/bin/vm_demo_native_early_2</path>
2581 </early_vm>
2582 </early_vms>
2583 "#,
2584 )?;
2585
2586 let cid_range = 100..1000;
2587
2588 let early_vms = get_early_vms_in_path(&xml_path)?;
2589 validate_cid_range(&early_vms, &cid_range)?;
2590
2591 let test_cases = [
2592 (
2593 "vm_demo_native_early",
2594 EarlyVm {
2595 name: "vm_demo_native_early".to_owned(),
2596 cid: 123,
2597 path: "/system/bin/vm_demo_native_early".to_owned(),
2598 },
2599 ),
2600 (
2601 "vm_demo_native_early_2",
2602 EarlyVm {
2603 name: "vm_demo_native_early_2".to_owned(),
2604 cid: 456,
2605 path: "/system/bin/vm_demo_native_early_2".to_owned(),
2606 },
2607 ),
2608 ];
2609
2610 for (name, expected) in test_cases {
2611 let result = find_early_vm(&early_vms, name)?;
2612 assert_eq!(result, &expected);
2613 }
2614
2615 Ok(())
2616 }
2617
2618 #[test]
2619 fn test_invalid_cid_validation() -> Result<()> {
2620 let tmp_dir = tempfile::TempDir::new()?;
2621 let xml_path = tmp_dir.path().join("early_vms.xml");
2622
2623 let cid_range = 100..1000;
2624
2625 for cid in [-1, 999999] {
2626 std::fs::write(
2627 &xml_path,
2628 format!(
2629 r#"<?xml version="1.0" encoding="utf-8"?>
2630 <early_vms>
2631 <early_vm>
2632 <name>vm_demo_invalid_cid</name>
2633 <cid>{cid}</cid>
2634 <path>/system/bin/vm_demo_invalid_cid</path>
2635 </early_vm>
2636 </early_vms>
2637 "#
2638 ),
2639 )?;
2640
2641 let early_vms = get_early_vms_in_path(&xml_path)?;
2642 assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2643 }
2644
2645 Ok(())
2646 }
2647
2648 #[test]
2649 fn test_duplicated_early_vms() -> Result<()> {
2650 let tmp_dir = tempfile::TempDir::new()?;
2651 let tmp_dir_path = tmp_dir.path().to_owned();
2652 let xml_path = tmp_dir_path.join("early_vms.xml");
2653
2654 std::fs::write(
2655 &xml_path,
2656 br#"<?xml version="1.0" encoding="utf-8"?>
2657 <early_vms>
2658 <early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002659 <name>vm_demo_duplicated_name</name>
2660 <cid>456</cid>
2661 <path>/system/bin/vm_demo_duplicated_name_1</path>
2662 </early_vm>
2663 <early_vm>
2664 <name>vm_demo_duplicated_name</name>
2665 <cid>789</cid>
2666 <path>/system/bin/vm_demo_duplicated_name_2</path>
2667 </early_vm>
Inseob Kimecde8c02024-09-03 13:11:08 +09002668 </early_vms>
2669 "#,
2670 )?;
2671
2672 let cid_range = 100..1000;
2673
Inseob Kim7e1877b2024-11-07 17:28:56 +09002674 let early_vms = get_early_vms_in_path(&xml_path)?;
2675 validate_cid_range(&early_vms, &cid_range)?;
Inseob Kimecde8c02024-09-03 13:11:08 +09002676
Inseob Kim7e1877b2024-11-07 17:28:56 +09002677 assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
Inseob Kimecde8c02024-09-03 13:11:08 +09002678
2679 Ok(())
2680 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002681}