blob: 4b203d63503295e53541ed49cf13da0f372a521d [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;
Elie Kheirallah29d72912024-08-07 20:17:26 +000020use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
Jaewan Kim61f86142023-03-28 15:12:52 +090021use crate::debug_config::DebugConfig;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000022use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
Nikita Ioffe5dfddf22023-06-29 16:11:26 +010023use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090024use crate::selinux::{getfilecon, 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::{
Inseob Kim53d0b212023-07-20 16:58:37 +090032 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000033 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Jeongik Chac181be72024-03-27 00:18:30 +090035 InputDevice::InputDevice,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010036 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000037 IVirtualMachineCallback::IVirtualMachineCallback,
38 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090039 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000040 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090041 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090042 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000043 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010044 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090045 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000046 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090047};
Inseob Kimecde8c02024-09-03 13:11:08 +090048use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
David Brazdilafc9a9e2023-01-12 16:08:10 +000049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090050use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000051 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090052};
Shikha Panware45e9422024-02-28 21:18:10 +000053use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000054use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
55use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
56 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
57 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
58 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
59 SessionInitiationInfo::SessionInitiationInfo,
60};
Alan Stokes25f69362023-03-06 16:51:54 +000061use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090062use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090063use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010064use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000065 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
66 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090067 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000068};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000069use cstr::cstr;
Inseob Kim46257382024-01-03 15:41:22 +090070use glob::glob;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000071use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090072use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090073use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000074use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000075use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090076use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090077use serde::Deserialize;
Inseob Kim6ef80972023-07-20 17:23:36 +090078use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000079use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000080use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090081use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090082use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000083use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090084use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000085use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090086use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090087use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000088use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000089use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010090use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090091use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010092use vmconfig::{VmConfig, get_debug_level};
David Brazdilafc9a9e2023-01-12 16:08:10 +000093use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090094use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000095
David Brazdil41d1a872022-10-05 14:44:19 +010096/// The unique ID of a VM used (together with a port number) for vsock communication.
97pub type Cid = u32;
98
David Brazdil4b4c5102022-12-19 22:56:20 +000099pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
100
Jooyung Han95884632021-07-06 22:27:54 +0900101/// The size of zero.img.
102/// Gaps in composite disk images are filled with a shared zero.img.
103const ZERO_FILLER_SIZE: u64 = 4096;
104
David Brazdilf50c7a62023-04-19 14:22:42 +0000105/// Magic string for the instance image
106const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
107
108/// Version of the instance image format
109const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
110
Alan Stokes0d1ef782022-09-27 13:46:35 +0100111const MICRODROID_OS_NAME: &str = "microdroid";
112
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000113const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000114 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000115
David Brazdilf50c7a62023-04-19 14:22:42 +0000116const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
117
118/// crosvm requires all partitions to be a multiple of 4KiB.
119const PARTITION_GRANULARITY_BYTES: u64 = 4096;
120
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000121const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
122
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100123pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
124 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900125 if cfg!(early) {
126 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
127 } else {
128 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
129 .expect("Could not connect to VirtualizationServiceInternal")
130 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100131 });
132static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
133 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000134
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000135fn create_or_update_idsig_file(
136 input_fd: &ParcelFileDescriptor,
137 idsig_fd: &ParcelFileDescriptor,
138) -> Result<()> {
139 let mut input = clone_file(input_fd)?;
140 let metadata = input.metadata().context("failed to get input metadata")?;
141 if !metadata.is_file() {
142 bail!("input is not a regular file");
143 }
Alan Stokes25f69362023-03-06 16:51:54 +0000144 let mut sig =
145 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
146 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000147
148 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900149
150 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
151 // if the idsig file already has the same APK digest.
152 if output.metadata()?.len() > 0 {
153 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
154 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
155 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
156 return Ok(());
157 }
158 }
159 // if we fail to read v4signature from output, that's fine. User can pass a random file.
160 // We will anyway overwrite the file to the v4signature generated from input_fd.
161 }
162
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000163 output
164 .seek(SeekFrom::Start(0))
165 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000166 output.set_len(0).context("failed to set_len on the idsig output")?;
167 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000168 Ok(())
169}
170
Alan Stokes25f69362023-03-06 16:51:54 +0000171fn get_current_sdk() -> Result<u32> {
172 let current_sdk = system_properties::read("ro.build.version.sdk")?;
173 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
174 current_sdk.parse().context("Malformed SDK version")
175}
176
David Brazdil4b4c5102022-12-19 22:56:20 +0000177pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
178 for dir_entry in read_dir(path)? {
179 remove_file(dir_entry?.path())?;
180 }
181 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100182}
183
David Brazdil528e0472022-10-10 15:06:02 +0100184/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000185#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000186pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900187 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000188}
189
Shikha Panward8e35422021-10-11 13:51:27 +0000190impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000191 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000192 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
193 let state = &mut *self.state.lock().unwrap();
194 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000195 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000196 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000197 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
198 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000199 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000200 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000201 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000202 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
203 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000204 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000205 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000206 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000207 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000208 .or(Err(StatusCode::UNKNOWN_ERROR))?;
209 }
210 Ok(())
211 }
212}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000213impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000214 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
215 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000216 ///
217 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000218 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000219 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000220 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900221 console_out_fd: Option<&ParcelFileDescriptor>,
222 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000223 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000224 dump_dt_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000225 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000226 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900227 let ret = self.create_vm_internal(
228 config,
229 console_out_fd,
230 console_in_fd,
231 log_fd,
232 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000233 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900234 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000235 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000236 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000237 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000238
Shikha Panwar61a74b52024-02-16 13:17:01 +0000239 /// Allocate a new instance_id to the VM
240 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000241 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000242 GLOBAL_SERVICE.allocateInstanceId()
243 }
244
Andrew Walbrandff3b942021-06-09 15:20:36 +0000245 /// Initialise an empty partition image of the given size to be used as a writable partition.
246 fn initializeWritablePartition(
247 &self,
248 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000249 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900250 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000251 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900252 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900253 let size_bytes = size_bytes
254 .try_into()
255 .with_context(|| format!("Invalid size: {}", size_bytes))
256 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000257 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000258 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000259 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000260 image
261 .seek(SeekFrom::Start(0))
262 .context("failed to move cursor to start")
263 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900264 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700265 // Set the file length. In most filesystems, this will not allocate any physical disk
266 // space, it will only change the logical size.
267 image
268 .set_len(size_bytes)
269 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900270 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000271
272 match partition_type {
273 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700274 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
275 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000276 _ => Err(Error::new(
277 ErrorKind::Unsupported,
278 format!("Unsupported partition type {:?}", partition_type),
279 )),
280 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900281 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
282 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000283
284 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000285 }
286
Jiyong Park0a248432021-08-20 23:32:39 +0900287 /// Creates or update the idsig file by digesting the input APK file.
288 fn createOrUpdateIdsigFile(
289 &self,
290 input_fd: &ParcelFileDescriptor,
291 idsig_fd: &ParcelFileDescriptor,
292 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900293 check_manage_access()?;
294
Jiyong Park2227eaa2023-08-04 11:59:18 +0900295 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900296 Ok(())
297 }
298
Andrew Walbran320b5602021-03-04 16:11:12 +0000299 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
300 /// and as such is only permitted from the shell user.
301 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000302 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000303 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000304 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900305
306 /// Get a list of assignable device types.
307 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
308 // Delegate to the global service, including checking the permission.
309 GLOBAL_SERVICE.getAssignableDevices()
310 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100311
Inseob Kim46257382024-01-03 15:41:22 +0900312 /// Get a list of supported OSes.
313 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
314 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
315 }
316
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100317 /// Returns whether given feature is enabled
318 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
319 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000320 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100321 }
Alice Wange64dd182024-01-17 15:57:55 +0000322
323 fn enableTestAttestation(&self) -> binder::Result<()> {
324 GLOBAL_SERVICE.enableTestAttestation()
325 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000326
327 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
328 check_manage_access()?;
329 GLOBAL_SERVICE.isRemoteAttestationSupported()
330 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000331
332 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
333 // The response is specific to Microdroid. Updatable VMs are only possible if device
334 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
335 // this, however other guest OSes may do things differently.
336 check_manage_access()?;
337 Ok(is_secretkeeper_supported())
338 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000339
Shikha Panwar07d701c2024-03-28 14:43:52 +0000340 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
341 check_manage_access()?;
342 GLOBAL_SERVICE.removeVmInstance(instance_id)
343 }
344
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000345 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
346 check_manage_access()?;
347 GLOBAL_SERVICE.claimVmInstance(instance_id)
348 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000349}
350
Inseob Kimecde8c02024-09-03 13:11:08 +0900351/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
352#[derive(Debug, Default)]
353struct EarlyVmContext {
354 /// The unique CID assigned to the VM for vsock communication.
355 cid: Cid,
356 /// Temporary directory for this VM instance.
357 temp_dir: PathBuf,
358}
359
360impl EarlyVmContext {
361 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
362 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
363 // should trust clients, e.g. they won't run two VMs at the same time
364 let _ = remove_dir_all(&temp_dir);
365 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
366
367 Ok(Self { cid, temp_dir })
368 }
369}
370
371impl Interface for EarlyVmContext {}
372
373impl Drop for EarlyVmContext {
374 fn drop(&mut self) {
375 if let Err(e) = remove_dir_all(&self.temp_dir) {
376 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
377 }
378 }
379}
380
381impl IGlobalVmContext for EarlyVmContext {
382 fn getCid(&self) -> binder::Result<i32> {
383 Ok(self.cid as i32)
384 }
385
386 fn getTemporaryDirectory(&self) -> binder::Result<String> {
387 Ok(self.temp_dir.to_string_lossy().to_string())
388 }
389
390 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
391 Err(Status::new_exception_str(
392 ExceptionCode::UNSUPPORTED_OPERATION,
393 Some("Early VM doesn't support setting host console name"),
394 ))
395 }
396}
397
398fn find_partition(path: &Path) -> binder::Result<String> {
399 match path.components().nth(1) {
400 Some(std::path::Component::Normal(partition)) => {
401 Ok(partition.to_string_lossy().into_owned())
402 }
403 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
404 .or_service_specific_exception(-1),
405 }
406}
407
Jiyong Park8611a6c2021-07-09 18:17:44 +0900408impl VirtualizationService {
409 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000410 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900411 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000412
Inseob Kimecde8c02024-09-03 13:11:08 +0900413 fn create_early_vm_context(
414 &self,
415 config: &VirtualMachineConfig,
416 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
417 let calling_exe_path = format!("/proc/{}/exe", get_calling_pid());
418 let link = fs::read_link(&calling_exe_path)
419 .context(format!("can't read_link '{calling_exe_path}'"))
420 .or_service_specific_exception(-1)?;
421 let partition = find_partition(&link)?;
422
423 let name = match config {
424 VirtualMachineConfig::RawConfig(config) => &config.name,
425 VirtualMachineConfig::AppConfig(config) => &config.name,
426 };
427 let early_vm =
428 find_early_vm_for_partition(&partition, name).or_service_specific_exception(-1)?;
429 if Path::new(&early_vm.path) != link {
430 return Err(anyhow!(
431 "VM '{name}' in partition '{partition}' must be created with '{}', not '{}'",
432 &early_vm.path,
433 link.display()
434 ))
435 .or_service_specific_exception(-1);
436 }
437
438 let cid = early_vm.cid as Cid;
439 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
440
441 let context = EarlyVmContext::new(cid, temp_dir.clone())
442 .context(format!("Can't create early vm contexts for {cid}"))
443 .or_service_specific_exception(-1)?;
444 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
445
446 // Start VM service listening for connections from the new CID on port=CID.
447 let port = cid;
448 let vm_server = RpcServer::new_vsock(service, cid, port)
449 .context(format!("Could not start RpcServer on port {port}"))
450 .or_service_specific_exception(-1)?;
451 vm_server.start();
452 Ok((VmContext::new(Strong::new(Box::new(context)), vm_server), cid, temp_dir))
453 }
454
David Brazdil209074a2023-01-12 16:44:51 +0000455 fn create_vm_context(
456 &self,
457 requester_debug_pid: pid_t,
458 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000459 const NUM_ATTEMPTS: usize = 5;
460
461 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000462 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000463 let cid = vm_context.getCid()? as Cid;
464 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000465 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
466
467 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000468 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000469 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000470 Ok(vm_server) => {
471 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000472 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000473 }
474 Err(err) => {
475 warn!("Could not start RpcServer on port {}: {}", port, err);
476 }
477 }
478 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900479 Err(anyhow!("Too many attempts to create VM context failed"))
480 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000481 }
482
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000483 fn create_vm_internal(
484 &self,
485 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900486 console_out_fd: Option<&ParcelFileDescriptor>,
487 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000488 log_fd: Option<&ParcelFileDescriptor>,
489 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000490 dump_dt_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000491 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000492 let requester_uid = get_calling_uid();
493 let requester_debug_pid = get_calling_pid();
494
Nikita Ioffe631717e2023-09-05 13:38:07 +0100495 check_config_features(config)?;
496
Inseob Kimecde8c02024-09-03 13:11:08 +0900497 if cfg!(early) {
498 check_config_allowed_for_early_vms(config)?;
499 }
500
David Brazdil209074a2023-01-12 16:44:51 +0000501 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900502 let (vm_context, cid, temporary_directory) = if cfg!(early) {
503 self.create_early_vm_context(config)?
504 } else {
505 self.create_vm_context(requester_debug_pid)?
506 };
Inseob Kim1119d702022-05-02 18:01:58 +0900507
Alan Stokesfda70842023-12-20 17:50:14 +0000508 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100509 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900510 }
511
Nikita Ioffe5776f082023-02-10 21:38:26 +0000512 let gdb_port = extract_gdb_port(config);
513
514 // Additional permission checks if caller request gdb.
515 if gdb_port.is_some() {
516 check_gdb_allowed(config)?;
517 }
518
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000519 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900520
Jaewan Kimf3143242024-03-15 06:56:31 +0000521 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000522 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900523 Some(prepare_ramdump_file(&temporary_directory)?)
524 } else {
525 None
526 };
527
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000528 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900529 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100530 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900531 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100532 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000533 let dump_dt_fd = dump_dt_fd.map(clone_file).transpose()?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000534
535 // Counter to generate unique IDs for temporary image files.
536 let mut next_temporary_image_id = 0;
537 // Files which are referred to from composite images. These must be mapped to the crosvm
538 // child process, and not closed before it is started.
539 let mut indirect_files = vec![];
540
Alan Stokes7bc146c2022-10-20 17:10:32 +0100541 let (is_app_config, config) = match config {
542 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
543 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900544 let config = load_app_config(config, &debug_config, &temporary_directory)
545 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900546 *is_protected = config.protectedVm;
547 let message = format!("Failed to load app config: {:?}", e);
548 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900549 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900550 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100551 (true, BorrowedOrOwned::Owned(config))
552 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000553 };
554 let config = config.as_ref();
555 *is_protected = config.protectedVm;
556
557 // Check if partition images are labeled incorrectly. This is to prevent random images
558 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100559 // being loaded in a pVM. This applies to everything but the instance image in the raw
560 // config, and everything but the non-executable, generated partitions in the app
561 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000562 config
563 .disks
564 .iter()
565 .flat_map(|disk| disk.partitions.iter())
566 .filter(|partition| {
567 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100568 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000569 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000570 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000571 }
572 })
573 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900574 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000575
Inseob Kimff48a7c2024-02-26 22:07:21 +0900576 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
577 // have unstable interfaces.
578 // TODO(b/316431494): remove once Treble interfaces are stabilized.
579 check_partitions_for_files(config).or_service_specific_exception(-1)?;
580
Alan Stokes185fe112023-01-10 16:20:55 +0000581 let kernel = maybe_clone_file(&config.kernel)?;
582 let initrd = maybe_clone_file(&config.initrd)?;
583
Alan Stokes185fe112023-01-10 16:20:55 +0000584 if config.protectedVm {
Nikita Ioffef934e812024-07-05 15:44:41 +0000585 // In a protected VM, we require custom kernels to come from a trusted source
586 // (b/237054515).
Jiyong Park2227eaa2023-08-04 11:59:18 +0900587 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Nikita Ioffef934e812024-07-05 15:44:41 +0000588 // Fail fast with a meaningful error message in case device doesn't support pVMs.
589 check_protected_vm_is_supported()?;
Alan Stokes185fe112023-01-10 16:20:55 +0000590 }
591
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000592 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900593 write_zero_filler(&zero_filler_path)
594 .context("Failed to make composite image")
595 .with_log()
596 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000597
598 // Assemble disk images if needed.
599 let disks = config
600 .disks
601 .iter()
602 .map(|disk| {
603 assemble_disk_image(
604 disk,
605 &zero_filler_path,
606 &temporary_directory,
607 &mut next_temporary_image_id,
608 &mut indirect_files,
609 )
610 })
611 .collect::<Result<Vec<DiskFile>, _>>()?;
612
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000613 let (cpus, host_cpu_topology) = match config.cpuTopology {
614 CpuTopology::MATCH_HOST => (None, true),
615 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
616 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900617 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
618 .with_log()
619 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000620 }
621 };
622
David Brazdil2dfefd12023-11-17 14:07:36 +0000623 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900624 let mut set = HashSet::new();
625 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900626 let path = canonicalize(device)
627 .with_context(|| format!("can't canonicalize {device}"))
628 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900629 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900630 return Err(anyhow!("duplicated device {device}"))
631 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900632 }
633 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000634 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000635 let dtbo_file = File::from(
636 GLOBAL_SERVICE
637 .getDtboFile()?
638 .as_ref()
639 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900640 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000641 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
642 );
643 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900644 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000645 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900646 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900647 let display_config = if cfg!(paravirtualized_devices) {
648 config
649 .displayConfig
650 .as_ref()
651 .map(DisplayConfig::new)
652 .transpose()
653 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
654 } else {
655 None
656 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700657 let gpu_config = if cfg!(paravirtualized_devices) {
658 config
659 .gpuConfig
660 .as_ref()
661 .map(GpuConfig::new)
662 .transpose()
663 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
664 } else {
665 None
666 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900667
Jeongik Chac181be72024-03-27 00:18:30 +0900668 let input_device_options = if cfg!(paravirtualized_devices) {
669 config
670 .inputDevices
671 .iter()
672 .map(to_input_device_option_from)
673 .collect::<Result<Vec<InputDeviceOption>, _>>()
674 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
675 } else {
676 vec![]
677 };
678
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900679 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900680 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900681 if *is_protected {
682 return Err(anyhow!("Network feature is not supported for pVM yet"))
683 .with_log()
684 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
685 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900686 Some(File::from(
687 GLOBAL_SERVICE
688 .createTapInterface(&get_this_pid().to_string())?
689 .as_ref()
690 .try_clone()
691 .context("Failed to get TAP interface from ParcelFileDescriptor")
692 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
693 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900694 } else {
695 None
696 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800697
698 let audio_config = if cfg!(paravirtualized_devices) {
699 config.audioConfig.as_ref().map(AudioConfig::new)
700 } else {
701 None
702 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900703
Elie Kheirallah29d72912024-08-07 20:17:26 +0000704 let usb_config = config
705 .usbConfig
706 .as_ref()
707 .map(UsbConfig::new)
708 .unwrap_or(Ok(UsbConfig { controller: false }))
709 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
710
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000711 // Actually start the VM.
712 let crosvm_config = CrosvmConfig {
713 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000714 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000715 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000716 kernel,
717 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000718 disks,
719 params: config.params.to_owned(),
720 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900721 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700722 memory_mib: config
723 .memoryMib
724 .try_into()
725 .ok()
726 .and_then(NonZeroU32::new)
727 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000728 cpus,
729 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900730 console_out_fd,
731 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000732 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900733 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000734 indirect_files,
735 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900736 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000737 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900738 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000739 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000740 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900741 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900742 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000743 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900744 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800745 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000746 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700747 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800748 audio_config,
Jeongik Cha75057452024-09-03 11:26:04 +0900749 no_balloon: config.noBalloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000750 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000751 dump_dt_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000752 };
753 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100754 VmInstance::new(
755 crosvm_config,
756 temporary_directory,
757 requester_uid,
758 requester_debug_pid,
759 vm_context,
760 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900761 .with_context(|| format!("Failed to create VM with config {:?}", config))
762 .with_log()
763 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000764 );
765 state.add_vm(Arc::downgrade(&instance));
766 Ok(VirtualMachine::create(instance))
767 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900768}
769
Alan Stokesfda70842023-12-20 17:50:14 +0000770/// Returns whether a VM config represents a "custom" virtual machine, which requires the
771/// USE_CUSTOM_VIRTUAL_MACHINE.
772fn is_custom_config(config: &VirtualMachineConfig) -> bool {
773 match config {
774 // Any raw (non-Microdroid) VM is considered custom.
775 VirtualMachineConfig::RawConfig(_) => true,
776 VirtualMachineConfig::AppConfig(config) => {
777 // Some features are reserved for platform apps only, even when using
778 // VirtualMachineAppConfig. Almost all of these features are grouped in the
779 // CustomConfig struct:
780 // - controlling CPUs;
781 // - gdbPort is set, meaning that crosvm will start a gdb server;
782 // - using anything other than the default kernel;
783 // - specifying devices to be assigned.
784 if config.customConfig.is_some() {
785 true
786 } else {
787 // Additional custom features not included in CustomConfig:
788 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000789 // - specifying extra APKs;
790 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900791 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000792 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900793 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
794 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000795 }
796 }
797 }
798}
799
Seungjae Yoo14e60182024-02-21 13:28:31 +0900800fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
801 let VirtualMachineConfig::AppConfig(config) = config else {
802 return Ok(None);
803 };
804 let Some(custom_config) = &config.customConfig else {
805 return Ok(None);
806 };
807 let Some(file) = custom_config.vendorImage.as_ref() else {
808 return Ok(None);
809 };
810
811 let file = clone_file(file)?;
812 let size =
813 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
814 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
815 .context("Failed to get vbmeta from microdroid-vendor.img")?;
816
817 for descriptor in vbmeta.descriptors()?.iter() {
818 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
819 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
820 return Ok(Some(root_digest.as_bytes().to_vec()));
821 }
822 }
823 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
824}
825
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000826fn maybe_create_device_tree_overlay(
827 config: &VirtualMachineConfig,
828 temporary_directory: &Path,
829) -> binder::Result<Option<File>> {
830 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
831 // (e.g. instance-id)
832 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
833 let host_ref_dt = if host_ref_dt.exists()
834 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
835 {
836 Some(host_ref_dt)
837 } else {
838 warn!("VM reference DT doesn't exist in host DT");
839 None
840 };
841
842 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
843 .context("Failed to extract vendor hashtree digest")
844 .or_service_specific_exception(-1)?;
845
846 let trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
847 info!(
848 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
849 match the trusted digest in the pvmfw config, causing the VM to fail to start."
850 );
851 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
852 } else {
853 vec![]
854 };
855
856 let instance_id;
857 let mut untrusted_props = Vec::with_capacity(2);
858 if cfg!(llpvm_changes) {
859 instance_id = extract_instance_id(config);
860 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
861 let want_updatable = extract_want_updatable(config);
862 if want_updatable && is_secretkeeper_supported() {
863 // Let guest know that it can defer rollback protection to Secretkeeper by setting
864 // an empty property in untrusted node in DT. This enables Updatable VMs.
865 untrusted_props.push((cstr!("defer-rollback-protection"), &[]))
866 }
867 }
868
869 let device_tree_overlay = if host_ref_dt.is_some()
870 || !untrusted_props.is_empty()
871 || !trusted_props.is_empty()
872 {
873 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
874 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
875 let fdt =
876 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
877 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
878 .or_service_specific_exception(-1)?;
879 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
880 Some(File::open(dt_output).or_service_specific_exception(-1)?)
881 } else {
882 None
883 };
884 Ok(device_tree_overlay)
885}
886
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000887fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900888 let file = OpenOptions::new()
889 .create_new(true)
890 .read(true)
891 .write(true)
892 .open(zero_filler_path)
893 .with_context(|| "Failed to create zero.img")?;
894 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000895 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900896}
897
David Brazdilf50c7a62023-04-19 14:22:42 +0000898fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
899 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
900 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
901 part.flush()
902}
903
904fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
905 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
906 part.flush()
907}
908
909fn round_up(input: u64, granularity: u64) -> u64 {
910 if granularity == 0 {
911 return input;
912 }
913 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
914 let result = input.checked_add(granularity - 1).unwrap_or(input);
915 (result / granularity) * granularity
916}
917
Jeongik Chac181be72024-03-27 00:18:30 +0900918fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
919 Ok(match input_device {
920 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
921 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
922 height: u32::try_from(single_touch.height)?,
923 width: u32::try_from(single_touch.width)?,
924 name: if !single_touch.name.is_empty() {
925 Some(single_touch.name.clone())
926 } else {
927 None
928 },
929 },
930 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
931 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
932 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +0900933 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
934 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
935 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +0900936 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
937 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
938 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +0900939 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
940 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
941 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +0900942 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
943 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
944 height: u32::try_from(trackpad.height)?,
945 width: u32::try_from(trackpad.width)?,
946 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
947 },
Jeongik Cha10494912024-07-16 11:19:50 +0900948 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
949 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
950 height: u32::try_from(multi_touch.height)?,
951 width: u32::try_from(multi_touch.width)?,
952 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
953 },
Jeongik Chac181be72024-03-27 00:18:30 +0900954 })
955}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000956/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
957///
958/// This may involve assembling a composite disk from a set of partition images.
959fn assemble_disk_image(
960 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900961 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000962 temporary_directory: &Path,
963 next_temporary_image_id: &mut u64,
964 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000965) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000966 let image = if !disk.partitions.is_empty() {
967 if disk.image.is_some() {
968 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900969 return Err(anyhow!("DiskImage contains both image and partitions"))
970 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000971 }
972
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000973 let composite_image_filenames =
974 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
975 let (image, partition_files) = make_composite_image(
976 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900977 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000978 &composite_image_filenames.composite,
979 &composite_image_filenames.header,
980 &composite_image_filenames.footer,
981 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900982 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
983 .with_log()
984 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000985
986 // Pass the file descriptors for the various partition files to crosvm when it
987 // is run.
988 indirect_files.extend(partition_files);
989
990 image
991 } else if let Some(image) = &disk.image {
992 clone_file(image)?
993 } else {
994 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900995 return Err(anyhow!("DiskImage didn't contain image or partitions."))
996 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000997 };
998
999 Ok(DiskFile { image, writable: disk.writable })
1000}
1001
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001002fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1003 if let Some(ref mut params) = vm_config.params {
1004 params.push(' ');
1005 params.push_str(param)
1006 } else {
1007 vm_config.params = Some(param.to_owned())
1008 }
1009}
1010
Inseob Kim46257382024-01-03 15:41:22 +09001011fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1012 if config.extension()?.to_str()? != "json" {
1013 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001014 }
Inseob Kim46257382024-01-03 15:41:22 +09001015
1016 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1017}
1018
1019fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1020 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1021 let os_names =
1022 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1023
1024 Ok(os_names)
1025}
1026
1027fn get_supported_os_names() -> Result<HashSet<String>> {
1028 if !cfg!(vendor_modules) {
1029 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1030 }
1031
1032 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1033}
1034
1035fn is_valid_os(os_name: &str) -> bool {
1036 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001037}
1038
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001039fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1040 if !cfg!(vendor_modules) {
1041 return false;
1042 }
1043 match config {
1044 VirtualMachineConfig::RawConfig(_) => false,
1045 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1046 }
1047}
1048
Jooyung Han21e9b922021-06-26 04:14:16 +09001049fn load_app_config(
1050 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001051 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001052 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001053) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001054 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1055 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001056 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001057
Shikha Panwar22e70452022-10-10 18:32:55 +00001058 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1059 Some(clone_file(file)?)
1060 } else {
1061 None
1062 };
1063
Alan Stokesfda70842023-12-20 17:50:14 +00001064 let vm_payload_config;
1065 let extra_apk_files: Vec<_>;
1066 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001067 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001068 vm_payload_config =
1069 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1070 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1071 extra_apk_files = vm_payload_config
1072 .extra_apks
1073 .iter()
1074 .enumerate()
1075 .map(|(i, apk)| {
1076 File::open(PathBuf::from(&apk.path))
1077 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1078 })
1079 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001080 }
Alan Stokesfda70842023-12-20 17:50:14 +00001081 Payload::PayloadConfig(payload_config) => {
1082 vm_payload_config = create_vm_payload_config(payload_config)?;
1083 extra_apk_files =
1084 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1085 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001086 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001087
Inseob Kim89b24592024-02-23 18:59:43 +09001088 let payload_config_os = vm_payload_config.os.name.as_str();
1089 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1090 bail!("'os' in payload config is deprecated");
1091 }
1092
Inseob Kim172f9eb2023-11-06 17:02:08 +09001093 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001094 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001095 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001096 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001097 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001098
1099 // It is safe to construct a filename based on the os_name because we've already checked that it
1100 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001101 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1102 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001103 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001104
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001105 if let Some(custom_config) = &config.customConfig {
1106 if let Some(file) = custom_config.customKernelImage.as_ref() {
1107 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1108 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001109 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001110
1111 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001112 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001113 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001114 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001115
Chris Wailes6177c662024-05-09 14:37:44 -07001116 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001117 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001118
1119 for param in custom_config.extraKernelCmdlineParams.iter() {
1120 append_kernel_param(param, &mut vm_config);
1121 }
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001122 }
1123
Andrew Walbrancc045902021-07-27 16:06:17 +00001124 if config.memoryMib > 0 {
1125 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001126 }
1127
Chris Wailes6177c662024-05-09 14:37:44 -07001128 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001129 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001130 vm_config.cpuTopology = config.cpuTopology;
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001131 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001132 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001133
Shikha Panwar22e70452022-10-10 18:32:55 +00001134 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001135 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001136
1137 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1138 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001139 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001140 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001141 temporary_directory,
1142 apk_file,
1143 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001144 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001145 &vm_payload_config,
1146 &mut vm_config,
1147 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001148
Andrew Walbrancc0db522021-07-12 17:03:42 +00001149 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001150}
1151
Inseob Kimff48a7c2024-02-26 22:07:21 +09001152fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1153 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1154 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1155
1156 // microdroid vendor image is OK
1157 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1158 {
1159 return Ok(());
1160 }
1161
1162 if link.starts_with("/vendor") || link.starts_with("/odm") {
1163 bail!("vendor or odm file {} can't be used for VM", link.display());
1164 }
1165
1166 Ok(())
1167}
1168
1169fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1170 config
1171 .disks
1172 .iter()
1173 .flat_map(|disk| disk.partitions.iter())
1174 .filter_map(|partition| partition.image.as_ref())
1175 .try_for_each(check_partition_for_file)?;
1176
1177 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1178 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1179 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1180
1181 Ok(())
1182}
1183
Alan Stokes0d1ef782022-09-27 13:46:35 +01001184fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1185 let mut apk_zip = ZipArchive::new(apk_file)?;
1186 let config_file = apk_zip.by_name(config_path)?;
1187 Ok(serde_json::from_reader(config_file)?)
1188}
1189
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001190fn create_vm_payload_config(
1191 payload_config: &VirtualMachinePayloadConfig,
1192) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001193 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1194 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1195 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001196
1197 let payload_binary_name = &payload_config.payloadBinaryName;
1198 if payload_binary_name.contains('/') {
1199 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1200 }
1201
1202 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001203
1204 // The VM only cares about how many there are, these names are actually ignored.
1205 let extra_apk_count = payload_config.extraApks.len();
1206 let extra_apks =
1207 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1208
Inseob Kim89b24592024-02-23 18:59:43 +09001209 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001210}
1211
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001212/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001213fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001214 temporary_directory: &Path,
1215 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001216) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001217 let id = *next_temporary_image_id;
1218 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001219 CompositeImageFilenames {
1220 composite: temporary_directory.join(format!("composite-{}.img", id)),
1221 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1222 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1223 }
1224}
1225
1226/// Filenames for a composite disk image, including header and footer partitions.
1227#[derive(Clone, Debug, Eq, PartialEq)]
1228struct CompositeImageFilenames {
1229 /// The composite disk image itself.
1230 composite: PathBuf,
1231 /// The header partition image.
1232 header: PathBuf,
1233 /// The footer partition image.
1234 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001235}
1236
Jiyong Park753553b2021-07-12 21:21:09 +09001237/// Checks whether the caller has a specific permission
1238fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001239 if cfg!(early) {
1240 // Skip permission check for early VMs, in favor of SELinux
1241 return Ok(());
1242 }
David Brazdil1f530702022-10-03 12:18:10 +01001243 let calling_pid = get_calling_pid();
1244 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001245 // Root can do anything
1246 if calling_uid == 0 {
1247 return Ok(());
1248 }
1249 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001250 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001251 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001252 Ok(())
1253 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001254 Err(anyhow!("does not have the {} permission", perm))
1255 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001256 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001257}
1258
Jiyong Park753553b2021-07-12 21:21:09 +09001259/// Check whether the caller of the current Binder method is allowed to manage VMs
1260fn check_manage_access() -> binder::Result<()> {
1261 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1262}
1263
Inseob Kim1119d702022-05-02 18:01:58 +09001264/// Check whether the caller of the current Binder method is allowed to create custom VMs
1265fn check_use_custom_virtual_machine() -> binder::Result<()> {
1266 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1267}
1268
Alan Stokes185fe112023-01-10 16:20:55 +00001269/// Return whether a partition is exempt from selinux label checks, because we know that it does
1270/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001271fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001272 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001273 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001274 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001275 || label == "microdroid-apk-idsig"
1276 || label == "payload-metadata"
1277 || label.starts_with("extra-idsig-")
1278}
1279
Alice Wangc206b9b2023-08-28 14:13:51 +00001280/// Returns whether a partition with the given label is safe for a raw config VM.
1281fn is_safe_raw_partition(label: &str) -> bool {
1282 label == "vm-instance"
1283}
1284
Alan Stokes185fe112023-01-10 16:20:55 +00001285/// Check that a file SELinux label is acceptable.
1286///
1287/// 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 +09001288/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001289///
1290/// Note that sepolicy must also grant read access for these types to both virtualization
1291/// service and crosvm.
1292///
1293/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1294/// user devices (W^X).
1295fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1296 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001297 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001298 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001299 | "staging_data_file" // updated/staged APEX images
1300 | "system_file" // immutable dm-verity protected partition
1301 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001302 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001303 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001304 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001305 }
1306}
1307
Alan Stokes185fe112023-01-10 16:20:55 +00001308fn check_label_for_partition(partition: &Partition) -> Result<()> {
1309 let file = partition.image.as_ref().unwrap().as_ref();
1310 check_label_is_allowed(&getfilecon(file)?)
1311 .with_context(|| format!("Partition {} invalid", &partition.label))
1312}
1313
1314fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1315 if let Some(f) = kernel {
1316 check_label_for_file(f, "kernel")?;
1317 }
1318 if let Some(f) = initrd {
1319 check_label_for_file(f, "initrd")?;
1320 }
1321 Ok(())
1322}
1323fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1324 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1325}
1326
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001327/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1328#[derive(Debug)]
1329struct VirtualMachine {
1330 instance: Arc<VmInstance>,
1331}
1332
1333impl VirtualMachine {
1334 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001335 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001336 }
1337}
1338
1339impl Interface for VirtualMachine {}
1340
1341impl IVirtualMachine for VirtualMachine {
1342 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001343 // Don't check permission. The owner of the VM might have passed this binder object to
1344 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001345 Ok(self.instance.cid as i32)
1346 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001347
Andrew Walbran6b650662021-09-07 13:13:23 +00001348 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001349 // Don't check permission. The owner of the VM might have passed this binder object to
1350 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001351 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001352 }
1353
1354 fn registerCallback(
1355 &self,
1356 callback: &Strong<dyn IVirtualMachineCallback>,
1357 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001358 // Don't check permission. The owner of the VM might have passed this binder object to
1359 // others.
1360 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001361 // TODO: Should this give an error if the VM is already dead?
1362 self.instance.callbacks.add(callback.clone());
1363 Ok(())
1364 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001365
Andrew Walbranf8d94112021-09-07 11:45:36 +00001366 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001367 self.instance
1368 .start()
1369 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1370 .with_log()
1371 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001372 }
1373
Inseob Kima446f802022-07-11 19:46:37 +09001374 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001375 self.instance
1376 .kill()
1377 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1378 .with_log()
1379 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001380 }
1381
Keir Fraser48221ba2024-07-12 14:05:02 +00001382 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1383 let balloon = self
1384 .instance
1385 .get_memory_balloon()
1386 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1387 .with_log()
1388 .or_service_specific_exception(-1)?;
1389 Ok(balloon.try_into().unwrap())
1390 }
1391
1392 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001393 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001394 .set_memory_balloon(num_bytes.try_into().unwrap())
1395 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001396 .with_log()
1397 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001398 }
1399
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001400 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001401 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001402 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001403 }
Alan Stokes10c47672022-12-13 17:17:08 +00001404 let port = port as u32;
1405 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001406 return Err(anyhow!("Can't connect to privileged port {port}"))
1407 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +00001408 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001409 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1410 .context("Failed to connect")
1411 .or_service_specific_exception(-1)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001412 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001413 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001414
1415 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1416 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1417 }
Jiyong Park23b67392024-07-04 13:51:42 +09001418
1419 fn suspend(&self) -> binder::Result<()> {
1420 self.instance
1421 .suspend()
1422 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1423 .with_log()
1424 .or_service_specific_exception(-1)
1425 }
1426
1427 fn resume(&self) -> binder::Result<()> {
1428 self.instance
1429 .resume()
1430 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1431 .with_log()
1432 .or_service_specific_exception(-1)
1433 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001434}
1435
1436impl Drop for VirtualMachine {
1437 fn drop(&mut self) {
1438 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001439 if let Err(e) = self.instance.kill() {
1440 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1441 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001442 }
1443}
1444
1445/// A set of Binders to be called back in response to various events on the VM, such as when it
1446/// dies.
1447#[derive(Debug, Default)]
1448pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1449
1450impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001451 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001452 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001453 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001454 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001455 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001456 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001457 }
1458 }
1459 }
1460
Inseob Kim14cb8692021-08-31 21:50:39 +09001461 /// Call all registered callbacks to notify that the payload is ready to serve.
1462 pub fn notify_payload_ready(&self, cid: Cid) {
1463 let callbacks = &*self.0.lock().unwrap();
1464 for callback in callbacks {
1465 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001466 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001467 }
1468 }
1469 }
1470
Inseob Kim2444af92021-08-31 01:22:50 +09001471 /// Call all registered callbacks to notify that the payload has finished.
1472 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1473 let callbacks = &*self.0.lock().unwrap();
1474 for callback in callbacks {
1475 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001476 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001477 }
1478 }
1479 }
1480
Jooyung Handd0a1732021-11-23 15:26:20 +09001481 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001482 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001483 let callbacks = &*self.0.lock().unwrap();
1484 for callback in callbacks {
1485 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001486 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001487 }
1488 }
1489 }
1490
Andrew Walbrandae07162021-03-12 17:05:20 +00001491 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001492 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001493 let callbacks = &*self.0.lock().unwrap();
1494 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001495 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001496 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001497 }
1498 }
1499 }
1500
1501 /// Add a new callback to the set.
1502 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1503 self.0.lock().unwrap().push(callback);
1504 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001505}
1506
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001507/// The mutable state of the VirtualizationService. There should only be one instance of this
1508/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001509#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001510struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001511 /// The VMs which have been started. When VMs are started a weak reference is added to this
1512 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1513 /// the Binder client are dropped the weak reference here will become invalid, and will be
1514 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001515 vms: Vec<Weak<VmInstance>>,
1516}
1517
1518impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001519 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001520 fn vms(&self) -> Vec<Arc<VmInstance>> {
1521 // Attempt to upgrade the weak pointers to strong pointers.
1522 self.vms.iter().filter_map(Weak::upgrade).collect()
1523 }
1524
1525 /// Add a new VM to the list.
1526 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1527 // Garbage collect any entries from the stored list which no longer exist.
1528 self.vms.retain(|vm| vm.strong_count() > 0);
1529
1530 // Actually add the new VM.
1531 self.vms.push(vm);
1532 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001533
Jiyong Park8611a6c2021-07-09 18:17:44 +09001534 /// Get a VM that corresponds to the given cid
1535 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1536 self.vms().into_iter().find(|vm| vm.cid == cid)
1537 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001538}
1539
Andrew Walbran6b650662021-09-07 13:13:23 +00001540/// Gets the `VirtualMachineState` of the given `VmInstance`.
1541fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001542 match &*instance.vm_state.lock().unwrap() {
1543 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1544 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001545 PayloadState::Starting => VirtualMachineState::STARTING,
1546 PayloadState::Started => VirtualMachineState::STARTED,
1547 PayloadState::Ready => VirtualMachineState::READY,
1548 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001549 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001550 },
1551 VmState::Dead => VirtualMachineState::DEAD,
1552 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001553 }
1554}
1555
David Brazdilf50c7a62023-04-19 14:22:42 +00001556/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001557pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1558 file.as_ref()
1559 .try_clone()
1560 .context("Failed to clone File from ParcelFileDescriptor")
1561 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001562 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001563}
1564
Andrew Walbrand3a84182021-09-07 14:48:52 +00001565/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001566fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001567 file.as_ref().map(clone_file).transpose()
1568}
1569
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001570/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001571fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1572 // SAFETY: ownership is transferred from stream to f
1573 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1574 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001575}
1576
Jiyong Parkdcf17412022-02-08 15:07:23 +09001577/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001578fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1579 VersionReq::parse(s)
1580 .with_context(|| format!("Invalid platform version requirement {}", s))
1581 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001582}
1583
Jiyong Parked180932023-02-24 19:55:41 +09001584/// Create the empty ramdump file
1585fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1586 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1587 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1588 // owner) for readout.
1589 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001590 let ramdump = File::create(ramdump_path)
1591 .context("Failed to prepare ramdump file")
1592 .with_log()
1593 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001594 Ok(ramdump)
1595}
1596
Nikita Ioffe5776f082023-02-10 21:38:26 +00001597fn is_protected(config: &VirtualMachineConfig) -> bool {
1598 match config {
1599 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1600 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1601 }
1602}
1603
1604fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1605 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001606 return Err(anyhow!("Can't use gdb with protected VMs"))
1607 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001608 }
1609
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001610 if get_debug_level(config) == Some(DebugLevel::NONE) {
1611 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1612 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001613 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001614
1615 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001616}
1617
Shikha Panwar61a74b52024-02-16 13:17:01 +00001618fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1619 match config {
1620 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1621 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1622 }
1623}
1624
Alan Stokesc96b35e2024-05-03 13:21:20 +01001625fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1626 match config {
1627 VirtualMachineConfig::RawConfig(_) => true,
1628 VirtualMachineConfig::AppConfig(config) => {
1629 let Some(custom) = &config.customConfig else { return true };
1630 custom.wantUpdatable
1631 }
1632 }
1633}
1634
Nikita Ioffe5776f082023-02-10 21:38:26 +00001635fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1636 match config {
1637 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001638 VirtualMachineConfig::AppConfig(config) => {
1639 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1640 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001641 }
1642}
1643
Nikita Ioffe631717e2023-09-05 13:38:07 +01001644fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1645 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1646 if let Some(custom_config) = &config.customConfig {
1647 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1648 return Err(anyhow!("vendor modules feature is disabled"))
1649 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1650 }
1651 }
1652 Ok(())
1653}
1654
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001655fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1656 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1657 if let Some(custom_config) = &config.customConfig {
1658 if !custom_config.devices.is_empty() {
1659 return Err(anyhow!("device assignment feature is disabled"))
1660 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1661 }
1662 }
1663 Ok(())
1664}
1665
Alan Stokesfda70842023-12-20 17:50:14 +00001666fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1667 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1668 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1669 if !payload_config.extraApks.is_empty() {
1670 return Err(anyhow!("multi-tenant feature is disabled"))
1671 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1672 }
1673 Ok(())
1674}
1675
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001676fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1677 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1678 if let Some(custom_config) = &config.customConfig {
1679 if !custom_config.extraKernelCmdlineParams.is_empty() {
1680 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1681 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1682 }
1683 }
1684 Ok(())
1685}
1686
Nikita Ioffef934e812024-07-05 15:44:41 +00001687fn check_protected_vm_is_supported() -> binder::Result<()> {
1688 let is_pvm_supported =
1689 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1690 if is_pvm_supported {
1691 Ok(())
1692 } else {
1693 Err(anyhow!("pVM is not supported"))
1694 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1695 }
1696}
1697
Nikita Ioffe631717e2023-09-05 13:38:07 +01001698fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1699 if !cfg!(vendor_modules) {
1700 check_no_vendor_modules(config)?;
1701 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001702 if !cfg!(device_assignment) {
1703 check_no_devices(config)?;
1704 }
Alan Stokesfda70842023-12-20 17:50:14 +00001705 if !cfg!(multi_tenant) {
1706 check_no_extra_apks(config)?;
1707 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001708 if !cfg!(debuggable_vms_improvements) {
1709 check_no_extra_kernel_cmdline_params(config)?;
1710 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001711 Ok(())
1712}
1713
Inseob Kimecde8c02024-09-03 13:11:08 +09001714fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1715 check_no_vendor_modules(config)?;
1716 check_no_devices(config)?;
1717
1718 Ok(())
1719}
1720
Inseob Kim0168b462022-12-27 14:54:35 +09001721fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001722 fd: Option<&ParcelFileDescriptor>,
1723 tag: String,
1724) -> Result<Option<File>, Status> {
1725 if let Some(fd) = fd {
1726 return Ok(Some(clone_file(fd)?));
1727 }
1728
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001729 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001730 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001731
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001732 let mut reader = BufReader::new(File::from(read_fd));
1733 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001734
1735 std::thread::spawn(move || loop {
1736 let mut buf = vec![];
1737 match reader.read_until(b'\n', &mut buf) {
1738 Ok(0) => {
1739 // EOF
1740 return;
1741 }
1742 Ok(size) => {
1743 if buf[size - 1] == b'\n' {
1744 buf.pop();
1745 }
1746 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1747 }
1748 Err(e) => {
1749 error!("Could not read console pipe: {:?}", e);
1750 return;
1751 }
1752 };
1753 });
1754
1755 Ok(Some(write_fd))
1756}
1757
Jooyung Han35edb8f2021-07-01 16:17:16 +09001758/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1759/// it doesn't require that T implements Clone.
1760enum BorrowedOrOwned<'a, T> {
1761 Borrowed(&'a T),
1762 Owned(T),
1763}
1764
1765impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1766 fn as_ref(&self) -> &T {
1767 match self {
1768 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001769 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001770 }
1771 }
1772}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001773
1774/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1775#[derive(Debug, Default)]
1776struct VirtualMachineService {
1777 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001778 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001779}
1780
1781impl Interface for VirtualMachineService {}
1782
1783impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001784 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1785 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001786 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001787 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001788 vm.update_payload_state(PayloadState::Started)
1789 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001790 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001791
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001792 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1793 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001794 Ok(())
1795 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001796 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001797 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001798 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001799 }
Inseob Kim2444af92021-08-31 01:22:50 +09001800
Inseob Kimc7d28c72021-10-25 14:28:10 +00001801 fn notifyPayloadReady(&self) -> binder::Result<()> {
1802 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001803 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001804 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001805 vm.update_payload_state(PayloadState::Ready)
1806 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001807 vm.callbacks.notify_payload_ready(cid);
1808 Ok(())
1809 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001810 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001811 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001812 }
1813 }
1814
Inseob Kimc7d28c72021-10-25 14:28:10 +00001815 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1816 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001817 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001818 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001819 vm.update_payload_state(PayloadState::Finished)
1820 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001821 vm.callbacks.notify_payload_finished(cid, exit_code);
1822 Ok(())
1823 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001824 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001825 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001826 }
1827 }
1828
Alan Stokes2bead0d2022-09-05 16:58:34 +01001829 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001830 let cid = self.cid;
1831 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001832 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001833 vm.update_payload_state(PayloadState::Finished)
1834 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001835 vm.callbacks.notify_error(cid, error_code, message);
1836 Ok(())
1837 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001838 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001839 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001840 }
1841 }
Alice Wangc2fec932023-02-23 16:24:02 +00001842
Shikha Panware45e9422024-02-28 21:18:10 +00001843 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
1844 if !is_secretkeeper_supported() {
1845 return Err(StatusCode::NAME_NOT_FOUND)?;
1846 }
1847 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1848 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001849 }
1850
Alice Wange64dd182024-01-17 15:57:55 +00001851 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
1852 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00001853 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001854}
1855
Shikha Panwar8707f0f2024-02-28 20:40:42 +00001856fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00001857 binder::is_declared(SECRETKEEPER_IDENTIFIER)
1858 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00001859}
1860
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001861impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001862 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001863 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001864 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001865 BinderFeatures::default(),
1866 )
1867 }
1868}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001869
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08001870struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
1871
1872impl Interface for SecretkeeperProxy {}
1873
1874impl ISecretkeeper for SecretkeeperProxy {
1875 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
1876 // Pass the request to the channel, and read the response.
1877 self.0.processSecretManagementRequest(req)
1878 }
1879
1880 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
1881 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
1882 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
1883 }
1884
1885 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
1886 self.0.deleteIds(ids)
1887 }
1888
1889 fn deleteAll(&self) -> binder::Result<()> {
1890 self.0.deleteAll()
1891 }
1892}
1893
1894struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
1895
1896impl Interface for AuthGraphKeyExchangeProxy {}
1897
1898impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
1899 fn create(&self) -> binder::Result<SessionInitiationInfo> {
1900 self.0.create()
1901 }
1902
1903 fn init(
1904 &self,
1905 peer_pub_key: &PubKey,
1906 peer_id: &Identity,
1907 peer_nonce: &[u8],
1908 peer_version: i32,
1909 ) -> binder::Result<KeInitResult> {
1910 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
1911 }
1912
1913 fn finish(
1914 &self,
1915 peer_pub_key: &PubKey,
1916 peer_id: &Identity,
1917 peer_signature: &SessionIdSignature,
1918 peer_nonce: &[u8],
1919 peer_version: i32,
1920 own_key: &Key,
1921 ) -> binder::Result<SessionInfo> {
1922 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
1923 }
1924
1925 fn authenticationComplete(
1926 &self,
1927 peer_signature: &SessionIdSignature,
1928 shared_keys: &[AuthgraphArc; 2],
1929 ) -> binder::Result<[AuthgraphArc; 2]> {
1930 self.0.authenticationComplete(peer_signature, shared_keys)
1931 }
1932}
1933
Inseob Kimecde8c02024-09-03 13:11:08 +09001934// KEEP IN SYNC WITH early_vms.xsd
1935#[derive(Debug, Deserialize, PartialEq)]
1936struct EarlyVm {
1937 #[allow(dead_code)]
1938 name: String,
1939 #[allow(dead_code)]
1940 cid: i32,
1941 #[allow(dead_code)]
1942 path: String,
1943}
1944
1945#[derive(Debug, Default, Deserialize)]
1946struct EarlyVms {
1947 #[allow(dead_code)]
1948 early_vm: Vec<EarlyVm>,
1949}
1950
1951fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
1952 match partition {
1953 "system" => Ok(100..200),
1954 "system_ext" | "product" => Ok(200..300),
1955 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
1956 }
1957}
1958
1959fn find_early_vm(xml_path: &Path, cid_range: &Range<Cid>, name: &str) -> Result<EarlyVm> {
1960 if !xml_path.exists() {
1961 bail!("{} doesn't exist", xml_path.display());
1962 }
1963
1964 let xml =
1965 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
1966 let xml = String::from_utf8(xml)
1967 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
1968 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
1969 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
1970
1971 let mut found_vm: Option<EarlyVm> = None;
1972
1973 for early_vm in early_vms.early_vm {
1974 if early_vm.name != name {
1975 continue;
1976 }
1977
1978 let cid = early_vm
1979 .cid
1980 .try_into()
1981 .with_context(|| format!("Invalid CID value {}", early_vm.cid))?;
1982
1983 if !cid_range.contains(&cid) {
1984 bail!("VM '{}' uses CID {cid} which is out of range. Available CIDs for '{}': {cid_range:?}", xml_path.display(), early_vm.name);
1985 }
1986
1987 if found_vm.is_some() {
1988 bail!("Multiple VMs named {name} are found in {}", xml_path.display());
1989 }
1990
1991 found_vm = Some(early_vm);
1992 }
1993
1994 found_vm.ok_or_else(|| anyhow!("Can't find {name} in {}", xml_path.display()))
1995}
1996
1997fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
1998 let cid_range = range_for_partition(partition)?;
1999 find_early_vm(Path::new(&format!("/{partition}/etc/avf/early_vms.xml")), &cid_range, name)
2000}
2001
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002002#[cfg(test)]
2003mod tests {
2004 use super::*;
2005
2006 #[test]
2007 fn test_is_allowed_label_for_partition() -> Result<()> {
2008 let expected_results = vec![
2009 ("u:object_r:system_file:s0", true),
2010 ("u:object_r:apk_data_file:s0", true),
2011 ("u:object_r:app_data_file:s0", false),
2012 ("u:object_r:app_data_file:s0:c512,c768", false),
2013 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2014 ("invalid", false),
2015 ("user:role:apk_data_file:severity:categories", true),
2016 ("user:role:apk_data_file:severity:categories:extraneous", false),
2017 ];
2018
2019 for (label, expected_valid) in expected_results {
2020 let context = SeContext::new(label)?;
2021 let result = check_label_is_allowed(&context);
2022 if expected_valid {
2023 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2024 } else if result.is_ok() {
2025 bail!("Expected label {} to be disallowed", label);
2026 }
2027 }
2028 Ok(())
2029 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002030
2031 #[test]
2032 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2033 let apk = tempfile::tempfile().unwrap();
2034 let idsig = tempfile::tempfile().unwrap();
2035
2036 let ret = create_or_update_idsig_file(
2037 &ParcelFileDescriptor::new(apk),
2038 &ParcelFileDescriptor::new(idsig),
2039 );
2040 assert!(ret.is_err(), "should fail");
2041 Ok(())
2042 }
2043
2044 #[test]
2045 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2046 let tmp_dir = tempfile::TempDir::new().unwrap();
2047 let apk = File::open(tmp_dir.path()).unwrap();
2048 let idsig = tempfile::tempfile().unwrap();
2049
2050 let ret = create_or_update_idsig_file(
2051 &ParcelFileDescriptor::new(apk),
2052 &ParcelFileDescriptor::new(idsig),
2053 );
2054 assert!(ret.is_err(), "should fail");
2055 Ok(())
2056 }
2057
2058 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2059 /// on ext4 filesystem is passed.
2060 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2061 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2062 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2063 #[test]
2064 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2065 // APEXes are backed by the ext4.
2066 let apk = File::open("/apex/com.android.virt/").unwrap();
2067 let idsig = tempfile::tempfile().unwrap();
2068
2069 let ret = create_or_update_idsig_file(
2070 &ParcelFileDescriptor::new(apk),
2071 &ParcelFileDescriptor::new(idsig),
2072 );
2073 assert!(ret.is_err(), "should fail");
2074 Ok(())
2075 }
Jiyong Park8d192952023-06-26 14:29:51 +09002076
2077 #[test]
2078 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2079 use std::io::Seek;
2080
2081 // Pick any APK
2082 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2083 let mut idsig = tempfile::tempfile().unwrap();
2084
2085 create_or_update_idsig_file(
2086 &ParcelFileDescriptor::new(apk.try_clone()?),
2087 &ParcelFileDescriptor::new(idsig.try_clone()?),
2088 )?;
2089 let modified_orig = idsig.metadata()?.modified()?;
2090 apk.rewind()?;
2091 idsig.rewind()?;
2092
2093 // Call the function again
2094 create_or_update_idsig_file(
2095 &ParcelFileDescriptor::new(apk.try_clone()?),
2096 &ParcelFileDescriptor::new(idsig.try_clone()?),
2097 )?;
2098 let modified_new = idsig.metadata()?.modified()?;
2099 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2100 Ok(())
2101 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002102
2103 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002104 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2105 use std::io::Read;
2106
2107 // Pick any APK
2108 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2109 let idsig_empty = tempfile::tempfile().unwrap();
2110 let mut idsig_invalid = tempfile::tempfile().unwrap();
2111 idsig_invalid.write_all(b"Oops")?;
2112
2113 // Create new idsig
2114 create_or_update_idsig_file(
2115 &ParcelFileDescriptor::new(apk.try_clone()?),
2116 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2117 )?;
2118 apk.rewind()?;
2119
2120 // Update idsig_invalid
2121 create_or_update_idsig_file(
2122 &ParcelFileDescriptor::new(apk.try_clone()?),
2123 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2124 )?;
2125
2126 // Ensure the 2 idsig files have same size!
2127 assert!(
2128 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2129 "idsig files differ in size"
2130 );
2131 // Ensure the 2 idsig files have same content!
2132 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2133 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2134 }
2135 Ok(())
2136 }
2137 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002138 fn test_append_kernel_param_first_param() {
2139 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2140 append_kernel_param("foo=1", &mut vm_config);
2141 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2142 }
2143
2144 #[test]
2145 fn test_append_kernel_param() {
2146 let mut vm_config =
2147 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2148 append_kernel_param("bar=42", &mut vm_config);
2149 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2150 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002151
Inseob Kim46257382024-01-03 15:41:22 +09002152 fn test_extract_os_name_from_config_path(
2153 path: &Path,
2154 expected_result: Option<&str>,
2155 ) -> Result<()> {
2156 let result = extract_os_name_from_config_path(path);
2157 if result.as_deref() != expected_result {
2158 bail!("Expected {:?} but was {:?}", expected_result, &result)
2159 }
2160 Ok(())
2161 }
2162
2163 #[test]
2164 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2165 test_extract_os_name_from_config_path(
2166 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2167 Some("microdroid"),
2168 )
2169 }
2170
2171 #[test]
2172 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2173 test_extract_os_name_from_config_path(
2174 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2175 Some("microdroid_gki-android14-6.1"),
2176 )
2177 }
2178
2179 #[test]
2180 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2181 test_extract_os_name_from_config_path(
2182 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2183 None,
2184 )
2185 }
2186
2187 #[test]
2188 fn test_extract_os_name_from_configs() -> Result<()> {
2189 let tmp_dir = tempfile::TempDir::new()?;
2190 let tmp_dir_path = tmp_dir.path().to_owned();
2191
2192 let mut os_names: HashSet<String> = HashSet::new();
2193 os_names.insert("microdroid".to_owned());
2194 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2195 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2196
2197 // config files
2198 for os_name in &os_names {
2199 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2200 }
2201
2202 // fake files not related to configs
2203 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2204 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2205
2206 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2207 Some(s) => s.to_owned(),
2208 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2209 };
2210
2211 let result = extract_os_names_from_configs(&glob_pattern)?;
2212 if result != os_names {
2213 bail!("Expected {:?} but was {:?}", os_names, result);
2214 }
2215 Ok(())
2216 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002217
2218 #[test]
2219 fn test_find_early_vms_from_xml() -> Result<()> {
2220 let tmp_dir = tempfile::TempDir::new()?;
2221 let tmp_dir_path = tmp_dir.path().to_owned();
2222 let xml_path = tmp_dir_path.join("early_vms.xml");
2223
2224 std::fs::write(
2225 &xml_path,
2226 br#"<?xml version="1.0" encoding="utf-8"?>
2227 <early_vms>
2228 <early_vm>
2229 <name>vm_demo_native_early</name>
2230 <cid>123</cid>
2231 <path>/system/bin/vm_demo_native_early</path>
2232 </early_vm>
2233 <early_vm>
2234 <name>vm_demo_duplicated_name</name>
2235 <cid>456</cid>
2236 <path>/system/bin/vm_demo_duplicated_name_1</path>
2237 </early_vm>
2238 <early_vm>
2239 <name>vm_demo_duplicated_name</name>
2240 <cid>789</cid>
2241 <path>/system/bin/vm_demo_duplicated_name_2</path>
2242 </early_vm>
2243 <early_vm>
2244 <name>vm_demo_invalid_cid_1</name>
2245 <cid>-1</cid>
2246 <path>/system/bin/vm_demo_invalid_cid_1</path>
2247 </early_vm>
2248 <early_vm>
2249 <name>vm_demo_invalid_cid_2</name>
2250 <cid>999999</cid>
2251 <path>/system/bin/vm_demo_invalid_cid_2</path>
2252 </early_vm>
2253 </early_vms>
2254 "#,
2255 )?;
2256
2257 let cid_range = 100..1000;
2258
2259 let result = find_early_vm(&xml_path, &cid_range, "vm_demo_native_early")?;
2260 let expected = EarlyVm {
2261 name: "vm_demo_native_early".to_owned(),
2262 cid: 123,
2263 path: "/system/bin/vm_demo_native_early".to_owned(),
2264 };
2265 assert_eq!(result, expected);
2266
2267 assert!(
2268 find_early_vm(&xml_path, &cid_range, "vm_demo_duplicated_name").is_err(),
2269 "should fail"
2270 );
2271 assert!(
2272 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_1").is_err(),
2273 "should fail"
2274 );
2275 assert!(
2276 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_2").is_err(),
2277 "should fail"
2278 );
2279
2280 Ok(())
2281 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002282}