blob: 23652d294ed5428ed75f349cd1dc9545adb353d5 [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,
Devin Moore407df8f2024-08-27 19:39:16 +000036 IVirtualMachine::{self, BnVirtualMachine},
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::{
Devin Moore407df8f2024-08-27 19:39:16 +000065 self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
66 SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000067};
Shikha Panwar55e10ec2024-02-13 12:53:49 +000068use cstr::cstr;
Inseob Kim46257382024-01-03 15:41:22 +090069use glob::glob;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000070use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090071use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090072use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000073use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000074use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090075use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090076use serde::Deserialize;
Inseob Kim6ef80972023-07-20 17:23:36 +090077use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000078use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000079use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090080use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090081use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000082use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090083use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000084use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090085use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090086use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000087use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000088use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010089use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090090use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010091use vmconfig::{VmConfig, get_debug_level};
Devin Moore407df8f2024-08-27 19:39:16 +000092use vsock::{VsockAddr, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090093use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000094
David Brazdil41d1a872022-10-05 14:44:19 +010095/// The unique ID of a VM used (together with a port number) for vsock communication.
96pub type Cid = u32;
97
David Brazdil4b4c5102022-12-19 22:56:20 +000098pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
99
Devin Moore407df8f2024-08-27 19:39:16 +0000100/// Vsock privileged ports are below this number.
101const VSOCK_PRIV_PORT_MAX: u32 = 1024;
102
Jooyung Han95884632021-07-06 22:27:54 +0900103/// The size of zero.img.
104/// Gaps in composite disk images are filled with a shared zero.img.
105const ZERO_FILLER_SIZE: u64 = 4096;
106
David Brazdilf50c7a62023-04-19 14:22:42 +0000107/// Magic string for the instance image
108const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
109
110/// Version of the instance image format
111const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
112
Alan Stokes0d1ef782022-09-27 13:46:35 +0100113const MICRODROID_OS_NAME: &str = "microdroid";
114
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000115const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000116 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000117
David Brazdilf50c7a62023-04-19 14:22:42 +0000118const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
119
120/// crosvm requires all partitions to be a multiple of 4KiB.
121const PARTITION_GRANULARITY_BYTES: u64 = 4096;
122
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000123const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
124
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100125pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
126 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900127 if cfg!(early) {
128 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
129 } else {
130 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
131 .expect("Could not connect to VirtualizationServiceInternal")
132 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100133 });
134static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
135 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000136
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000137fn create_or_update_idsig_file(
138 input_fd: &ParcelFileDescriptor,
139 idsig_fd: &ParcelFileDescriptor,
140) -> Result<()> {
141 let mut input = clone_file(input_fd)?;
142 let metadata = input.metadata().context("failed to get input metadata")?;
143 if !metadata.is_file() {
144 bail!("input is not a regular file");
145 }
Alan Stokes25f69362023-03-06 16:51:54 +0000146 let mut sig =
147 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
148 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000149
150 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900151
152 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
153 // if the idsig file already has the same APK digest.
154 if output.metadata()?.len() > 0 {
155 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
156 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
157 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
158 return Ok(());
159 }
160 }
161 // if we fail to read v4signature from output, that's fine. User can pass a random file.
162 // We will anyway overwrite the file to the v4signature generated from input_fd.
163 }
164
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000165 output
166 .seek(SeekFrom::Start(0))
167 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000168 output.set_len(0).context("failed to set_len on the idsig output")?;
169 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000170 Ok(())
171}
172
Alan Stokes25f69362023-03-06 16:51:54 +0000173fn get_current_sdk() -> Result<u32> {
174 let current_sdk = system_properties::read("ro.build.version.sdk")?;
175 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
176 current_sdk.parse().context("Malformed SDK version")
177}
178
David Brazdil4b4c5102022-12-19 22:56:20 +0000179pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
180 for dir_entry in read_dir(path)? {
181 remove_file(dir_entry?.path())?;
182 }
183 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100184}
185
David Brazdil528e0472022-10-10 15:06:02 +0100186/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000187#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000188pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900189 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000190}
191
Shikha Panward8e35422021-10-11 13:51:27 +0000192impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000193 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000194 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
195 let state = &mut *self.state.lock().unwrap();
196 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000197 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000198 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000199 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
200 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000201 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000202 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000203 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000204 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
205 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000206 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000207 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000208 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000209 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000210 .or(Err(StatusCode::UNKNOWN_ERROR))?;
211 }
212 Ok(())
213 }
214}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000215impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000216 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
217 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000218 ///
219 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000220 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000221 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000222 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900223 console_out_fd: Option<&ParcelFileDescriptor>,
224 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000225 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000226 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000227 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000228 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900229 let ret = self.create_vm_internal(
230 config,
231 console_out_fd,
232 console_in_fd,
233 log_fd,
234 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000235 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900236 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000237 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000238 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000239 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000240
Shikha Panwar61a74b52024-02-16 13:17:01 +0000241 /// Allocate a new instance_id to the VM
242 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000243 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000244 GLOBAL_SERVICE.allocateInstanceId()
245 }
246
Andrew Walbrandff3b942021-06-09 15:20:36 +0000247 /// Initialise an empty partition image of the given size to be used as a writable partition.
248 fn initializeWritablePartition(
249 &self,
250 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000251 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900252 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000253 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900254 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900255 let size_bytes = size_bytes
256 .try_into()
257 .with_context(|| format!("Invalid size: {}", size_bytes))
258 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000259 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000260 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000261 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000262 image
263 .seek(SeekFrom::Start(0))
264 .context("failed to move cursor to start")
265 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900266 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700267 // Set the file length. In most filesystems, this will not allocate any physical disk
268 // space, it will only change the logical size.
269 image
270 .set_len(size_bytes)
271 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900272 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000273
274 match partition_type {
275 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700276 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
277 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000278 _ => Err(Error::new(
279 ErrorKind::Unsupported,
280 format!("Unsupported partition type {:?}", partition_type),
281 )),
282 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900283 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
284 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000285
286 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000287 }
288
Jiyong Park0a248432021-08-20 23:32:39 +0900289 /// Creates or update the idsig file by digesting the input APK file.
290 fn createOrUpdateIdsigFile(
291 &self,
292 input_fd: &ParcelFileDescriptor,
293 idsig_fd: &ParcelFileDescriptor,
294 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900295 check_manage_access()?;
296
Jiyong Park2227eaa2023-08-04 11:59:18 +0900297 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900298 Ok(())
299 }
300
Andrew Walbran320b5602021-03-04 16:11:12 +0000301 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
302 /// and as such is only permitted from the shell user.
303 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000304 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000305 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000306 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900307
308 /// Get a list of assignable device types.
309 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
310 // Delegate to the global service, including checking the permission.
311 GLOBAL_SERVICE.getAssignableDevices()
312 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100313
Inseob Kim46257382024-01-03 15:41:22 +0900314 /// Get a list of supported OSes.
315 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
316 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
317 }
318
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100319 /// Returns whether given feature is enabled
320 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
321 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000322 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100323 }
Alice Wange64dd182024-01-17 15:57:55 +0000324
325 fn enableTestAttestation(&self) -> binder::Result<()> {
326 GLOBAL_SERVICE.enableTestAttestation()
327 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000328
329 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
330 check_manage_access()?;
331 GLOBAL_SERVICE.isRemoteAttestationSupported()
332 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000333
334 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
335 // The response is specific to Microdroid. Updatable VMs are only possible if device
336 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
337 // this, however other guest OSes may do things differently.
338 check_manage_access()?;
339 Ok(is_secretkeeper_supported())
340 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000341
Shikha Panwar07d701c2024-03-28 14:43:52 +0000342 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
343 check_manage_access()?;
344 GLOBAL_SERVICE.removeVmInstance(instance_id)
345 }
346
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000347 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
348 check_manage_access()?;
349 GLOBAL_SERVICE.claimVmInstance(instance_id)
350 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000351}
352
Inseob Kimecde8c02024-09-03 13:11:08 +0900353/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
354#[derive(Debug, Default)]
355struct EarlyVmContext {
356 /// The unique CID assigned to the VM for vsock communication.
357 cid: Cid,
358 /// Temporary directory for this VM instance.
359 temp_dir: PathBuf,
360}
361
362impl EarlyVmContext {
363 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
364 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
365 // should trust clients, e.g. they won't run two VMs at the same time
366 let _ = remove_dir_all(&temp_dir);
367 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
368
369 Ok(Self { cid, temp_dir })
370 }
371}
372
373impl Interface for EarlyVmContext {}
374
375impl Drop for EarlyVmContext {
376 fn drop(&mut self) {
377 if let Err(e) = remove_dir_all(&self.temp_dir) {
378 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
379 }
380 }
381}
382
383impl IGlobalVmContext for EarlyVmContext {
384 fn getCid(&self) -> binder::Result<i32> {
385 Ok(self.cid as i32)
386 }
387
388 fn getTemporaryDirectory(&self) -> binder::Result<String> {
389 Ok(self.temp_dir.to_string_lossy().to_string())
390 }
391
392 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
393 Err(Status::new_exception_str(
394 ExceptionCode::UNSUPPORTED_OPERATION,
395 Some("Early VM doesn't support setting host console name"),
396 ))
397 }
398}
399
400fn find_partition(path: &Path) -> binder::Result<String> {
401 match path.components().nth(1) {
402 Some(std::path::Component::Normal(partition)) => {
403 Ok(partition.to_string_lossy().into_owned())
404 }
405 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
406 .or_service_specific_exception(-1),
407 }
408}
409
Jiyong Park8611a6c2021-07-09 18:17:44 +0900410impl VirtualizationService {
411 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000412 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900413 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000414
Inseob Kimecde8c02024-09-03 13:11:08 +0900415 fn create_early_vm_context(
416 &self,
417 config: &VirtualMachineConfig,
418 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
419 let calling_exe_path = format!("/proc/{}/exe", get_calling_pid());
420 let link = fs::read_link(&calling_exe_path)
421 .context(format!("can't read_link '{calling_exe_path}'"))
422 .or_service_specific_exception(-1)?;
423 let partition = find_partition(&link)?;
424
425 let name = match config {
426 VirtualMachineConfig::RawConfig(config) => &config.name,
427 VirtualMachineConfig::AppConfig(config) => &config.name,
428 };
429 let early_vm =
430 find_early_vm_for_partition(&partition, name).or_service_specific_exception(-1)?;
431 if Path::new(&early_vm.path) != link {
432 return Err(anyhow!(
433 "VM '{name}' in partition '{partition}' must be created with '{}', not '{}'",
434 &early_vm.path,
435 link.display()
436 ))
437 .or_service_specific_exception(-1);
438 }
439
440 let cid = early_vm.cid as Cid;
441 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
442
443 let context = EarlyVmContext::new(cid, temp_dir.clone())
444 .context(format!("Can't create early vm contexts for {cid}"))
445 .or_service_specific_exception(-1)?;
446 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
447
448 // Start VM service listening for connections from the new CID on port=CID.
449 let port = cid;
450 let vm_server = RpcServer::new_vsock(service, cid, port)
451 .context(format!("Could not start RpcServer on port {port}"))
452 .or_service_specific_exception(-1)?;
453 vm_server.start();
454 Ok((VmContext::new(Strong::new(Box::new(context)), vm_server), cid, temp_dir))
455 }
456
David Brazdil209074a2023-01-12 16:44:51 +0000457 fn create_vm_context(
458 &self,
459 requester_debug_pid: pid_t,
460 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000461 const NUM_ATTEMPTS: usize = 5;
462
463 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000464 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000465 let cid = vm_context.getCid()? as Cid;
466 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000467 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
468
469 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000470 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000471 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000472 Ok(vm_server) => {
473 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000474 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000475 }
476 Err(err) => {
477 warn!("Could not start RpcServer on port {}: {}", port, err);
478 }
479 }
480 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900481 Err(anyhow!("Too many attempts to create VM context failed"))
482 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000483 }
484
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000485 fn create_vm_internal(
486 &self,
487 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900488 console_out_fd: Option<&ParcelFileDescriptor>,
489 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000490 log_fd: Option<&ParcelFileDescriptor>,
491 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000492 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000493 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000494 let requester_uid = get_calling_uid();
495 let requester_debug_pid = get_calling_pid();
496
Nikita Ioffe631717e2023-09-05 13:38:07 +0100497 check_config_features(config)?;
498
Inseob Kimecde8c02024-09-03 13:11:08 +0900499 if cfg!(early) {
500 check_config_allowed_for_early_vms(config)?;
501 }
502
David Brazdil209074a2023-01-12 16:44:51 +0000503 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900504 let (vm_context, cid, temporary_directory) = if cfg!(early) {
505 self.create_early_vm_context(config)?
506 } else {
507 self.create_vm_context(requester_debug_pid)?
508 };
Inseob Kim1119d702022-05-02 18:01:58 +0900509
Alan Stokesfda70842023-12-20 17:50:14 +0000510 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100511 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900512 }
513
Nikita Ioffe5776f082023-02-10 21:38:26 +0000514 let gdb_port = extract_gdb_port(config);
515
516 // Additional permission checks if caller request gdb.
517 if gdb_port.is_some() {
518 check_gdb_allowed(config)?;
519 }
520
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000521 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900522
Jaewan Kimf3143242024-03-15 06:56:31 +0000523 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000524 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900525 Some(prepare_ramdump_file(&temporary_directory)?)
526 } else {
527 None
528 };
529
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000530 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900531 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100532 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900533 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100534 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000535 let dump_dt_fd = dump_dt_fd.map(clone_file).transpose()?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000536
537 // Counter to generate unique IDs for temporary image files.
538 let mut next_temporary_image_id = 0;
539 // Files which are referred to from composite images. These must be mapped to the crosvm
540 // child process, and not closed before it is started.
541 let mut indirect_files = vec![];
542
Alan Stokes7bc146c2022-10-20 17:10:32 +0100543 let (is_app_config, config) = match config {
544 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
545 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900546 let config = load_app_config(config, &debug_config, &temporary_directory)
547 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900548 *is_protected = config.protectedVm;
549 let message = format!("Failed to load app config: {:?}", e);
550 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900551 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900552 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100553 (true, BorrowedOrOwned::Owned(config))
554 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000555 };
556 let config = config.as_ref();
557 *is_protected = config.protectedVm;
558
559 // Check if partition images are labeled incorrectly. This is to prevent random images
560 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100561 // being loaded in a pVM. This applies to everything but the instance image in the raw
562 // config, and everything but the non-executable, generated partitions in the app
563 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000564 config
565 .disks
566 .iter()
567 .flat_map(|disk| disk.partitions.iter())
568 .filter(|partition| {
569 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100570 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000571 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000572 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000573 }
574 })
575 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900576 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000577
Inseob Kimff48a7c2024-02-26 22:07:21 +0900578 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
579 // have unstable interfaces.
580 // TODO(b/316431494): remove once Treble interfaces are stabilized.
581 check_partitions_for_files(config).or_service_specific_exception(-1)?;
582
Alan Stokes185fe112023-01-10 16:20:55 +0000583 let kernel = maybe_clone_file(&config.kernel)?;
584 let initrd = maybe_clone_file(&config.initrd)?;
585
Alan Stokes185fe112023-01-10 16:20:55 +0000586 if config.protectedVm {
Nikita Ioffef934e812024-07-05 15:44:41 +0000587 // In a protected VM, we require custom kernels to come from a trusted source
588 // (b/237054515).
Jiyong Park2227eaa2023-08-04 11:59:18 +0900589 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Nikita Ioffef934e812024-07-05 15:44:41 +0000590 // Fail fast with a meaningful error message in case device doesn't support pVMs.
591 check_protected_vm_is_supported()?;
Alan Stokes185fe112023-01-10 16:20:55 +0000592 }
593
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000594 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900595 write_zero_filler(&zero_filler_path)
596 .context("Failed to make composite image")
597 .with_log()
598 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000599
600 // Assemble disk images if needed.
601 let disks = config
602 .disks
603 .iter()
604 .map(|disk| {
605 assemble_disk_image(
606 disk,
607 &zero_filler_path,
608 &temporary_directory,
609 &mut next_temporary_image_id,
610 &mut indirect_files,
611 )
612 })
613 .collect::<Result<Vec<DiskFile>, _>>()?;
614
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000615 let (cpus, host_cpu_topology) = match config.cpuTopology {
616 CpuTopology::MATCH_HOST => (None, true),
617 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
618 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900619 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
620 .with_log()
621 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000622 }
623 };
624
David Brazdil2dfefd12023-11-17 14:07:36 +0000625 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900626 let mut set = HashSet::new();
627 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900628 let path = canonicalize(device)
629 .with_context(|| format!("can't canonicalize {device}"))
630 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900631 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900632 return Err(anyhow!("duplicated device {device}"))
633 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900634 }
635 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000636 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000637 let dtbo_file = File::from(
638 GLOBAL_SERVICE
639 .getDtboFile()?
640 .as_ref()
641 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900642 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000643 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
644 );
645 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900646 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000647 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900648 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900649 let display_config = if cfg!(paravirtualized_devices) {
650 config
651 .displayConfig
652 .as_ref()
653 .map(DisplayConfig::new)
654 .transpose()
655 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
656 } else {
657 None
658 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700659 let gpu_config = if cfg!(paravirtualized_devices) {
660 config
661 .gpuConfig
662 .as_ref()
663 .map(GpuConfig::new)
664 .transpose()
665 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
666 } else {
667 None
668 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900669
Jeongik Chac181be72024-03-27 00:18:30 +0900670 let input_device_options = if cfg!(paravirtualized_devices) {
671 config
672 .inputDevices
673 .iter()
674 .map(to_input_device_option_from)
675 .collect::<Result<Vec<InputDeviceOption>, _>>()
676 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
677 } else {
678 vec![]
679 };
680
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900681 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900682 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900683 if *is_protected {
684 return Err(anyhow!("Network feature is not supported for pVM yet"))
685 .with_log()
686 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
687 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900688 Some(File::from(
689 GLOBAL_SERVICE
690 .createTapInterface(&get_this_pid().to_string())?
691 .as_ref()
692 .try_clone()
693 .context("Failed to get TAP interface from ParcelFileDescriptor")
694 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
695 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900696 } else {
697 None
698 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800699
700 let audio_config = if cfg!(paravirtualized_devices) {
701 config.audioConfig.as_ref().map(AudioConfig::new)
702 } else {
703 None
704 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900705
Elie Kheirallah29d72912024-08-07 20:17:26 +0000706 let usb_config = config
707 .usbConfig
708 .as_ref()
709 .map(UsbConfig::new)
710 .unwrap_or(Ok(UsbConfig { controller: false }))
711 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
712
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000713 // Actually start the VM.
714 let crosvm_config = CrosvmConfig {
715 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000716 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000717 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000718 kernel,
719 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000720 disks,
721 params: config.params.to_owned(),
722 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900723 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700724 memory_mib: config
725 .memoryMib
726 .try_into()
727 .ok()
728 .and_then(NonZeroU32::new)
729 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000730 cpus,
731 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900732 console_out_fd,
733 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000734 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900735 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000736 indirect_files,
737 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900738 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000739 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900740 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000741 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000742 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900743 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900744 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000745 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900746 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800747 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000748 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700749 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800750 audio_config,
Jeongik Cha75057452024-09-03 11:26:04 +0900751 no_balloon: config.noBalloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000752 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000753 dump_dt_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000754 };
755 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100756 VmInstance::new(
757 crosvm_config,
758 temporary_directory,
759 requester_uid,
760 requester_debug_pid,
761 vm_context,
762 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900763 .with_context(|| format!("Failed to create VM with config {:?}", config))
764 .with_log()
765 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000766 );
767 state.add_vm(Arc::downgrade(&instance));
768 Ok(VirtualMachine::create(instance))
769 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900770}
771
Alan Stokesfda70842023-12-20 17:50:14 +0000772/// Returns whether a VM config represents a "custom" virtual machine, which requires the
773/// USE_CUSTOM_VIRTUAL_MACHINE.
774fn is_custom_config(config: &VirtualMachineConfig) -> bool {
775 match config {
776 // Any raw (non-Microdroid) VM is considered custom.
777 VirtualMachineConfig::RawConfig(_) => true,
778 VirtualMachineConfig::AppConfig(config) => {
779 // Some features are reserved for platform apps only, even when using
780 // VirtualMachineAppConfig. Almost all of these features are grouped in the
781 // CustomConfig struct:
782 // - controlling CPUs;
783 // - gdbPort is set, meaning that crosvm will start a gdb server;
784 // - using anything other than the default kernel;
785 // - specifying devices to be assigned.
786 if config.customConfig.is_some() {
787 true
788 } else {
789 // Additional custom features not included in CustomConfig:
790 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000791 // - specifying extra APKs;
792 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900793 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000794 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900795 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
796 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000797 }
798 }
799 }
800}
801
Seungjae Yoo14e60182024-02-21 13:28:31 +0900802fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
803 let VirtualMachineConfig::AppConfig(config) = config else {
804 return Ok(None);
805 };
806 let Some(custom_config) = &config.customConfig else {
807 return Ok(None);
808 };
809 let Some(file) = custom_config.vendorImage.as_ref() else {
810 return Ok(None);
811 };
812
813 let file = clone_file(file)?;
814 let size =
815 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
816 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
817 .context("Failed to get vbmeta from microdroid-vendor.img")?;
818
819 for descriptor in vbmeta.descriptors()?.iter() {
820 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
821 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
822 return Ok(Some(root_digest.as_bytes().to_vec()));
823 }
824 }
825 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
826}
827
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000828fn maybe_create_device_tree_overlay(
829 config: &VirtualMachineConfig,
830 temporary_directory: &Path,
831) -> binder::Result<Option<File>> {
832 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
833 // (e.g. instance-id)
834 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
835 let host_ref_dt = if host_ref_dt.exists()
836 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
837 {
838 Some(host_ref_dt)
839 } else {
840 warn!("VM reference DT doesn't exist in host DT");
841 None
842 };
843
844 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
845 .context("Failed to extract vendor hashtree digest")
846 .or_service_specific_exception(-1)?;
847
848 let trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
849 info!(
850 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
851 match the trusted digest in the pvmfw config, causing the VM to fail to start."
852 );
853 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
854 } else {
855 vec![]
856 };
857
858 let instance_id;
859 let mut untrusted_props = Vec::with_capacity(2);
860 if cfg!(llpvm_changes) {
861 instance_id = extract_instance_id(config);
862 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
863 let want_updatable = extract_want_updatable(config);
864 if want_updatable && is_secretkeeper_supported() {
865 // Let guest know that it can defer rollback protection to Secretkeeper by setting
866 // an empty property in untrusted node in DT. This enables Updatable VMs.
867 untrusted_props.push((cstr!("defer-rollback-protection"), &[]))
868 }
869 }
870
871 let device_tree_overlay = if host_ref_dt.is_some()
872 || !untrusted_props.is_empty()
873 || !trusted_props.is_empty()
874 {
875 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
876 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
877 let fdt =
878 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
879 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
880 .or_service_specific_exception(-1)?;
881 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
882 Some(File::open(dt_output).or_service_specific_exception(-1)?)
883 } else {
884 None
885 };
886 Ok(device_tree_overlay)
887}
888
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000889fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900890 let file = OpenOptions::new()
891 .create_new(true)
892 .read(true)
893 .write(true)
894 .open(zero_filler_path)
895 .with_context(|| "Failed to create zero.img")?;
896 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000897 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900898}
899
David Brazdilf50c7a62023-04-19 14:22:42 +0000900fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
901 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
902 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
903 part.flush()
904}
905
906fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
907 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
908 part.flush()
909}
910
911fn round_up(input: u64, granularity: u64) -> u64 {
912 if granularity == 0 {
913 return input;
914 }
915 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
916 let result = input.checked_add(granularity - 1).unwrap_or(input);
917 (result / granularity) * granularity
918}
919
Jeongik Chac181be72024-03-27 00:18:30 +0900920fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
921 Ok(match input_device {
922 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
923 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
924 height: u32::try_from(single_touch.height)?,
925 width: u32::try_from(single_touch.width)?,
926 name: if !single_touch.name.is_empty() {
927 Some(single_touch.name.clone())
928 } else {
929 None
930 },
931 },
932 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
933 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
934 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +0900935 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
936 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
937 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +0900938 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
939 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
940 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +0900941 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
942 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
943 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +0900944 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
945 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
946 height: u32::try_from(trackpad.height)?,
947 width: u32::try_from(trackpad.width)?,
948 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
949 },
Jeongik Cha10494912024-07-16 11:19:50 +0900950 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
951 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
952 height: u32::try_from(multi_touch.height)?,
953 width: u32::try_from(multi_touch.width)?,
954 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
955 },
Jeongik Chac181be72024-03-27 00:18:30 +0900956 })
957}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000958/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
959///
960/// This may involve assembling a composite disk from a set of partition images.
961fn assemble_disk_image(
962 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900963 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000964 temporary_directory: &Path,
965 next_temporary_image_id: &mut u64,
966 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000967) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000968 let image = if !disk.partitions.is_empty() {
969 if disk.image.is_some() {
970 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900971 return Err(anyhow!("DiskImage contains both image and partitions"))
972 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000973 }
974
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000975 let composite_image_filenames =
976 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
977 let (image, partition_files) = make_composite_image(
978 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900979 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000980 &composite_image_filenames.composite,
981 &composite_image_filenames.header,
982 &composite_image_filenames.footer,
983 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900984 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
985 .with_log()
986 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000987
988 // Pass the file descriptors for the various partition files to crosvm when it
989 // is run.
990 indirect_files.extend(partition_files);
991
992 image
993 } else if let Some(image) = &disk.image {
994 clone_file(image)?
995 } else {
996 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900997 return Err(anyhow!("DiskImage didn't contain image or partitions."))
998 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000999 };
1000
1001 Ok(DiskFile { image, writable: disk.writable })
1002}
1003
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001004fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1005 if let Some(ref mut params) = vm_config.params {
1006 params.push(' ');
1007 params.push_str(param)
1008 } else {
1009 vm_config.params = Some(param.to_owned())
1010 }
1011}
1012
Inseob Kim46257382024-01-03 15:41:22 +09001013fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1014 if config.extension()?.to_str()? != "json" {
1015 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001016 }
Inseob Kim46257382024-01-03 15:41:22 +09001017
1018 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1019}
1020
1021fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1022 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1023 let os_names =
1024 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1025
1026 Ok(os_names)
1027}
1028
1029fn get_supported_os_names() -> Result<HashSet<String>> {
1030 if !cfg!(vendor_modules) {
1031 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1032 }
1033
1034 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1035}
1036
1037fn is_valid_os(os_name: &str) -> bool {
1038 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001039}
1040
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001041fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1042 if !cfg!(vendor_modules) {
1043 return false;
1044 }
1045 match config {
1046 VirtualMachineConfig::RawConfig(_) => false,
1047 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1048 }
1049}
1050
Jooyung Han21e9b922021-06-26 04:14:16 +09001051fn load_app_config(
1052 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001053 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001054 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001055) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001056 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1057 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001058 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001059
Shikha Panwar22e70452022-10-10 18:32:55 +00001060 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1061 Some(clone_file(file)?)
1062 } else {
1063 None
1064 };
1065
Alan Stokesfda70842023-12-20 17:50:14 +00001066 let vm_payload_config;
1067 let extra_apk_files: Vec<_>;
1068 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001069 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001070 vm_payload_config =
1071 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1072 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1073 extra_apk_files = vm_payload_config
1074 .extra_apks
1075 .iter()
1076 .enumerate()
1077 .map(|(i, apk)| {
1078 File::open(PathBuf::from(&apk.path))
1079 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1080 })
1081 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001082 }
Alan Stokesfda70842023-12-20 17:50:14 +00001083 Payload::PayloadConfig(payload_config) => {
1084 vm_payload_config = create_vm_payload_config(payload_config)?;
1085 extra_apk_files =
1086 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1087 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001088 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001089
Inseob Kim89b24592024-02-23 18:59:43 +09001090 let payload_config_os = vm_payload_config.os.name.as_str();
1091 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1092 bail!("'os' in payload config is deprecated");
1093 }
1094
Inseob Kim172f9eb2023-11-06 17:02:08 +09001095 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001096 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001097 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001098 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001099 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001100
1101 // It is safe to construct a filename based on the os_name because we've already checked that it
1102 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001103 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1104 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001105 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001106
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001107 if let Some(custom_config) = &config.customConfig {
1108 if let Some(file) = custom_config.customKernelImage.as_ref() {
1109 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1110 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001111 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001112
1113 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001114 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001115 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001116 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001117
Chris Wailes6177c662024-05-09 14:37:44 -07001118 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001119 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001120
1121 for param in custom_config.extraKernelCmdlineParams.iter() {
1122 append_kernel_param(param, &mut vm_config);
1123 }
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001124 }
1125
Andrew Walbrancc045902021-07-27 16:06:17 +00001126 if config.memoryMib > 0 {
1127 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001128 }
1129
Chris Wailes6177c662024-05-09 14:37:44 -07001130 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001131 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001132 vm_config.cpuTopology = config.cpuTopology;
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001133 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001134 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001135
Shikha Panwar22e70452022-10-10 18:32:55 +00001136 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001137 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001138
1139 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1140 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001141 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001142 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001143 temporary_directory,
1144 apk_file,
1145 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001146 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001147 &vm_payload_config,
1148 &mut vm_config,
1149 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001150
Andrew Walbrancc0db522021-07-12 17:03:42 +00001151 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001152}
1153
Inseob Kimff48a7c2024-02-26 22:07:21 +09001154fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1155 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1156 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1157
1158 // microdroid vendor image is OK
1159 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1160 {
1161 return Ok(());
1162 }
1163
1164 if link.starts_with("/vendor") || link.starts_with("/odm") {
1165 bail!("vendor or odm file {} can't be used for VM", link.display());
1166 }
1167
1168 Ok(())
1169}
1170
1171fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1172 config
1173 .disks
1174 .iter()
1175 .flat_map(|disk| disk.partitions.iter())
1176 .filter_map(|partition| partition.image.as_ref())
1177 .try_for_each(check_partition_for_file)?;
1178
1179 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1180 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1181 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1182
1183 Ok(())
1184}
1185
Alan Stokes0d1ef782022-09-27 13:46:35 +01001186fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1187 let mut apk_zip = ZipArchive::new(apk_file)?;
1188 let config_file = apk_zip.by_name(config_path)?;
1189 Ok(serde_json::from_reader(config_file)?)
1190}
1191
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001192fn create_vm_payload_config(
1193 payload_config: &VirtualMachinePayloadConfig,
1194) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001195 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1196 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1197 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001198
1199 let payload_binary_name = &payload_config.payloadBinaryName;
1200 if payload_binary_name.contains('/') {
1201 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1202 }
1203
1204 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001205
1206 // The VM only cares about how many there are, these names are actually ignored.
1207 let extra_apk_count = payload_config.extraApks.len();
1208 let extra_apks =
1209 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1210
Inseob Kim89b24592024-02-23 18:59:43 +09001211 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001212}
1213
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001214/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001215fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001216 temporary_directory: &Path,
1217 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001218) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001219 let id = *next_temporary_image_id;
1220 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001221 CompositeImageFilenames {
1222 composite: temporary_directory.join(format!("composite-{}.img", id)),
1223 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1224 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1225 }
1226}
1227
1228/// Filenames for a composite disk image, including header and footer partitions.
1229#[derive(Clone, Debug, Eq, PartialEq)]
1230struct CompositeImageFilenames {
1231 /// The composite disk image itself.
1232 composite: PathBuf,
1233 /// The header partition image.
1234 header: PathBuf,
1235 /// The footer partition image.
1236 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001237}
1238
Jiyong Park753553b2021-07-12 21:21:09 +09001239/// Checks whether the caller has a specific permission
1240fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001241 if cfg!(early) {
1242 // Skip permission check for early VMs, in favor of SELinux
1243 return Ok(());
1244 }
David Brazdil1f530702022-10-03 12:18:10 +01001245 let calling_pid = get_calling_pid();
1246 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001247 // Root can do anything
1248 if calling_uid == 0 {
1249 return Ok(());
1250 }
1251 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001252 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001253 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001254 Ok(())
1255 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001256 Err(anyhow!("does not have the {} permission", perm))
1257 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001258 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001259}
1260
Jiyong Park753553b2021-07-12 21:21:09 +09001261/// Check whether the caller of the current Binder method is allowed to manage VMs
1262fn check_manage_access() -> binder::Result<()> {
1263 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1264}
1265
Inseob Kim1119d702022-05-02 18:01:58 +09001266/// Check whether the caller of the current Binder method is allowed to create custom VMs
1267fn check_use_custom_virtual_machine() -> binder::Result<()> {
1268 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1269}
1270
Alan Stokes185fe112023-01-10 16:20:55 +00001271/// Return whether a partition is exempt from selinux label checks, because we know that it does
1272/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001273fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001274 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001275 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001276 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001277 || label == "microdroid-apk-idsig"
1278 || label == "payload-metadata"
1279 || label.starts_with("extra-idsig-")
1280}
1281
Alice Wangc206b9b2023-08-28 14:13:51 +00001282/// Returns whether a partition with the given label is safe for a raw config VM.
1283fn is_safe_raw_partition(label: &str) -> bool {
1284 label == "vm-instance"
1285}
1286
Alan Stokes185fe112023-01-10 16:20:55 +00001287/// Check that a file SELinux label is acceptable.
1288///
1289/// 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 +09001290/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001291///
1292/// Note that sepolicy must also grant read access for these types to both virtualization
1293/// service and crosvm.
1294///
1295/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1296/// user devices (W^X).
1297fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1298 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001299 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001300 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001301 | "staging_data_file" // updated/staged APEX images
1302 | "system_file" // immutable dm-verity protected partition
1303 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001304 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001305 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001306 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001307 }
1308}
1309
Alan Stokes185fe112023-01-10 16:20:55 +00001310fn check_label_for_partition(partition: &Partition) -> Result<()> {
1311 let file = partition.image.as_ref().unwrap().as_ref();
1312 check_label_is_allowed(&getfilecon(file)?)
1313 .with_context(|| format!("Partition {} invalid", &partition.label))
1314}
1315
1316fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1317 if let Some(f) = kernel {
1318 check_label_for_file(f, "kernel")?;
1319 }
1320 if let Some(f) = initrd {
1321 check_label_for_file(f, "initrd")?;
1322 }
1323 Ok(())
1324}
1325fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1326 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1327}
1328
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001329/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1330#[derive(Debug)]
1331struct VirtualMachine {
1332 instance: Arc<VmInstance>,
1333}
1334
1335impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001336 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001337 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001338 }
1339}
1340
1341impl Interface for VirtualMachine {}
1342
Devin Moore407df8f2024-08-27 19:39:16 +00001343impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001344 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001345 // Don't check permission. The owner of the VM might have passed this binder object to
1346 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001347 Ok(self.instance.cid as i32)
1348 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001349
Andrew Walbran6b650662021-09-07 13:13:23 +00001350 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001351 // Don't check permission. The owner of the VM might have passed this binder object to
1352 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001353 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001354 }
1355
1356 fn registerCallback(
1357 &self,
1358 callback: &Strong<dyn IVirtualMachineCallback>,
1359 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001360 // Don't check permission. The owner of the VM might have passed this binder object to
1361 // others.
1362 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001363 // TODO: Should this give an error if the VM is already dead?
1364 self.instance.callbacks.add(callback.clone());
1365 Ok(())
1366 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001367
Andrew Walbranf8d94112021-09-07 11:45:36 +00001368 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001369 self.instance
1370 .start()
1371 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1372 .with_log()
1373 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001374 }
1375
Inseob Kima446f802022-07-11 19:46:37 +09001376 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001377 self.instance
1378 .kill()
1379 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1380 .with_log()
1381 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001382 }
1383
Keir Fraser48221ba2024-07-12 14:05:02 +00001384 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1385 let balloon = self
1386 .instance
1387 .get_memory_balloon()
1388 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1389 .with_log()
1390 .or_service_specific_exception(-1)?;
1391 Ok(balloon.try_into().unwrap())
1392 }
1393
1394 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001395 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001396 .set_memory_balloon(num_bytes.try_into().unwrap())
1397 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001398 .with_log()
1399 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001400 }
1401
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001402 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001403 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001404 return Err(Status::new_service_specific_error_str(
1405 IVirtualMachine::ERROR_UNEXPECTED,
1406 Some("Virtual Machine is not running"),
1407 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001408 }
Alan Stokes10c47672022-12-13 17:17:08 +00001409 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001410 if port < VSOCK_PRIV_PORT_MAX {
1411 return Err(Status::new_service_specific_error_str(
1412 IVirtualMachine::ERROR_UNEXPECTED,
1413 Some("Can't connect to privileged port {port}"),
1414 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001415 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001416 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1417 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001418 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001419 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001420 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001421
Devin Moore407df8f2024-08-27 19:39:16 +00001422 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1423 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1424 return Err(Status::new_service_specific_error_str(
1425 IVirtualMachine::ERROR_UNEXPECTED,
1426 Some("Virtual Machine is not running"),
1427 ));
1428 }
1429 let port = port as u32;
1430 if port < VSOCK_PRIV_PORT_MAX {
1431 return Err(Status::new_service_specific_error_str(
1432 IVirtualMachine::ERROR_UNEXPECTED,
1433 Some("Can't connect to privileged port {port}"),
1434 ));
1435 }
1436 let cid = self.instance.cid;
1437 let get_connection_info =
1438 move |_instance: &str| Some(ConnectionInfo::Vsock(VsockAddr::new(cid, port)));
1439 let accessor = Accessor::new(name, get_connection_info);
1440 accessor
1441 .as_binder()
1442 .context("The newly created Accessor should always have a binder")
1443 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1444 }
1445
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001446 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1447 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1448 }
Jiyong Park23b67392024-07-04 13:51:42 +09001449
1450 fn suspend(&self) -> binder::Result<()> {
1451 self.instance
1452 .suspend()
1453 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1454 .with_log()
1455 .or_service_specific_exception(-1)
1456 }
1457
1458 fn resume(&self) -> binder::Result<()> {
1459 self.instance
1460 .resume()
1461 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1462 .with_log()
1463 .or_service_specific_exception(-1)
1464 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001465}
1466
1467impl Drop for VirtualMachine {
1468 fn drop(&mut self) {
1469 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001470 if let Err(e) = self.instance.kill() {
1471 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1472 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001473 }
1474}
1475
1476/// A set of Binders to be called back in response to various events on the VM, such as when it
1477/// dies.
1478#[derive(Debug, Default)]
1479pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1480
1481impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001482 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001483 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001484 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001485 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001486 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001487 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001488 }
1489 }
1490 }
1491
Inseob Kim14cb8692021-08-31 21:50:39 +09001492 /// Call all registered callbacks to notify that the payload is ready to serve.
1493 pub fn notify_payload_ready(&self, cid: Cid) {
1494 let callbacks = &*self.0.lock().unwrap();
1495 for callback in callbacks {
1496 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001497 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001498 }
1499 }
1500 }
1501
Inseob Kim2444af92021-08-31 01:22:50 +09001502 /// Call all registered callbacks to notify that the payload has finished.
1503 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1504 let callbacks = &*self.0.lock().unwrap();
1505 for callback in callbacks {
1506 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001507 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001508 }
1509 }
1510 }
1511
Jooyung Handd0a1732021-11-23 15:26:20 +09001512 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001513 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001514 let callbacks = &*self.0.lock().unwrap();
1515 for callback in callbacks {
1516 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001517 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001518 }
1519 }
1520 }
1521
Andrew Walbrandae07162021-03-12 17:05:20 +00001522 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001523 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001524 let callbacks = &*self.0.lock().unwrap();
1525 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001526 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001527 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001528 }
1529 }
1530 }
1531
1532 /// Add a new callback to the set.
1533 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1534 self.0.lock().unwrap().push(callback);
1535 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001536}
1537
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001538/// The mutable state of the VirtualizationService. There should only be one instance of this
1539/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001540#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001541struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001542 /// The VMs which have been started. When VMs are started a weak reference is added to this
1543 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1544 /// the Binder client are dropped the weak reference here will become invalid, and will be
1545 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001546 vms: Vec<Weak<VmInstance>>,
1547}
1548
1549impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001550 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001551 fn vms(&self) -> Vec<Arc<VmInstance>> {
1552 // Attempt to upgrade the weak pointers to strong pointers.
1553 self.vms.iter().filter_map(Weak::upgrade).collect()
1554 }
1555
1556 /// Add a new VM to the list.
1557 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1558 // Garbage collect any entries from the stored list which no longer exist.
1559 self.vms.retain(|vm| vm.strong_count() > 0);
1560
1561 // Actually add the new VM.
1562 self.vms.push(vm);
1563 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001564
Jiyong Park8611a6c2021-07-09 18:17:44 +09001565 /// Get a VM that corresponds to the given cid
1566 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1567 self.vms().into_iter().find(|vm| vm.cid == cid)
1568 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001569}
1570
Andrew Walbran6b650662021-09-07 13:13:23 +00001571/// Gets the `VirtualMachineState` of the given `VmInstance`.
1572fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001573 match &*instance.vm_state.lock().unwrap() {
1574 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1575 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001576 PayloadState::Starting => VirtualMachineState::STARTING,
1577 PayloadState::Started => VirtualMachineState::STARTED,
1578 PayloadState::Ready => VirtualMachineState::READY,
1579 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001580 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001581 },
1582 VmState::Dead => VirtualMachineState::DEAD,
1583 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001584 }
1585}
1586
David Brazdilf50c7a62023-04-19 14:22:42 +00001587/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001588pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1589 file.as_ref()
1590 .try_clone()
1591 .context("Failed to clone File from ParcelFileDescriptor")
1592 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001593 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001594}
1595
Andrew Walbrand3a84182021-09-07 14:48:52 +00001596/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001597fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001598 file.as_ref().map(clone_file).transpose()
1599}
1600
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001601/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001602fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1603 // SAFETY: ownership is transferred from stream to f
1604 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1605 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001606}
1607
Jiyong Parkdcf17412022-02-08 15:07:23 +09001608/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001609fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1610 VersionReq::parse(s)
1611 .with_context(|| format!("Invalid platform version requirement {}", s))
1612 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001613}
1614
Jiyong Parked180932023-02-24 19:55:41 +09001615/// Create the empty ramdump file
1616fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1617 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1618 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1619 // owner) for readout.
1620 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001621 let ramdump = File::create(ramdump_path)
1622 .context("Failed to prepare ramdump file")
1623 .with_log()
1624 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001625 Ok(ramdump)
1626}
1627
Nikita Ioffe5776f082023-02-10 21:38:26 +00001628fn is_protected(config: &VirtualMachineConfig) -> bool {
1629 match config {
1630 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1631 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1632 }
1633}
1634
1635fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1636 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001637 return Err(anyhow!("Can't use gdb with protected VMs"))
1638 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001639 }
1640
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001641 if get_debug_level(config) == Some(DebugLevel::NONE) {
1642 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1643 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001644 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001645
1646 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001647}
1648
Shikha Panwar61a74b52024-02-16 13:17:01 +00001649fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1650 match config {
1651 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1652 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1653 }
1654}
1655
Alan Stokesc96b35e2024-05-03 13:21:20 +01001656fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1657 match config {
1658 VirtualMachineConfig::RawConfig(_) => true,
1659 VirtualMachineConfig::AppConfig(config) => {
1660 let Some(custom) = &config.customConfig else { return true };
1661 custom.wantUpdatable
1662 }
1663 }
1664}
1665
Nikita Ioffe5776f082023-02-10 21:38:26 +00001666fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1667 match config {
1668 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001669 VirtualMachineConfig::AppConfig(config) => {
1670 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1671 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001672 }
1673}
1674
Nikita Ioffe631717e2023-09-05 13:38:07 +01001675fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1676 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1677 if let Some(custom_config) = &config.customConfig {
1678 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1679 return Err(anyhow!("vendor modules feature is disabled"))
1680 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1681 }
1682 }
1683 Ok(())
1684}
1685
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001686fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1687 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1688 if let Some(custom_config) = &config.customConfig {
1689 if !custom_config.devices.is_empty() {
1690 return Err(anyhow!("device assignment feature is disabled"))
1691 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1692 }
1693 }
1694 Ok(())
1695}
1696
Alan Stokesfda70842023-12-20 17:50:14 +00001697fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1698 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1699 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1700 if !payload_config.extraApks.is_empty() {
1701 return Err(anyhow!("multi-tenant feature is disabled"))
1702 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1703 }
1704 Ok(())
1705}
1706
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001707fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1708 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1709 if let Some(custom_config) = &config.customConfig {
1710 if !custom_config.extraKernelCmdlineParams.is_empty() {
1711 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1712 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1713 }
1714 }
1715 Ok(())
1716}
1717
Nikita Ioffef934e812024-07-05 15:44:41 +00001718fn check_protected_vm_is_supported() -> binder::Result<()> {
1719 let is_pvm_supported =
1720 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1721 if is_pvm_supported {
1722 Ok(())
1723 } else {
1724 Err(anyhow!("pVM is not supported"))
1725 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1726 }
1727}
1728
Nikita Ioffe631717e2023-09-05 13:38:07 +01001729fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1730 if !cfg!(vendor_modules) {
1731 check_no_vendor_modules(config)?;
1732 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001733 if !cfg!(device_assignment) {
1734 check_no_devices(config)?;
1735 }
Alan Stokesfda70842023-12-20 17:50:14 +00001736 if !cfg!(multi_tenant) {
1737 check_no_extra_apks(config)?;
1738 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001739 if !cfg!(debuggable_vms_improvements) {
1740 check_no_extra_kernel_cmdline_params(config)?;
1741 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001742 Ok(())
1743}
1744
Inseob Kimecde8c02024-09-03 13:11:08 +09001745fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1746 check_no_vendor_modules(config)?;
1747 check_no_devices(config)?;
1748
1749 Ok(())
1750}
1751
Inseob Kim0168b462022-12-27 14:54:35 +09001752fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001753 fd: Option<&ParcelFileDescriptor>,
1754 tag: String,
1755) -> Result<Option<File>, Status> {
1756 if let Some(fd) = fd {
1757 return Ok(Some(clone_file(fd)?));
1758 }
1759
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001760 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001761 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001762
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001763 let mut reader = BufReader::new(File::from(read_fd));
1764 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001765
1766 std::thread::spawn(move || loop {
1767 let mut buf = vec![];
1768 match reader.read_until(b'\n', &mut buf) {
1769 Ok(0) => {
1770 // EOF
1771 return;
1772 }
1773 Ok(size) => {
1774 if buf[size - 1] == b'\n' {
1775 buf.pop();
1776 }
1777 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1778 }
1779 Err(e) => {
1780 error!("Could not read console pipe: {:?}", e);
1781 return;
1782 }
1783 };
1784 });
1785
1786 Ok(Some(write_fd))
1787}
1788
Jooyung Han35edb8f2021-07-01 16:17:16 +09001789/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1790/// it doesn't require that T implements Clone.
1791enum BorrowedOrOwned<'a, T> {
1792 Borrowed(&'a T),
1793 Owned(T),
1794}
1795
1796impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1797 fn as_ref(&self) -> &T {
1798 match self {
1799 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001800 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001801 }
1802 }
1803}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001804
1805/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1806#[derive(Debug, Default)]
1807struct VirtualMachineService {
1808 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001809 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001810}
1811
1812impl Interface for VirtualMachineService {}
1813
1814impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001815 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1816 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001817 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001818 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001819 vm.update_payload_state(PayloadState::Started)
1820 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001821 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001822
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001823 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1824 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001825 Ok(())
1826 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001827 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001828 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001829 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001830 }
Inseob Kim2444af92021-08-31 01:22:50 +09001831
Inseob Kimc7d28c72021-10-25 14:28:10 +00001832 fn notifyPayloadReady(&self) -> binder::Result<()> {
1833 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001834 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001835 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001836 vm.update_payload_state(PayloadState::Ready)
1837 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001838 vm.callbacks.notify_payload_ready(cid);
1839 Ok(())
1840 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001841 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001842 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001843 }
1844 }
1845
Inseob Kimc7d28c72021-10-25 14:28:10 +00001846 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1847 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001848 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001849 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001850 vm.update_payload_state(PayloadState::Finished)
1851 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001852 vm.callbacks.notify_payload_finished(cid, exit_code);
1853 Ok(())
1854 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001855 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001856 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001857 }
1858 }
1859
Alan Stokes2bead0d2022-09-05 16:58:34 +01001860 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001861 let cid = self.cid;
1862 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001863 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001864 vm.update_payload_state(PayloadState::Finished)
1865 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001866 vm.callbacks.notify_error(cid, error_code, message);
1867 Ok(())
1868 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001869 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001870 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001871 }
1872 }
Alice Wangc2fec932023-02-23 16:24:02 +00001873
Shikha Panware45e9422024-02-28 21:18:10 +00001874 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
1875 if !is_secretkeeper_supported() {
1876 return Err(StatusCode::NAME_NOT_FOUND)?;
1877 }
1878 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1879 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001880 }
1881
Alice Wange64dd182024-01-17 15:57:55 +00001882 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
1883 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00001884 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001885}
1886
Shikha Panwar8707f0f2024-02-28 20:40:42 +00001887fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00001888 binder::is_declared(SECRETKEEPER_IDENTIFIER)
1889 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00001890}
1891
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001892impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001893 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001894 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001895 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001896 BinderFeatures::default(),
1897 )
1898 }
1899}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001900
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08001901struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
1902
1903impl Interface for SecretkeeperProxy {}
1904
1905impl ISecretkeeper for SecretkeeperProxy {
1906 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
1907 // Pass the request to the channel, and read the response.
1908 self.0.processSecretManagementRequest(req)
1909 }
1910
1911 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
1912 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
1913 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
1914 }
1915
1916 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
1917 self.0.deleteIds(ids)
1918 }
1919
1920 fn deleteAll(&self) -> binder::Result<()> {
1921 self.0.deleteAll()
1922 }
1923}
1924
1925struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
1926
1927impl Interface for AuthGraphKeyExchangeProxy {}
1928
1929impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
1930 fn create(&self) -> binder::Result<SessionInitiationInfo> {
1931 self.0.create()
1932 }
1933
1934 fn init(
1935 &self,
1936 peer_pub_key: &PubKey,
1937 peer_id: &Identity,
1938 peer_nonce: &[u8],
1939 peer_version: i32,
1940 ) -> binder::Result<KeInitResult> {
1941 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
1942 }
1943
1944 fn finish(
1945 &self,
1946 peer_pub_key: &PubKey,
1947 peer_id: &Identity,
1948 peer_signature: &SessionIdSignature,
1949 peer_nonce: &[u8],
1950 peer_version: i32,
1951 own_key: &Key,
1952 ) -> binder::Result<SessionInfo> {
1953 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
1954 }
1955
1956 fn authenticationComplete(
1957 &self,
1958 peer_signature: &SessionIdSignature,
1959 shared_keys: &[AuthgraphArc; 2],
1960 ) -> binder::Result<[AuthgraphArc; 2]> {
1961 self.0.authenticationComplete(peer_signature, shared_keys)
1962 }
1963}
1964
Inseob Kimecde8c02024-09-03 13:11:08 +09001965// KEEP IN SYNC WITH early_vms.xsd
1966#[derive(Debug, Deserialize, PartialEq)]
1967struct EarlyVm {
1968 #[allow(dead_code)]
1969 name: String,
1970 #[allow(dead_code)]
1971 cid: i32,
1972 #[allow(dead_code)]
1973 path: String,
1974}
1975
1976#[derive(Debug, Default, Deserialize)]
1977struct EarlyVms {
1978 #[allow(dead_code)]
1979 early_vm: Vec<EarlyVm>,
1980}
1981
1982fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
1983 match partition {
1984 "system" => Ok(100..200),
1985 "system_ext" | "product" => Ok(200..300),
1986 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
1987 }
1988}
1989
1990fn find_early_vm(xml_path: &Path, cid_range: &Range<Cid>, name: &str) -> Result<EarlyVm> {
1991 if !xml_path.exists() {
1992 bail!("{} doesn't exist", xml_path.display());
1993 }
1994
1995 let xml =
1996 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
1997 let xml = String::from_utf8(xml)
1998 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
1999 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2000 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2001
2002 let mut found_vm: Option<EarlyVm> = None;
2003
2004 for early_vm in early_vms.early_vm {
2005 if early_vm.name != name {
2006 continue;
2007 }
2008
2009 let cid = early_vm
2010 .cid
2011 .try_into()
2012 .with_context(|| format!("Invalid CID value {}", early_vm.cid))?;
2013
2014 if !cid_range.contains(&cid) {
2015 bail!("VM '{}' uses CID {cid} which is out of range. Available CIDs for '{}': {cid_range:?}", xml_path.display(), early_vm.name);
2016 }
2017
2018 if found_vm.is_some() {
2019 bail!("Multiple VMs named {name} are found in {}", xml_path.display());
2020 }
2021
2022 found_vm = Some(early_vm);
2023 }
2024
2025 found_vm.ok_or_else(|| anyhow!("Can't find {name} in {}", xml_path.display()))
2026}
2027
2028fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
2029 let cid_range = range_for_partition(partition)?;
2030 find_early_vm(Path::new(&format!("/{partition}/etc/avf/early_vms.xml")), &cid_range, name)
2031}
2032
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002033#[cfg(test)]
2034mod tests {
2035 use super::*;
2036
2037 #[test]
2038 fn test_is_allowed_label_for_partition() -> Result<()> {
2039 let expected_results = vec![
2040 ("u:object_r:system_file:s0", true),
2041 ("u:object_r:apk_data_file:s0", true),
2042 ("u:object_r:app_data_file:s0", false),
2043 ("u:object_r:app_data_file:s0:c512,c768", false),
2044 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2045 ("invalid", false),
2046 ("user:role:apk_data_file:severity:categories", true),
2047 ("user:role:apk_data_file:severity:categories:extraneous", false),
2048 ];
2049
2050 for (label, expected_valid) in expected_results {
2051 let context = SeContext::new(label)?;
2052 let result = check_label_is_allowed(&context);
2053 if expected_valid {
2054 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2055 } else if result.is_ok() {
2056 bail!("Expected label {} to be disallowed", label);
2057 }
2058 }
2059 Ok(())
2060 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002061
2062 #[test]
2063 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2064 let apk = tempfile::tempfile().unwrap();
2065 let idsig = tempfile::tempfile().unwrap();
2066
2067 let ret = create_or_update_idsig_file(
2068 &ParcelFileDescriptor::new(apk),
2069 &ParcelFileDescriptor::new(idsig),
2070 );
2071 assert!(ret.is_err(), "should fail");
2072 Ok(())
2073 }
2074
2075 #[test]
2076 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2077 let tmp_dir = tempfile::TempDir::new().unwrap();
2078 let apk = File::open(tmp_dir.path()).unwrap();
2079 let idsig = tempfile::tempfile().unwrap();
2080
2081 let ret = create_or_update_idsig_file(
2082 &ParcelFileDescriptor::new(apk),
2083 &ParcelFileDescriptor::new(idsig),
2084 );
2085 assert!(ret.is_err(), "should fail");
2086 Ok(())
2087 }
2088
2089 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2090 /// on ext4 filesystem is passed.
2091 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2092 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2093 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2094 #[test]
2095 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2096 // APEXes are backed by the ext4.
2097 let apk = File::open("/apex/com.android.virt/").unwrap();
2098 let idsig = tempfile::tempfile().unwrap();
2099
2100 let ret = create_or_update_idsig_file(
2101 &ParcelFileDescriptor::new(apk),
2102 &ParcelFileDescriptor::new(idsig),
2103 );
2104 assert!(ret.is_err(), "should fail");
2105 Ok(())
2106 }
Jiyong Park8d192952023-06-26 14:29:51 +09002107
2108 #[test]
2109 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2110 use std::io::Seek;
2111
2112 // Pick any APK
2113 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2114 let mut idsig = tempfile::tempfile().unwrap();
2115
2116 create_or_update_idsig_file(
2117 &ParcelFileDescriptor::new(apk.try_clone()?),
2118 &ParcelFileDescriptor::new(idsig.try_clone()?),
2119 )?;
2120 let modified_orig = idsig.metadata()?.modified()?;
2121 apk.rewind()?;
2122 idsig.rewind()?;
2123
2124 // Call the function again
2125 create_or_update_idsig_file(
2126 &ParcelFileDescriptor::new(apk.try_clone()?),
2127 &ParcelFileDescriptor::new(idsig.try_clone()?),
2128 )?;
2129 let modified_new = idsig.metadata()?.modified()?;
2130 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2131 Ok(())
2132 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002133
2134 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002135 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2136 use std::io::Read;
2137
2138 // Pick any APK
2139 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2140 let idsig_empty = tempfile::tempfile().unwrap();
2141 let mut idsig_invalid = tempfile::tempfile().unwrap();
2142 idsig_invalid.write_all(b"Oops")?;
2143
2144 // Create new idsig
2145 create_or_update_idsig_file(
2146 &ParcelFileDescriptor::new(apk.try_clone()?),
2147 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2148 )?;
2149 apk.rewind()?;
2150
2151 // Update idsig_invalid
2152 create_or_update_idsig_file(
2153 &ParcelFileDescriptor::new(apk.try_clone()?),
2154 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2155 )?;
2156
2157 // Ensure the 2 idsig files have same size!
2158 assert!(
2159 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2160 "idsig files differ in size"
2161 );
2162 // Ensure the 2 idsig files have same content!
2163 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2164 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2165 }
2166 Ok(())
2167 }
2168 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002169 fn test_append_kernel_param_first_param() {
2170 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2171 append_kernel_param("foo=1", &mut vm_config);
2172 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2173 }
2174
2175 #[test]
2176 fn test_append_kernel_param() {
2177 let mut vm_config =
2178 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2179 append_kernel_param("bar=42", &mut vm_config);
2180 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2181 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002182
Inseob Kim46257382024-01-03 15:41:22 +09002183 fn test_extract_os_name_from_config_path(
2184 path: &Path,
2185 expected_result: Option<&str>,
2186 ) -> Result<()> {
2187 let result = extract_os_name_from_config_path(path);
2188 if result.as_deref() != expected_result {
2189 bail!("Expected {:?} but was {:?}", expected_result, &result)
2190 }
2191 Ok(())
2192 }
2193
2194 #[test]
2195 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2196 test_extract_os_name_from_config_path(
2197 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2198 Some("microdroid"),
2199 )
2200 }
2201
2202 #[test]
2203 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2204 test_extract_os_name_from_config_path(
2205 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2206 Some("microdroid_gki-android14-6.1"),
2207 )
2208 }
2209
2210 #[test]
2211 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2212 test_extract_os_name_from_config_path(
2213 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2214 None,
2215 )
2216 }
2217
2218 #[test]
2219 fn test_extract_os_name_from_configs() -> Result<()> {
2220 let tmp_dir = tempfile::TempDir::new()?;
2221 let tmp_dir_path = tmp_dir.path().to_owned();
2222
2223 let mut os_names: HashSet<String> = HashSet::new();
2224 os_names.insert("microdroid".to_owned());
2225 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2226 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2227
2228 // config files
2229 for os_name in &os_names {
2230 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2231 }
2232
2233 // fake files not related to configs
2234 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2235 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2236
2237 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2238 Some(s) => s.to_owned(),
2239 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2240 };
2241
2242 let result = extract_os_names_from_configs(&glob_pattern)?;
2243 if result != os_names {
2244 bail!("Expected {:?} but was {:?}", os_names, result);
2245 }
2246 Ok(())
2247 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002248
2249 #[test]
2250 fn test_find_early_vms_from_xml() -> Result<()> {
2251 let tmp_dir = tempfile::TempDir::new()?;
2252 let tmp_dir_path = tmp_dir.path().to_owned();
2253 let xml_path = tmp_dir_path.join("early_vms.xml");
2254
2255 std::fs::write(
2256 &xml_path,
2257 br#"<?xml version="1.0" encoding="utf-8"?>
2258 <early_vms>
2259 <early_vm>
2260 <name>vm_demo_native_early</name>
2261 <cid>123</cid>
2262 <path>/system/bin/vm_demo_native_early</path>
2263 </early_vm>
2264 <early_vm>
2265 <name>vm_demo_duplicated_name</name>
2266 <cid>456</cid>
2267 <path>/system/bin/vm_demo_duplicated_name_1</path>
2268 </early_vm>
2269 <early_vm>
2270 <name>vm_demo_duplicated_name</name>
2271 <cid>789</cid>
2272 <path>/system/bin/vm_demo_duplicated_name_2</path>
2273 </early_vm>
2274 <early_vm>
2275 <name>vm_demo_invalid_cid_1</name>
2276 <cid>-1</cid>
2277 <path>/system/bin/vm_demo_invalid_cid_1</path>
2278 </early_vm>
2279 <early_vm>
2280 <name>vm_demo_invalid_cid_2</name>
2281 <cid>999999</cid>
2282 <path>/system/bin/vm_demo_invalid_cid_2</path>
2283 </early_vm>
2284 </early_vms>
2285 "#,
2286 )?;
2287
2288 let cid_range = 100..1000;
2289
2290 let result = find_early_vm(&xml_path, &cid_range, "vm_demo_native_early")?;
2291 let expected = EarlyVm {
2292 name: "vm_demo_native_early".to_owned(),
2293 cid: 123,
2294 path: "/system/bin/vm_demo_native_early".to_owned(),
2295 };
2296 assert_eq!(result, expected);
2297
2298 assert!(
2299 find_early_vm(&xml_path, &cid_range, "vm_demo_duplicated_name").is_err(),
2300 "should fail"
2301 );
2302 assert!(
2303 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_1").is_err(),
2304 "should fail"
2305 );
2306 assert!(
2307 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_2").is_err(),
2308 "should fail"
2309 );
2310
2311 Ok(())
2312 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002313}