blob: 52bfd87d4f68717d6ea0e40689046cfa2fb7e5f7 [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;
Devin Moorec8800a12024-10-17 17:56:18 +000070use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000071use log::{debug, error, info, warn};
Inseob Kim89b24592024-02-23 18:59:43 +090072use microdroid_payload_config::{ApkConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090073use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000074use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000075use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090076use semver::VersionReq;
Inseob Kimecde8c02024-09-03 13:11:08 +090077use serde::Deserialize;
Inseob Kim6ef80972023-07-20 17:23:36 +090078use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000079use std::convert::TryInto;
Shikha Panwar55e10ec2024-02-13 12:53:49 +000080use std::fs;
Jaewan Kim39952072024-01-19 17:04:53 +090081use std::ffi::CStr;
Inseob Kimecde8c02024-09-03 13:11:08 +090082use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000083use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
Inseob Kim46257382024-01-03 15:41:22 +090084use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000085use std::num::{NonZeroU16, NonZeroU32};
Inseob Kimecde8c02024-09-03 13:11:08 +090086use std::ops::Range;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +090087use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000088use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000089use std::path::{Path, PathBuf};
Andrew Walbran9c03a3a2024-09-03 12:12:59 +010090use std::sync::{Arc, Mutex, Weak, LazyLock};
Seungjae Yoo14e60182024-02-21 13:28:31 +090091use vbmeta::VbMetaImage;
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010092use vmconfig::{VmConfig, get_debug_level};
Devin Moorec8800a12024-10-17 17:56:18 +000093use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090094use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000095
David Brazdil41d1a872022-10-05 14:44:19 +010096/// The unique ID of a VM used (together with a port number) for vsock communication.
97pub type Cid = u32;
98
David Brazdil4b4c5102022-12-19 22:56:20 +000099pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
100
Devin Moore407df8f2024-08-27 19:39:16 +0000101/// Vsock privileged ports are below this number.
102const VSOCK_PRIV_PORT_MAX: u32 = 1024;
103
Jooyung Han95884632021-07-06 22:27:54 +0900104/// The size of zero.img.
105/// Gaps in composite disk images are filled with a shared zero.img.
106const ZERO_FILLER_SIZE: u64 = 4096;
107
David Brazdilf50c7a62023-04-19 14:22:42 +0000108/// Magic string for the instance image
109const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
110
111/// Version of the instance image format
112const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
113
Alan Stokes0d1ef782022-09-27 13:46:35 +0100114const MICRODROID_OS_NAME: &str = "microdroid";
115
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000116const SECRETKEEPER_IDENTIFIER: &str =
Shikha Panwarbe5dee72024-02-21 19:06:20 +0000117 "android.hardware.security.secretkeeper.ISecretkeeper/default";
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000118
David Brazdilf50c7a62023-04-19 14:22:42 +0000119const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
120
121/// crosvm requires all partitions to be a multiple of 4KiB.
122const PARTITION_GRANULARITY_BYTES: u64 = 4096;
123
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000124const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
125
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100126pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
127 LazyLock::new(|| {
Inseob Kimecde8c02024-09-03 13:11:08 +0900128 if cfg!(early) {
129 panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
130 } else {
131 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
132 .expect("Could not connect to VirtualizationServiceInternal")
133 }
Andrew Walbran9c03a3a2024-09-03 12:12:59 +0100134 });
135static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
136 LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
David Brazdil49f96f52022-12-16 21:29:13 +0000137
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000138fn create_or_update_idsig_file(
139 input_fd: &ParcelFileDescriptor,
140 idsig_fd: &ParcelFileDescriptor,
141) -> Result<()> {
142 let mut input = clone_file(input_fd)?;
143 let metadata = input.metadata().context("failed to get input metadata")?;
144 if !metadata.is_file() {
145 bail!("input is not a regular file");
146 }
Alan Stokes25f69362023-03-06 16:51:54 +0000147 let mut sig =
148 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
149 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000150
151 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900152
153 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
154 // if the idsig file already has the same APK digest.
155 if output.metadata()?.len() > 0 {
156 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
157 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
158 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
159 return Ok(());
160 }
161 }
162 // if we fail to read v4signature from output, that's fine. User can pass a random file.
163 // We will anyway overwrite the file to the v4signature generated from input_fd.
164 }
165
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000166 output
167 .seek(SeekFrom::Start(0))
168 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000169 output.set_len(0).context("failed to set_len on the idsig output")?;
170 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000171 Ok(())
172}
173
Alan Stokes25f69362023-03-06 16:51:54 +0000174fn get_current_sdk() -> Result<u32> {
175 let current_sdk = system_properties::read("ro.build.version.sdk")?;
176 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
177 current_sdk.parse().context("Malformed SDK version")
178}
179
David Brazdil4b4c5102022-12-19 22:56:20 +0000180pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
181 for dir_entry in read_dir(path)? {
182 remove_file(dir_entry?.path())?;
183 }
184 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100185}
186
David Brazdil528e0472022-10-10 15:06:02 +0100187/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000188#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000189pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900190 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000191}
192
Shikha Panward8e35422021-10-11 13:51:27 +0000193impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000194 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000195 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
196 let state = &mut *self.state.lock().unwrap();
197 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000198 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000199 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000200 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
201 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000202 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000203 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000204 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000205 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
206 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000207 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000208 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000209 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000210 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000211 .or(Err(StatusCode::UNKNOWN_ERROR))?;
212 }
213 Ok(())
214 }
215}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000216impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000217 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
218 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000219 ///
220 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000221 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000222 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000223 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900224 console_out_fd: Option<&ParcelFileDescriptor>,
225 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000226 log_fd: Option<&ParcelFileDescriptor>,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000227 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000228 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000229 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900230 let ret = self.create_vm_internal(
231 config,
232 console_out_fd,
233 console_in_fd,
234 log_fd,
235 &mut is_protected,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000236 dump_dt_fd,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900237 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000238 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000239 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000240 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000241
Shikha Panwar61a74b52024-02-16 13:17:01 +0000242 /// Allocate a new instance_id to the VM
243 fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000244 check_manage_access()?;
Shikha Panwar61a74b52024-02-16 13:17:01 +0000245 GLOBAL_SERVICE.allocateInstanceId()
246 }
247
Andrew Walbrandff3b942021-06-09 15:20:36 +0000248 /// Initialise an empty partition image of the given size to be used as a writable partition.
249 fn initializeWritablePartition(
250 &self,
251 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000252 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900253 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000254 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900255 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900256 let size_bytes = size_bytes
257 .try_into()
258 .with_context(|| format!("Invalid size: {}", size_bytes))
259 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000260 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000261 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000262 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000263 image
264 .seek(SeekFrom::Start(0))
265 .context("failed to move cursor to start")
266 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900267 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Frederick Mayle0d310572024-05-02 12:34:58 -0700268 // Set the file length. In most filesystems, this will not allocate any physical disk
269 // space, it will only change the logical size.
270 image
271 .set_len(size_bytes)
272 .context("Failed to extend file")
Jiyong Park2227eaa2023-08-04 11:59:18 +0900273 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000274
275 match partition_type {
276 PartitionType::RAW => Ok(()),
Frederick Mayle0d310572024-05-02 12:34:58 -0700277 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
278 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
David Brazdilf50c7a62023-04-19 14:22:42 +0000279 _ => Err(Error::new(
280 ErrorKind::Unsupported,
281 format!("Unsupported partition type {:?}", partition_type),
282 )),
283 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900284 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
285 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000286
287 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000288 }
289
Jiyong Park0a248432021-08-20 23:32:39 +0900290 /// Creates or update the idsig file by digesting the input APK file.
291 fn createOrUpdateIdsigFile(
292 &self,
293 input_fd: &ParcelFileDescriptor,
294 idsig_fd: &ParcelFileDescriptor,
295 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900296 check_manage_access()?;
297
Jiyong Park2227eaa2023-08-04 11:59:18 +0900298 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900299 Ok(())
300 }
301
Andrew Walbran320b5602021-03-04 16:11:12 +0000302 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
303 /// and as such is only permitted from the shell user.
304 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000305 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000306 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000307 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900308
309 /// Get a list of assignable device types.
310 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
311 // Delegate to the global service, including checking the permission.
312 GLOBAL_SERVICE.getAssignableDevices()
313 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100314
Inseob Kim46257382024-01-03 15:41:22 +0900315 /// Get a list of supported OSes.
316 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
317 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
318 }
319
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100320 /// Returns whether given feature is enabled
321 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
322 check_manage_access()?;
Shikha Panwar6d306412024-02-17 21:37:49 +0000323 Ok(avf_features::is_feature_enabled(feature))
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100324 }
Alice Wange64dd182024-01-17 15:57:55 +0000325
326 fn enableTestAttestation(&self) -> binder::Result<()> {
327 GLOBAL_SERVICE.enableTestAttestation()
328 }
Alice Wang0362f7f2024-03-21 08:16:26 +0000329
330 fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
331 check_manage_access()?;
332 GLOBAL_SERVICE.isRemoteAttestationSupported()
333 }
Shikha Panwar7aef66d2024-03-13 00:28:41 +0000334
335 fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
336 // The response is specific to Microdroid. Updatable VMs are only possible if device
337 // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
338 // this, however other guest OSes may do things differently.
339 check_manage_access()?;
340 Ok(is_secretkeeper_supported())
341 }
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000342
Shikha Panwar07d701c2024-03-28 14:43:52 +0000343 fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
344 check_manage_access()?;
345 GLOBAL_SERVICE.removeVmInstance(instance_id)
346 }
347
Shikha Panwarbd5eba92024-03-27 20:23:31 +0000348 fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
349 check_manage_access()?;
350 GLOBAL_SERVICE.claimVmInstance(instance_id)
351 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000352}
353
Inseob Kimecde8c02024-09-03 13:11:08 +0900354/// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
355#[derive(Debug, Default)]
356struct EarlyVmContext {
357 /// The unique CID assigned to the VM for vsock communication.
358 cid: Cid,
359 /// Temporary directory for this VM instance.
360 temp_dir: PathBuf,
361}
362
363impl EarlyVmContext {
364 fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
365 // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
366 // should trust clients, e.g. they won't run two VMs at the same time
367 let _ = remove_dir_all(&temp_dir);
368 create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
369
370 Ok(Self { cid, temp_dir })
371 }
372}
373
374impl Interface for EarlyVmContext {}
375
376impl Drop for EarlyVmContext {
377 fn drop(&mut self) {
378 if let Err(e) = remove_dir_all(&self.temp_dir) {
379 error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
380 }
381 }
382}
383
384impl IGlobalVmContext for EarlyVmContext {
385 fn getCid(&self) -> binder::Result<i32> {
386 Ok(self.cid as i32)
387 }
388
389 fn getTemporaryDirectory(&self) -> binder::Result<String> {
390 Ok(self.temp_dir.to_string_lossy().to_string())
391 }
392
393 fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
394 Err(Status::new_exception_str(
395 ExceptionCode::UNSUPPORTED_OPERATION,
396 Some("Early VM doesn't support setting host console name"),
397 ))
398 }
399}
400
401fn find_partition(path: &Path) -> binder::Result<String> {
402 match path.components().nth(1) {
403 Some(std::path::Component::Normal(partition)) => {
404 Ok(partition.to_string_lossy().into_owned())
405 }
406 _ => Err(anyhow!("Can't find partition in '{}'", path.display()))
407 .or_service_specific_exception(-1),
408 }
409}
410
Jiyong Park8611a6c2021-07-09 18:17:44 +0900411impl VirtualizationService {
412 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000413 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900414 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000415
Inseob Kimecde8c02024-09-03 13:11:08 +0900416 fn create_early_vm_context(
417 &self,
418 config: &VirtualMachineConfig,
419 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
420 let calling_exe_path = format!("/proc/{}/exe", get_calling_pid());
421 let link = fs::read_link(&calling_exe_path)
422 .context(format!("can't read_link '{calling_exe_path}'"))
423 .or_service_specific_exception(-1)?;
424 let partition = find_partition(&link)?;
425
426 let name = match config {
427 VirtualMachineConfig::RawConfig(config) => &config.name,
428 VirtualMachineConfig::AppConfig(config) => &config.name,
429 };
430 let early_vm =
431 find_early_vm_for_partition(&partition, name).or_service_specific_exception(-1)?;
432 if Path::new(&early_vm.path) != link {
433 return Err(anyhow!(
434 "VM '{name}' in partition '{partition}' must be created with '{}', not '{}'",
435 &early_vm.path,
436 link.display()
437 ))
438 .or_service_specific_exception(-1);
439 }
440
441 let cid = early_vm.cid as Cid;
442 let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
443
444 let context = EarlyVmContext::new(cid, temp_dir.clone())
445 .context(format!("Can't create early vm contexts for {cid}"))
446 .or_service_specific_exception(-1)?;
447 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
448
449 // Start VM service listening for connections from the new CID on port=CID.
450 let port = cid;
451 let vm_server = RpcServer::new_vsock(service, cid, port)
452 .context(format!("Could not start RpcServer on port {port}"))
453 .or_service_specific_exception(-1)?;
454 vm_server.start();
455 Ok((VmContext::new(Strong::new(Box::new(context)), vm_server), cid, temp_dir))
456 }
457
David Brazdil209074a2023-01-12 16:44:51 +0000458 fn create_vm_context(
459 &self,
460 requester_debug_pid: pid_t,
461 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000462 const NUM_ATTEMPTS: usize = 5;
463
464 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000465 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000466 let cid = vm_context.getCid()? as Cid;
467 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000468 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
469
470 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000471 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000472 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000473 Ok(vm_server) => {
474 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000475 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000476 }
477 Err(err) => {
478 warn!("Could not start RpcServer on port {}: {}", port, err);
479 }
480 }
481 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900482 Err(anyhow!("Too many attempts to create VM context failed"))
483 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000484 }
485
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000486 fn create_vm_internal(
487 &self,
488 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900489 console_out_fd: Option<&ParcelFileDescriptor>,
490 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000491 log_fd: Option<&ParcelFileDescriptor>,
492 is_protected: &mut bool,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000493 dump_dt_fd: Option<&ParcelFileDescriptor>,
Devin Moore407df8f2024-08-27 19:39:16 +0000494 ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000495 let requester_uid = get_calling_uid();
496 let requester_debug_pid = get_calling_pid();
497
Nikita Ioffe631717e2023-09-05 13:38:07 +0100498 check_config_features(config)?;
499
Inseob Kimecde8c02024-09-03 13:11:08 +0900500 if cfg!(early) {
501 check_config_allowed_for_early_vms(config)?;
502 }
503
David Brazdil209074a2023-01-12 16:44:51 +0000504 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
Inseob Kimecde8c02024-09-03 13:11:08 +0900505 let (vm_context, cid, temporary_directory) = if cfg!(early) {
506 self.create_early_vm_context(config)?
507 } else {
508 self.create_vm_context(requester_debug_pid)?
509 };
Inseob Kim1119d702022-05-02 18:01:58 +0900510
Alan Stokesfda70842023-12-20 17:50:14 +0000511 if is_custom_config(config) {
Alan Stokes7bc146c2022-10-20 17:10:32 +0100512 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900513 }
514
Nikita Ioffe5776f082023-02-10 21:38:26 +0000515 let gdb_port = extract_gdb_port(config);
516
517 // Additional permission checks if caller request gdb.
518 if gdb_port.is_some() {
519 check_gdb_allowed(config)?;
520 }
521
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000522 let device_tree_overlay = maybe_create_device_tree_overlay(config, &temporary_directory)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900523
Jaewan Kimf3143242024-03-15 06:56:31 +0000524 let debug_config = DebugConfig::new(config);
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +0000525 let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900526 Some(prepare_ramdump_file(&temporary_directory)?)
527 } else {
528 None
529 };
530
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000531 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900532 let console_out_fd =
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100533 clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900534 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Pierre-Clément Tosifc523c52024-08-20 10:34:06 +0100535 let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000536 let dump_dt_fd = dump_dt_fd.map(clone_file).transpose()?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000537
538 // Counter to generate unique IDs for temporary image files.
539 let mut next_temporary_image_id = 0;
540 // Files which are referred to from composite images. These must be mapped to the crosvm
541 // child process, and not closed before it is started.
542 let mut indirect_files = vec![];
543
Alan Stokes7bc146c2022-10-20 17:10:32 +0100544 let (is_app_config, config) = match config {
545 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
546 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900547 let config = load_app_config(config, &debug_config, &temporary_directory)
548 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900549 *is_protected = config.protectedVm;
550 let message = format!("Failed to load app config: {:?}", e);
551 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900552 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900553 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100554 (true, BorrowedOrOwned::Owned(config))
555 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000556 };
557 let config = config.as_ref();
558 *is_protected = config.protectedVm;
559
560 // Check if partition images are labeled incorrectly. This is to prevent random images
561 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100562 // being loaded in a pVM. This applies to everything but the instance image in the raw
563 // config, and everything but the non-executable, generated partitions in the app
564 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000565 config
566 .disks
567 .iter()
568 .flat_map(|disk| disk.partitions.iter())
569 .filter(|partition| {
570 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100571 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000572 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000573 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000574 }
575 })
576 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900577 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000578
Inseob Kimff48a7c2024-02-26 22:07:21 +0900579 // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
580 // have unstable interfaces.
581 // TODO(b/316431494): remove once Treble interfaces are stabilized.
582 check_partitions_for_files(config).or_service_specific_exception(-1)?;
583
Alan Stokes185fe112023-01-10 16:20:55 +0000584 let kernel = maybe_clone_file(&config.kernel)?;
585 let initrd = maybe_clone_file(&config.initrd)?;
586
Alan Stokes185fe112023-01-10 16:20:55 +0000587 if config.protectedVm {
Nikita Ioffef934e812024-07-05 15:44:41 +0000588 // In a protected VM, we require custom kernels to come from a trusted source
589 // (b/237054515).
Jiyong Park2227eaa2023-08-04 11:59:18 +0900590 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Nikita Ioffef934e812024-07-05 15:44:41 +0000591 // Fail fast with a meaningful error message in case device doesn't support pVMs.
592 check_protected_vm_is_supported()?;
Alan Stokes185fe112023-01-10 16:20:55 +0000593 }
594
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000595 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900596 write_zero_filler(&zero_filler_path)
597 .context("Failed to make composite image")
598 .with_log()
599 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000600
601 // Assemble disk images if needed.
602 let disks = config
603 .disks
604 .iter()
605 .map(|disk| {
606 assemble_disk_image(
607 disk,
608 &zero_filler_path,
609 &temporary_directory,
610 &mut next_temporary_image_id,
611 &mut indirect_files,
612 )
613 })
614 .collect::<Result<Vec<DiskFile>, _>>()?;
615
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000616 let (cpus, host_cpu_topology) = match config.cpuTopology {
617 CpuTopology::MATCH_HOST => (None, true),
618 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
619 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900620 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
621 .with_log()
622 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000623 }
624 };
625
David Brazdil2dfefd12023-11-17 14:07:36 +0000626 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900627 let mut set = HashSet::new();
628 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900629 let path = canonicalize(device)
630 .with_context(|| format!("can't canonicalize {device}"))
631 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900632 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900633 return Err(anyhow!("duplicated device {device}"))
634 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900635 }
636 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000637 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000638 let dtbo_file = File::from(
639 GLOBAL_SERVICE
640 .getDtboFile()?
641 .as_ref()
642 .try_clone()
Jaewan Kim39952072024-01-19 17:04:53 +0900643 .context("Failed to create VM DTBO from ParcelFileDescriptor")
David Brazdil2dfefd12023-11-17 14:07:36 +0000644 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
645 );
646 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900647 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000648 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900649 };
Jeongik Cha798401c2024-04-11 21:54:49 +0900650 let display_config = if cfg!(paravirtualized_devices) {
651 config
652 .displayConfig
653 .as_ref()
654 .map(DisplayConfig::new)
655 .transpose()
656 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
657 } else {
658 None
659 };
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700660 let gpu_config = if cfg!(paravirtualized_devices) {
661 config
662 .gpuConfig
663 .as_ref()
664 .map(GpuConfig::new)
665 .transpose()
666 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
667 } else {
668 None
669 };
Jeongik Cha1df1c032024-04-03 16:03:12 +0900670
Jeongik Chac181be72024-03-27 00:18:30 +0900671 let input_device_options = if cfg!(paravirtualized_devices) {
672 config
673 .inputDevices
674 .iter()
675 .map(to_input_device_option_from)
676 .collect::<Result<Vec<InputDeviceOption>, _>>()
677 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
678 } else {
679 vec![]
680 };
681
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900682 // Create TAP network interface if the VM supports network.
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900683 let tap = if cfg!(network) && config.networkSupported {
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900684 if *is_protected {
685 return Err(anyhow!("Network feature is not supported for pVM yet"))
686 .with_log()
687 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
688 }
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900689 Some(File::from(
690 GLOBAL_SERVICE
691 .createTapInterface(&get_this_pid().to_string())?
692 .as_ref()
693 .try_clone()
694 .context("Failed to get TAP interface from ParcelFileDescriptor")
695 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
696 ))
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900697 } else {
698 None
699 };
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800700
701 let audio_config = if cfg!(paravirtualized_devices) {
702 config.audioConfig.as_ref().map(AudioConfig::new)
703 } else {
704 None
705 };
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900706
Elie Kheirallah29d72912024-08-07 20:17:26 +0000707 let usb_config = config
708 .usbConfig
709 .as_ref()
710 .map(UsbConfig::new)
711 .unwrap_or(Ok(UsbConfig { controller: false }))
712 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
713
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000714 // Actually start the VM.
715 let crosvm_config = CrosvmConfig {
716 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000717 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000718 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000719 kernel,
720 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000721 disks,
722 params: config.params.to_owned(),
723 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900724 debug_config,
Frederick Mayle68d06e72024-07-12 17:18:11 -0700725 memory_mib: config
726 .memoryMib
727 .try_into()
728 .ok()
729 .and_then(NonZeroU32::new)
730 .unwrap_or(NonZeroU32::new(256).unwrap()),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000731 cpus,
732 host_cpu_topology,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900733 console_out_fd,
734 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000735 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900736 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000737 indirect_files,
738 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900739 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000740 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900741 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000742 dtbo,
Shikha Panwar55e10ec2024-02-13 12:53:49 +0000743 device_tree_overlay,
Jeongik Cha1df1c032024-04-03 16:03:12 +0900744 display_config,
Jeongik Chac181be72024-03-27 00:18:30 +0900745 input_device_options,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000746 hugepages: config.hugePages,
Seungjae Yoo986d7a42024-05-28 14:06:58 +0900747 tap,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800748 console_input_device: config.consoleInputDevice.clone(),
David Dai23cff712024-06-13 19:23:45 +0000749 boost_uclamp: config.boostUclamp,
Jason Macnakea7b0fa2024-05-08 17:02:44 -0700750 gpu_config,
Mu-Le Leeb2d5a312024-06-05 10:52:47 +0800751 audio_config,
Jeongik Cha75057452024-09-03 11:26:04 +0900752 no_balloon: config.noBalloon,
Elie Kheirallah29d72912024-08-07 20:17:26 +0000753 usb_config,
Elie Kheirallah5c807a22024-09-23 20:40:42 +0000754 dump_dt_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000755 };
756 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100757 VmInstance::new(
758 crosvm_config,
759 temporary_directory,
760 requester_uid,
761 requester_debug_pid,
762 vm_context,
763 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900764 .with_context(|| format!("Failed to create VM with config {:?}", config))
765 .with_log()
766 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000767 );
768 state.add_vm(Arc::downgrade(&instance));
769 Ok(VirtualMachine::create(instance))
770 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900771}
772
Alan Stokesfda70842023-12-20 17:50:14 +0000773/// Returns whether a VM config represents a "custom" virtual machine, which requires the
774/// USE_CUSTOM_VIRTUAL_MACHINE.
775fn is_custom_config(config: &VirtualMachineConfig) -> bool {
776 match config {
777 // Any raw (non-Microdroid) VM is considered custom.
778 VirtualMachineConfig::RawConfig(_) => true,
779 VirtualMachineConfig::AppConfig(config) => {
780 // Some features are reserved for platform apps only, even when using
781 // VirtualMachineAppConfig. Almost all of these features are grouped in the
782 // CustomConfig struct:
783 // - controlling CPUs;
784 // - gdbPort is set, meaning that crosvm will start a gdb server;
785 // - using anything other than the default kernel;
786 // - specifying devices to be assigned.
787 if config.customConfig.is_some() {
788 true
789 } else {
790 // Additional custom features not included in CustomConfig:
791 // - specifying a config file;
Alan Stokes736f6822024-02-16 16:08:00 +0000792 // - specifying extra APKs;
793 // - specifying an OS other than Microdroid.
Inseob Kim89b24592024-02-23 18:59:43 +0900794 (match &config.payload {
Alan Stokesfda70842023-12-20 17:50:14 +0000795 Payload::ConfigPath(_) => true,
Inseob Kim89b24592024-02-23 18:59:43 +0900796 Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
797 }) || config.osName != MICRODROID_OS_NAME
Alan Stokesfda70842023-12-20 17:50:14 +0000798 }
799 }
800 }
801}
802
Seungjae Yoo14e60182024-02-21 13:28:31 +0900803fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
804 let VirtualMachineConfig::AppConfig(config) = config else {
805 return Ok(None);
806 };
807 let Some(custom_config) = &config.customConfig else {
808 return Ok(None);
809 };
810 let Some(file) = custom_config.vendorImage.as_ref() else {
811 return Ok(None);
812 };
813
814 let file = clone_file(file)?;
815 let size =
816 file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
817 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
818 .context("Failed to get vbmeta from microdroid-vendor.img")?;
819
820 for descriptor in vbmeta.descriptors()?.iter() {
821 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
822 let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
823 return Ok(Some(root_digest.as_bytes().to_vec()));
824 }
825 }
826 Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
827}
828
Nikita Ioffeb2c6f3a2024-06-06 12:51:53 +0000829fn maybe_create_device_tree_overlay(
830 config: &VirtualMachineConfig,
831 temporary_directory: &Path,
832) -> binder::Result<Option<File>> {
833 // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
834 // (e.g. instance-id)
835 let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
836 let host_ref_dt = if host_ref_dt.exists()
837 && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
838 {
839 Some(host_ref_dt)
840 } else {
841 warn!("VM reference DT doesn't exist in host DT");
842 None
843 };
844
845 let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
846 .context("Failed to extract vendor hashtree digest")
847 .or_service_specific_exception(-1)?;
848
849 let trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
850 info!(
851 "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
852 match the trusted digest in the pvmfw config, causing the VM to fail to start."
853 );
854 vec![(cstr!("vendor_hashtree_descriptor_root_digest"), vendor_hashtree_digest.as_slice())]
855 } else {
856 vec![]
857 };
858
859 let instance_id;
860 let mut untrusted_props = Vec::with_capacity(2);
861 if cfg!(llpvm_changes) {
862 instance_id = extract_instance_id(config);
863 untrusted_props.push((cstr!("instance-id"), &instance_id[..]));
864 let want_updatable = extract_want_updatable(config);
865 if want_updatable && is_secretkeeper_supported() {
866 // Let guest know that it can defer rollback protection to Secretkeeper by setting
867 // an empty property in untrusted node in DT. This enables Updatable VMs.
868 untrusted_props.push((cstr!("defer-rollback-protection"), &[]))
869 }
870 }
871
872 let device_tree_overlay = if host_ref_dt.is_some()
873 || !untrusted_props.is_empty()
874 || !trusted_props.is_empty()
875 {
876 let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
877 let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
878 let fdt =
879 create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
880 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
881 .or_service_specific_exception(-1)?;
882 fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
883 Some(File::open(dt_output).or_service_specific_exception(-1)?)
884 } else {
885 None
886 };
887 Ok(device_tree_overlay)
888}
889
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000890fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900891 let file = OpenOptions::new()
892 .create_new(true)
893 .read(true)
894 .write(true)
895 .open(zero_filler_path)
896 .with_context(|| "Failed to create zero.img")?;
897 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000898 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900899}
900
David Brazdilf50c7a62023-04-19 14:22:42 +0000901fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
902 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
903 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
904 part.flush()
905}
906
907fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
908 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
909 part.flush()
910}
911
912fn round_up(input: u64, granularity: u64) -> u64 {
913 if granularity == 0 {
914 return input;
915 }
916 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
917 let result = input.checked_add(granularity - 1).unwrap_or(input);
918 (result / granularity) * granularity
919}
920
Jeongik Chac181be72024-03-27 00:18:30 +0900921fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
922 Ok(match input_device {
923 InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
924 file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
925 height: u32::try_from(single_touch.height)?,
926 width: u32::try_from(single_touch.width)?,
927 name: if !single_touch.name.is_empty() {
928 Some(single_touch.name.clone())
929 } else {
930 None
931 },
932 },
933 InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
934 evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
935 )?),
Jeongik Cha985b6402024-04-15 18:13:00 +0900936 InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
937 keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
938 )?),
Jeongik Cha343894e2024-05-17 20:39:31 +0900939 InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
940 mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
941 )?),
Jiyong Park6c1b9f02024-07-05 16:21:10 +0900942 InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
943 switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
944 )?),
Jeongik Cha112a2682024-07-09 12:28:45 +0900945 InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
946 file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
947 height: u32::try_from(trackpad.height)?,
948 width: u32::try_from(trackpad.width)?,
949 name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
950 },
Jeongik Cha10494912024-07-16 11:19:50 +0900951 InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
952 file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
953 height: u32::try_from(multi_touch.height)?,
954 width: u32::try_from(multi_touch.width)?,
955 name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
956 },
Jeongik Chac181be72024-03-27 00:18:30 +0900957 })
958}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000959/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
960///
961/// This may involve assembling a composite disk from a set of partition images.
962fn assemble_disk_image(
963 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900964 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000965 temporary_directory: &Path,
966 next_temporary_image_id: &mut u64,
967 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000968) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000969 let image = if !disk.partitions.is_empty() {
970 if disk.image.is_some() {
971 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900972 return Err(anyhow!("DiskImage contains both image and partitions"))
973 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000974 }
975
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000976 let composite_image_filenames =
977 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
978 let (image, partition_files) = make_composite_image(
979 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900980 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000981 &composite_image_filenames.composite,
982 &composite_image_filenames.header,
983 &composite_image_filenames.footer,
984 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900985 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
986 .with_log()
987 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000988
989 // Pass the file descriptors for the various partition files to crosvm when it
990 // is run.
991 indirect_files.extend(partition_files);
992
993 image
994 } else if let Some(image) = &disk.image {
995 clone_file(image)?
996 } else {
997 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900998 return Err(anyhow!("DiskImage didn't contain image or partitions."))
999 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001000 };
1001
1002 Ok(DiskFile { image, writable: disk.writable })
1003}
1004
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001005fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1006 if let Some(ref mut params) = vm_config.params {
1007 params.push(' ');
1008 params.push_str(param)
1009 } else {
1010 vm_config.params = Some(param.to_owned())
1011 }
1012}
1013
Inseob Kim46257382024-01-03 15:41:22 +09001014fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1015 if config.extension()?.to_str()? != "json" {
1016 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +09001017 }
Inseob Kim46257382024-01-03 15:41:22 +09001018
1019 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1020}
1021
1022fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1023 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1024 let os_names =
1025 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1026
1027 Ok(os_names)
1028}
1029
1030fn get_supported_os_names() -> Result<HashSet<String>> {
1031 if !cfg!(vendor_modules) {
1032 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1033 }
1034
1035 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1036}
1037
1038fn is_valid_os(os_name: &str) -> bool {
1039 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +09001040}
1041
Nikita Ioffe2cb75cf2024-06-04 16:43:56 +00001042fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1043 if !cfg!(vendor_modules) {
1044 return false;
1045 }
1046 match config {
1047 VirtualMachineConfig::RawConfig(_) => false,
1048 VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1049 }
1050}
1051
Jooyung Han21e9b922021-06-26 04:14:16 +09001052fn load_app_config(
1053 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +09001054 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +09001055 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +09001056) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001057 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1058 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +09001059 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001060
Shikha Panwar22e70452022-10-10 18:32:55 +00001061 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1062 Some(clone_file(file)?)
1063 } else {
1064 None
1065 };
1066
Alan Stokesfda70842023-12-20 17:50:14 +00001067 let vm_payload_config;
1068 let extra_apk_files: Vec<_>;
1069 match &config.payload {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001070 Payload::ConfigPath(config_path) => {
Alan Stokesfda70842023-12-20 17:50:14 +00001071 vm_payload_config =
1072 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1073 .with_context(|| format!("Couldn't read config from {}", config_path))?;
1074 extra_apk_files = vm_payload_config
1075 .extra_apks
1076 .iter()
1077 .enumerate()
1078 .map(|(i, apk)| {
1079 File::open(PathBuf::from(&apk.path))
1080 .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1081 })
1082 .collect::<Result<_>>()?;
Alan Stokes0d1ef782022-09-27 13:46:35 +01001083 }
Alan Stokesfda70842023-12-20 17:50:14 +00001084 Payload::PayloadConfig(payload_config) => {
1085 vm_payload_config = create_vm_payload_config(payload_config)?;
1086 extra_apk_files =
1087 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1088 }
Alan Stokes0d1ef782022-09-27 13:46:35 +01001089 };
Jooyung Han21e9b922021-06-26 04:14:16 +09001090
Inseob Kim89b24592024-02-23 18:59:43 +09001091 let payload_config_os = vm_payload_config.os.name.as_str();
1092 if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1093 bail!("'os' in payload config is deprecated");
1094 }
1095
Inseob Kim172f9eb2023-11-06 17:02:08 +09001096 // For now, the only supported OS is Microdroid and Microdroid GKI
Inseob Kim89b24592024-02-23 18:59:43 +09001097 let os_name = config.osName.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +09001098 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +00001099 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +09001100 }
Andrew Walbrancc0db522021-07-12 17:03:42 +00001101
1102 // It is safe to construct a filename based on the os_name because we've already checked that it
1103 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +09001104 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1105 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +00001106 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001107
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001108 if let Some(custom_config) = &config.customConfig {
1109 if let Some(file) = custom_config.customKernelImage.as_ref() {
1110 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1111 }
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001112 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001113
1114 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001115 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
Pechetty Sravani (xWF)faabfbd2024-09-24 15:27:48 +00001116 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +01001117 }
Inseob Kim6ef80972023-07-20 17:23:36 +09001118
Chris Wailes6177c662024-05-09 14:37:44 -07001119 vm_config.devices.clone_from(&custom_config.devices);
Seungjae Yoo13af0b62024-05-20 14:15:13 +09001120 vm_config.networkSupported = custom_config.networkSupported;
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001121
1122 for param in custom_config.extraKernelCmdlineParams.iter() {
1123 append_kernel_param(param, &mut vm_config);
1124 }
Nikita Ioffe26c35ed2023-06-05 17:49:08 +01001125 }
1126
Andrew Walbrancc045902021-07-27 16:06:17 +00001127 if config.memoryMib > 0 {
1128 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +00001129 }
1130
Chris Wailes6177c662024-05-09 14:37:44 -07001131 vm_config.name.clone_from(&config.name);
Andrew Walbran3994f002022-01-27 17:33:45 +00001132 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +00001133 vm_config.cpuTopology = config.cpuTopology;
Vincent Donnefort538a2c62024-03-20 16:01:10 +00001134 vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
David Dai23cff712024-06-13 19:23:45 +00001135 vm_config.boostUclamp = config.boostUclamp;
Jiyong Park032615f2022-01-10 13:55:34 +09001136
Shikha Panwar22e70452022-10-10 18:32:55 +00001137 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +09001138 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +00001139
1140 // Include Microdroid payload disk (contains apks, idsigs) in vm config
1141 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +01001142 config,
Jaewan Kim61f86142023-03-28 15:12:52 +09001143 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001144 temporary_directory,
1145 apk_file,
1146 idsig_file,
Alan Stokesfda70842023-12-20 17:50:14 +00001147 extra_apk_files,
Alan Stokes0d1ef782022-09-27 13:46:35 +01001148 &vm_payload_config,
1149 &mut vm_config,
1150 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +09001151
Andrew Walbrancc0db522021-07-12 17:03:42 +00001152 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +09001153}
1154
Inseob Kimff48a7c2024-02-26 22:07:21 +09001155fn check_partition_for_file(fd: &ParcelFileDescriptor) -> Result<()> {
1156 let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1157 let link = fs::read_link(&path).context(format!("can't read_link {path}"))?;
1158
1159 // microdroid vendor image is OK
1160 if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1161 {
1162 return Ok(());
1163 }
1164
1165 if link.starts_with("/vendor") || link.starts_with("/odm") {
1166 bail!("vendor or odm file {} can't be used for VM", link.display());
1167 }
1168
1169 Ok(())
1170}
1171
1172fn check_partitions_for_files(config: &VirtualMachineRawConfig) -> Result<()> {
1173 config
1174 .disks
1175 .iter()
1176 .flat_map(|disk| disk.partitions.iter())
1177 .filter_map(|partition| partition.image.as_ref())
1178 .try_for_each(check_partition_for_file)?;
1179
1180 config.kernel.as_ref().map_or(Ok(()), check_partition_for_file)?;
1181 config.initrd.as_ref().map_or(Ok(()), check_partition_for_file)?;
1182 config.bootloader.as_ref().map_or(Ok(()), check_partition_for_file)?;
1183
1184 Ok(())
1185}
1186
Alan Stokes0d1ef782022-09-27 13:46:35 +01001187fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1188 let mut apk_zip = ZipArchive::new(apk_file)?;
1189 let config_file = apk_zip.by_name(config_path)?;
1190 Ok(serde_json::from_reader(config_file)?)
1191}
1192
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001193fn create_vm_payload_config(
1194 payload_config: &VirtualMachinePayloadConfig,
1195) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +01001196 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1197 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1198 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +00001199
1200 let payload_binary_name = &payload_config.payloadBinaryName;
1201 if payload_binary_name.contains('/') {
1202 bail!("Payload binary name must not specify a path: {payload_binary_name}");
1203 }
1204
1205 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Alan Stokesfda70842023-12-20 17:50:14 +00001206
1207 // The VM only cares about how many there are, these names are actually ignored.
1208 let extra_apk_count = payload_config.extraApks.len();
1209 let extra_apks =
1210 (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1211
Inseob Kim89b24592024-02-23 18:59:43 +09001212 Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
Alan Stokes0d1ef782022-09-27 13:46:35 +01001213}
1214
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001215/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001216fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001217 temporary_directory: &Path,
1218 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001219) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001220 let id = *next_temporary_image_id;
1221 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +00001222 CompositeImageFilenames {
1223 composite: temporary_directory.join(format!("composite-{}.img", id)),
1224 header: temporary_directory.join(format!("composite-{}-header.img", id)),
1225 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1226 }
1227}
1228
1229/// Filenames for a composite disk image, including header and footer partitions.
1230#[derive(Clone, Debug, Eq, PartialEq)]
1231struct CompositeImageFilenames {
1232 /// The composite disk image itself.
1233 composite: PathBuf,
1234 /// The header partition image.
1235 header: PathBuf,
1236 /// The footer partition image.
1237 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001238}
1239
Jiyong Park753553b2021-07-12 21:21:09 +09001240/// Checks whether the caller has a specific permission
1241fn check_permission(perm: &str) -> binder::Result<()> {
Inseob Kimecde8c02024-09-03 13:11:08 +09001242 if cfg!(early) {
1243 // Skip permission check for early VMs, in favor of SELinux
1244 return Ok(());
1245 }
David Brazdil1f530702022-10-03 12:18:10 +01001246 let calling_pid = get_calling_pid();
1247 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +09001248 // Root can do anything
1249 if calling_uid == 0 {
1250 return Ok(());
1251 }
1252 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
Frederick Mayleb2a02872024-05-08 13:35:12 -07001253 binder::wait_for_interface("permission")?;
Jiyong Park753553b2021-07-12 21:21:09 +09001254 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +00001255 Ok(())
1256 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001257 Err(anyhow!("does not have the {} permission", perm))
1258 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +00001259 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001260}
1261
Jiyong Park753553b2021-07-12 21:21:09 +09001262/// Check whether the caller of the current Binder method is allowed to manage VMs
1263fn check_manage_access() -> binder::Result<()> {
1264 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1265}
1266
Inseob Kim1119d702022-05-02 18:01:58 +09001267/// Check whether the caller of the current Binder method is allowed to create custom VMs
1268fn check_use_custom_virtual_machine() -> binder::Result<()> {
1269 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1270}
1271
Alan Stokes185fe112023-01-10 16:20:55 +00001272/// Return whether a partition is exempt from selinux label checks, because we know that it does
1273/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001274fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001275 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001276 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +00001277 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001278 || label == "microdroid-apk-idsig"
1279 || label == "payload-metadata"
1280 || label.starts_with("extra-idsig-")
1281}
1282
Alice Wangc206b9b2023-08-28 14:13:51 +00001283/// Returns whether a partition with the given label is safe for a raw config VM.
1284fn is_safe_raw_partition(label: &str) -> bool {
1285 label == "vm-instance"
1286}
1287
Alan Stokes185fe112023-01-10 16:20:55 +00001288/// Check that a file SELinux label is acceptable.
1289///
1290/// 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 +09001291/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +00001292///
1293/// Note that sepolicy must also grant read access for these types to both virtualization
1294/// service and crosvm.
1295///
1296/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1297/// user devices (W^X).
1298fn check_label_is_allowed(context: &SeContext) -> Result<()> {
1299 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001300 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001301 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +00001302 | "staging_data_file" // updated/staged APEX images
1303 | "system_file" // immutable dm-verity protected partition
1304 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +09001305 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001306 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +00001307 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +09001308 }
1309}
1310
Alan Stokes185fe112023-01-10 16:20:55 +00001311fn check_label_for_partition(partition: &Partition) -> Result<()> {
1312 let file = partition.image.as_ref().unwrap().as_ref();
1313 check_label_is_allowed(&getfilecon(file)?)
1314 .with_context(|| format!("Partition {} invalid", &partition.label))
1315}
1316
1317fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
1318 if let Some(f) = kernel {
1319 check_label_for_file(f, "kernel")?;
1320 }
1321 if let Some(f) = initrd {
1322 check_label_for_file(f, "initrd")?;
1323 }
1324 Ok(())
1325}
1326fn check_label_for_file(file: &File, name: &str) -> Result<()> {
1327 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
1328}
1329
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001330/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1331#[derive(Debug)]
1332struct VirtualMachine {
1333 instance: Arc<VmInstance>,
1334}
1335
1336impl VirtualMachine {
Devin Moore407df8f2024-08-27 19:39:16 +00001337 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +00001338 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001339 }
1340}
1341
1342impl Interface for VirtualMachine {}
1343
Devin Moore407df8f2024-08-27 19:39:16 +00001344impl IVirtualMachine::IVirtualMachine for VirtualMachine {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001345 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001346 // Don't check permission. The owner of the VM might have passed this binder object to
1347 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001348 Ok(self.instance.cid as i32)
1349 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001350
Andrew Walbran6b650662021-09-07 13:13:23 +00001351 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001352 // Don't check permission. The owner of the VM might have passed this binder object to
1353 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001354 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001355 }
1356
1357 fn registerCallback(
1358 &self,
1359 callback: &Strong<dyn IVirtualMachineCallback>,
1360 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001361 // Don't check permission. The owner of the VM might have passed this binder object to
1362 // others.
1363 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001364 // TODO: Should this give an error if the VM is already dead?
1365 self.instance.callbacks.add(callback.clone());
1366 Ok(())
1367 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001368
Andrew Walbranf8d94112021-09-07 11:45:36 +00001369 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001370 self.instance
1371 .start()
1372 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1373 .with_log()
1374 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001375 }
1376
Inseob Kima446f802022-07-11 19:46:37 +09001377 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001378 self.instance
1379 .kill()
1380 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1381 .with_log()
1382 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001383 }
1384
Keir Fraser48221ba2024-07-12 14:05:02 +00001385 fn getMemoryBalloon(&self) -> binder::Result<i64> {
1386 let balloon = self
1387 .instance
1388 .get_memory_balloon()
1389 .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1390 .with_log()
1391 .or_service_specific_exception(-1)?;
1392 Ok(balloon.try_into().unwrap())
1393 }
1394
1395 fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001396 self.instance
Keir Fraser48221ba2024-07-12 14:05:02 +00001397 .set_memory_balloon(num_bytes.try_into().unwrap())
1398 .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
Jiyong Park2227eaa2023-08-04 11:59:18 +09001399 .with_log()
1400 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001401 }
1402
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001403 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001404 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Devin Moore407df8f2024-08-27 19:39:16 +00001405 return Err(Status::new_service_specific_error_str(
1406 IVirtualMachine::ERROR_UNEXPECTED,
1407 Some("Virtual Machine is not running"),
1408 ));
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001409 }
Alan Stokes10c47672022-12-13 17:17:08 +00001410 let port = port as u32;
Devin Moore407df8f2024-08-27 19:39:16 +00001411 if port < VSOCK_PRIV_PORT_MAX {
1412 return Err(Status::new_service_specific_error_str(
1413 IVirtualMachine::ERROR_UNEXPECTED,
1414 Some("Can't connect to privileged port {port}"),
1415 ));
Alan Stokes10c47672022-12-13 17:17:08 +00001416 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001417 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1418 .context("Failed to connect")
Devin Moore407df8f2024-08-27 19:39:16 +00001419 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001420 Ok(vsock_stream_to_pfd(stream))
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001421 }
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001422
Devin Moore407df8f2024-08-27 19:39:16 +00001423 fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1424 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1425 return Err(Status::new_service_specific_error_str(
1426 IVirtualMachine::ERROR_UNEXPECTED,
1427 Some("Virtual Machine is not running"),
1428 ));
1429 }
1430 let port = port as u32;
1431 if port < VSOCK_PRIV_PORT_MAX {
1432 return Err(Status::new_service_specific_error_str(
1433 IVirtualMachine::ERROR_UNEXPECTED,
1434 Some("Can't connect to privileged port {port}"),
1435 ));
1436 }
1437 let cid = self.instance.cid;
Devin Moorec8800a12024-10-17 17:56:18 +00001438 let addr = sockaddr_vm {
1439 svm_family: AF_VSOCK as sa_family_t,
1440 svm_reserved1: 0,
1441 svm_port: port,
1442 svm_cid: cid,
1443 svm_zero: [0u8; 4],
1444 };
1445 let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
Devin Moore407df8f2024-08-27 19:39:16 +00001446 let accessor = Accessor::new(name, get_connection_info);
1447 accessor
1448 .as_binder()
1449 .context("The newly created Accessor should always have a binder")
1450 .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1451 }
1452
Yi-Yo Chiang2fbf0da2024-06-14 22:56:56 +08001453 fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1454 self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1455 }
Jiyong Park23b67392024-07-04 13:51:42 +09001456
1457 fn suspend(&self) -> binder::Result<()> {
1458 self.instance
1459 .suspend()
1460 .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1461 .with_log()
1462 .or_service_specific_exception(-1)
1463 }
1464
1465 fn resume(&self) -> binder::Result<()> {
1466 self.instance
1467 .resume()
1468 .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1469 .with_log()
1470 .or_service_specific_exception(-1)
1471 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001472}
1473
1474impl Drop for VirtualMachine {
1475 fn drop(&mut self) {
1476 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001477 if let Err(e) = self.instance.kill() {
1478 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1479 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001480 }
1481}
1482
1483/// A set of Binders to be called back in response to various events on the VM, such as when it
1484/// dies.
1485#[derive(Debug, Default)]
1486pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1487
1488impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001489 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001490 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001491 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001492 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001493 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001494 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001495 }
1496 }
1497 }
1498
Inseob Kim14cb8692021-08-31 21:50:39 +09001499 /// Call all registered callbacks to notify that the payload is ready to serve.
1500 pub fn notify_payload_ready(&self, cid: Cid) {
1501 let callbacks = &*self.0.lock().unwrap();
1502 for callback in callbacks {
1503 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001504 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001505 }
1506 }
1507 }
1508
Inseob Kim2444af92021-08-31 01:22:50 +09001509 /// Call all registered callbacks to notify that the payload has finished.
1510 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1511 let callbacks = &*self.0.lock().unwrap();
1512 for callback in callbacks {
1513 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001514 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001515 }
1516 }
1517 }
1518
Jooyung Handd0a1732021-11-23 15:26:20 +09001519 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001520 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001521 let callbacks = &*self.0.lock().unwrap();
1522 for callback in callbacks {
1523 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001524 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001525 }
1526 }
1527 }
1528
Andrew Walbrandae07162021-03-12 17:05:20 +00001529 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001530 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001531 let callbacks = &*self.0.lock().unwrap();
1532 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001533 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001534 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001535 }
1536 }
1537 }
1538
1539 /// Add a new callback to the set.
1540 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1541 self.0.lock().unwrap().push(callback);
1542 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001543}
1544
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001545/// The mutable state of the VirtualizationService. There should only be one instance of this
1546/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001547#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001548struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001549 /// The VMs which have been started. When VMs are started a weak reference is added to this
1550 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1551 /// the Binder client are dropped the weak reference here will become invalid, and will be
1552 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001553 vms: Vec<Weak<VmInstance>>,
1554}
1555
1556impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001557 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001558 fn vms(&self) -> Vec<Arc<VmInstance>> {
1559 // Attempt to upgrade the weak pointers to strong pointers.
1560 self.vms.iter().filter_map(Weak::upgrade).collect()
1561 }
1562
1563 /// Add a new VM to the list.
1564 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1565 // Garbage collect any entries from the stored list which no longer exist.
1566 self.vms.retain(|vm| vm.strong_count() > 0);
1567
1568 // Actually add the new VM.
1569 self.vms.push(vm);
1570 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001571
Jiyong Park8611a6c2021-07-09 18:17:44 +09001572 /// Get a VM that corresponds to the given cid
1573 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1574 self.vms().into_iter().find(|vm| vm.cid == cid)
1575 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001576}
1577
Andrew Walbran6b650662021-09-07 13:13:23 +00001578/// Gets the `VirtualMachineState` of the given `VmInstance`.
1579fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001580 match &*instance.vm_state.lock().unwrap() {
1581 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1582 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001583 PayloadState::Starting => VirtualMachineState::STARTING,
1584 PayloadState::Started => VirtualMachineState::STARTED,
1585 PayloadState::Ready => VirtualMachineState::READY,
1586 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001587 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001588 },
1589 VmState::Dead => VirtualMachineState::DEAD,
1590 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001591 }
1592}
1593
David Brazdilf50c7a62023-04-19 14:22:42 +00001594/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001595pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1596 file.as_ref()
1597 .try_clone()
1598 .context("Failed to clone File from ParcelFileDescriptor")
1599 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001600 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001601}
1602
Andrew Walbrand3a84182021-09-07 14:48:52 +00001603/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001604fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001605 file.as_ref().map(clone_file).transpose()
1606}
1607
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001608/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
Jiyong Parkaf63d1c2024-09-04 16:15:42 +09001609fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1610 // SAFETY: ownership is transferred from stream to f
1611 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1612 ParcelFileDescriptor::new(f)
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001613}
1614
Jiyong Parkdcf17412022-02-08 15:07:23 +09001615/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001616fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1617 VersionReq::parse(s)
1618 .with_context(|| format!("Invalid platform version requirement {}", s))
1619 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001620}
1621
Jiyong Parked180932023-02-24 19:55:41 +09001622/// Create the empty ramdump file
1623fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1624 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1625 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1626 // owner) for readout.
1627 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001628 let ramdump = File::create(ramdump_path)
1629 .context("Failed to prepare ramdump file")
1630 .with_log()
1631 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001632 Ok(ramdump)
1633}
1634
Nikita Ioffe5776f082023-02-10 21:38:26 +00001635fn is_protected(config: &VirtualMachineConfig) -> bool {
1636 match config {
1637 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1638 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1639 }
1640}
1641
1642fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1643 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001644 return Err(anyhow!("Can't use gdb with protected VMs"))
1645 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001646 }
1647
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001648 if get_debug_level(config) == Some(DebugLevel::NONE) {
1649 return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1650 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001651 }
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +01001652
1653 Ok(())
Nikita Ioffe5776f082023-02-10 21:38:26 +00001654}
1655
Shikha Panwar61a74b52024-02-16 13:17:01 +00001656fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
1657 match config {
1658 VirtualMachineConfig::RawConfig(config) => config.instanceId,
1659 VirtualMachineConfig::AppConfig(config) => config.instanceId,
1660 }
1661}
1662
Alan Stokesc96b35e2024-05-03 13:21:20 +01001663fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
1664 match config {
1665 VirtualMachineConfig::RawConfig(_) => true,
1666 VirtualMachineConfig::AppConfig(config) => {
1667 let Some(custom) = &config.customConfig else { return true };
1668 custom.wantUpdatable
1669 }
1670 }
1671}
1672
Nikita Ioffe5776f082023-02-10 21:38:26 +00001673fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1674 match config {
1675 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001676 VirtualMachineConfig::AppConfig(config) => {
1677 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1678 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001679 }
1680}
1681
Nikita Ioffe631717e2023-09-05 13:38:07 +01001682fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1683 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1684 if let Some(custom_config) = &config.customConfig {
1685 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1686 return Err(anyhow!("vendor modules feature is disabled"))
1687 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1688 }
1689 }
1690 Ok(())
1691}
1692
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001693fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1694 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1695 if let Some(custom_config) = &config.customConfig {
1696 if !custom_config.devices.is_empty() {
1697 return Err(anyhow!("device assignment feature is disabled"))
1698 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1699 }
1700 }
1701 Ok(())
1702}
1703
Alan Stokesfda70842023-12-20 17:50:14 +00001704fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
1705 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1706 let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
1707 if !payload_config.extraApks.is_empty() {
1708 return Err(anyhow!("multi-tenant feature is disabled"))
1709 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1710 }
1711 Ok(())
1712}
1713
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001714fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
1715 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1716 if let Some(custom_config) = &config.customConfig {
1717 if !custom_config.extraKernelCmdlineParams.is_empty() {
1718 return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
1719 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1720 }
1721 }
1722 Ok(())
1723}
1724
Nikita Ioffef934e812024-07-05 15:44:41 +00001725fn check_protected_vm_is_supported() -> binder::Result<()> {
1726 let is_pvm_supported =
1727 hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
1728 if is_pvm_supported {
1729 Ok(())
1730 } else {
1731 Err(anyhow!("pVM is not supported"))
1732 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
1733 }
1734}
1735
Nikita Ioffe631717e2023-09-05 13:38:07 +01001736fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1737 if !cfg!(vendor_modules) {
1738 check_no_vendor_modules(config)?;
1739 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001740 if !cfg!(device_assignment) {
1741 check_no_devices(config)?;
1742 }
Alan Stokesfda70842023-12-20 17:50:14 +00001743 if !cfg!(multi_tenant) {
1744 check_no_extra_apks(config)?;
1745 }
Nikita Ioffeb4268b32024-09-03 10:23:14 +00001746 if !cfg!(debuggable_vms_improvements) {
1747 check_no_extra_kernel_cmdline_params(config)?;
1748 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001749 Ok(())
1750}
1751
Inseob Kimecde8c02024-09-03 13:11:08 +09001752fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
1753 check_no_vendor_modules(config)?;
1754 check_no_devices(config)?;
1755
1756 Ok(())
1757}
1758
Inseob Kim0168b462022-12-27 14:54:35 +09001759fn clone_or_prepare_logger_fd(
Inseob Kim0168b462022-12-27 14:54:35 +09001760 fd: Option<&ParcelFileDescriptor>,
1761 tag: String,
1762) -> Result<Option<File>, Status> {
1763 if let Some(fd) = fd {
1764 return Ok(Some(clone_file(fd)?));
1765 }
1766
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001767 let (read_fd, write_fd) =
Jiyong Park2227eaa2023-08-04 11:59:18 +09001768 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001769
Frederick Maylefbbcfcd2024-04-08 16:31:54 -07001770 let mut reader = BufReader::new(File::from(read_fd));
1771 let write_fd = File::from(write_fd);
Inseob Kim0168b462022-12-27 14:54:35 +09001772
1773 std::thread::spawn(move || loop {
1774 let mut buf = vec![];
1775 match reader.read_until(b'\n', &mut buf) {
1776 Ok(0) => {
1777 // EOF
1778 return;
1779 }
1780 Ok(size) => {
1781 if buf[size - 1] == b'\n' {
1782 buf.pop();
1783 }
1784 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1785 }
1786 Err(e) => {
1787 error!("Could not read console pipe: {:?}", e);
1788 return;
1789 }
1790 };
1791 });
1792
1793 Ok(Some(write_fd))
1794}
1795
Jooyung Han35edb8f2021-07-01 16:17:16 +09001796/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1797/// it doesn't require that T implements Clone.
1798enum BorrowedOrOwned<'a, T> {
1799 Borrowed(&'a T),
1800 Owned(T),
1801}
1802
1803impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1804 fn as_ref(&self) -> &T {
1805 match self {
1806 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001807 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001808 }
1809 }
1810}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001811
1812/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1813#[derive(Debug, Default)]
1814struct VirtualMachineService {
1815 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001816 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001817}
1818
1819impl Interface for VirtualMachineService {}
1820
1821impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001822 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1823 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001824 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001825 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001826 vm.update_payload_state(PayloadState::Started)
1827 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001828 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001829
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001830 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1831 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001832 Ok(())
1833 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001834 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001835 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001836 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001837 }
Inseob Kim2444af92021-08-31 01:22:50 +09001838
Inseob Kimc7d28c72021-10-25 14:28:10 +00001839 fn notifyPayloadReady(&self) -> binder::Result<()> {
1840 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001841 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001842 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001843 vm.update_payload_state(PayloadState::Ready)
1844 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001845 vm.callbacks.notify_payload_ready(cid);
1846 Ok(())
1847 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001848 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001849 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001850 }
1851 }
1852
Inseob Kimc7d28c72021-10-25 14:28:10 +00001853 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1854 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001855 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001856 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001857 vm.update_payload_state(PayloadState::Finished)
1858 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001859 vm.callbacks.notify_payload_finished(cid, exit_code);
1860 Ok(())
1861 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001862 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001863 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001864 }
1865 }
1866
Alan Stokes2bead0d2022-09-05 16:58:34 +01001867 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001868 let cid = self.cid;
1869 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001870 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001871 vm.update_payload_state(PayloadState::Finished)
1872 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001873 vm.callbacks.notify_error(cid, error_code, message);
1874 Ok(())
1875 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001876 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001877 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001878 }
1879 }
Alice Wangc2fec932023-02-23 16:24:02 +00001880
Shikha Panware45e9422024-02-28 21:18:10 +00001881 fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
1882 if !is_secretkeeper_supported() {
1883 return Err(StatusCode::NAME_NOT_FOUND)?;
1884 }
1885 let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1886 Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001887 }
1888
Alice Wange64dd182024-01-17 15:57:55 +00001889 fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
1890 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
Alice Wangc2fec932023-02-23 16:24:02 +00001891 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001892}
1893
Shikha Panwar8707f0f2024-02-28 20:40:42 +00001894fn is_secretkeeper_supported() -> bool {
Shikha Panwar81d13d32024-03-10 19:39:23 +00001895 binder::is_declared(SECRETKEEPER_IDENTIFIER)
1896 .expect("Could not check for declared Secretkeeper interface")
Shikha Panwar8187ca22024-01-04 08:33:08 +00001897}
1898
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001899impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001900 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001901 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001902 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001903 BinderFeatures::default(),
1904 )
1905 }
1906}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001907
Stephen Hines4c1e2fc2024-02-09 16:34:47 -08001908struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
1909
1910impl Interface for SecretkeeperProxy {}
1911
1912impl ISecretkeeper for SecretkeeperProxy {
1913 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
1914 // Pass the request to the channel, and read the response.
1915 self.0.processSecretManagementRequest(req)
1916 }
1917
1918 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
1919 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
1920 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
1921 }
1922
1923 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
1924 self.0.deleteIds(ids)
1925 }
1926
1927 fn deleteAll(&self) -> binder::Result<()> {
1928 self.0.deleteAll()
1929 }
1930}
1931
1932struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
1933
1934impl Interface for AuthGraphKeyExchangeProxy {}
1935
1936impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
1937 fn create(&self) -> binder::Result<SessionInitiationInfo> {
1938 self.0.create()
1939 }
1940
1941 fn init(
1942 &self,
1943 peer_pub_key: &PubKey,
1944 peer_id: &Identity,
1945 peer_nonce: &[u8],
1946 peer_version: i32,
1947 ) -> binder::Result<KeInitResult> {
1948 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
1949 }
1950
1951 fn finish(
1952 &self,
1953 peer_pub_key: &PubKey,
1954 peer_id: &Identity,
1955 peer_signature: &SessionIdSignature,
1956 peer_nonce: &[u8],
1957 peer_version: i32,
1958 own_key: &Key,
1959 ) -> binder::Result<SessionInfo> {
1960 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
1961 }
1962
1963 fn authenticationComplete(
1964 &self,
1965 peer_signature: &SessionIdSignature,
1966 shared_keys: &[AuthgraphArc; 2],
1967 ) -> binder::Result<[AuthgraphArc; 2]> {
1968 self.0.authenticationComplete(peer_signature, shared_keys)
1969 }
1970}
1971
Inseob Kimecde8c02024-09-03 13:11:08 +09001972// KEEP IN SYNC WITH early_vms.xsd
1973#[derive(Debug, Deserialize, PartialEq)]
1974struct EarlyVm {
1975 #[allow(dead_code)]
1976 name: String,
1977 #[allow(dead_code)]
1978 cid: i32,
1979 #[allow(dead_code)]
1980 path: String,
1981}
1982
1983#[derive(Debug, Default, Deserialize)]
1984struct EarlyVms {
1985 #[allow(dead_code)]
1986 early_vm: Vec<EarlyVm>,
1987}
1988
1989fn range_for_partition(partition: &str) -> Result<Range<Cid>> {
1990 match partition {
1991 "system" => Ok(100..200),
1992 "system_ext" | "product" => Ok(200..300),
1993 _ => Err(anyhow!("Early VMs are not supported for {partition}")),
1994 }
1995}
1996
1997fn find_early_vm(xml_path: &Path, cid_range: &Range<Cid>, name: &str) -> Result<EarlyVm> {
1998 if !xml_path.exists() {
1999 bail!("{} doesn't exist", xml_path.display());
2000 }
2001
2002 let xml =
2003 fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2004 let xml = String::from_utf8(xml)
2005 .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2006 let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2007 .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2008
2009 let mut found_vm: Option<EarlyVm> = None;
2010
2011 for early_vm in early_vms.early_vm {
2012 if early_vm.name != name {
2013 continue;
2014 }
2015
2016 let cid = early_vm
2017 .cid
2018 .try_into()
2019 .with_context(|| format!("Invalid CID value {}", early_vm.cid))?;
2020
2021 if !cid_range.contains(&cid) {
2022 bail!("VM '{}' uses CID {cid} which is out of range. Available CIDs for '{}': {cid_range:?}", xml_path.display(), early_vm.name);
2023 }
2024
2025 if found_vm.is_some() {
2026 bail!("Multiple VMs named {name} are found in {}", xml_path.display());
2027 }
2028
2029 found_vm = Some(early_vm);
2030 }
2031
2032 found_vm.ok_or_else(|| anyhow!("Can't find {name} in {}", xml_path.display()))
2033}
2034
2035fn find_early_vm_for_partition(partition: &str, name: &str) -> Result<EarlyVm> {
2036 let cid_range = range_for_partition(partition)?;
2037 find_early_vm(Path::new(&format!("/{partition}/etc/avf/early_vms.xml")), &cid_range, name)
2038}
2039
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002040#[cfg(test)]
2041mod tests {
2042 use super::*;
2043
2044 #[test]
2045 fn test_is_allowed_label_for_partition() -> Result<()> {
2046 let expected_results = vec![
2047 ("u:object_r:system_file:s0", true),
2048 ("u:object_r:apk_data_file:s0", true),
2049 ("u:object_r:app_data_file:s0", false),
2050 ("u:object_r:app_data_file:s0:c512,c768", false),
2051 ("u:object_r:privapp_data_file:s0:c512,c768", false),
2052 ("invalid", false),
2053 ("user:role:apk_data_file:severity:categories", true),
2054 ("user:role:apk_data_file:severity:categories:extraneous", false),
2055 ];
2056
2057 for (label, expected_valid) in expected_results {
2058 let context = SeContext::new(label)?;
2059 let result = check_label_is_allowed(&context);
2060 if expected_valid {
2061 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
2062 } else if result.is_ok() {
2063 bail!("Expected label {} to be disallowed", label);
2064 }
2065 }
2066 Ok(())
2067 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00002068
2069 #[test]
2070 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2071 let apk = tempfile::tempfile().unwrap();
2072 let idsig = tempfile::tempfile().unwrap();
2073
2074 let ret = create_or_update_idsig_file(
2075 &ParcelFileDescriptor::new(apk),
2076 &ParcelFileDescriptor::new(idsig),
2077 );
2078 assert!(ret.is_err(), "should fail");
2079 Ok(())
2080 }
2081
2082 #[test]
2083 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2084 let tmp_dir = tempfile::TempDir::new().unwrap();
2085 let apk = File::open(tmp_dir.path()).unwrap();
2086 let idsig = tempfile::tempfile().unwrap();
2087
2088 let ret = create_or_update_idsig_file(
2089 &ParcelFileDescriptor::new(apk),
2090 &ParcelFileDescriptor::new(idsig),
2091 );
2092 assert!(ret.is_err(), "should fail");
2093 Ok(())
2094 }
2095
2096 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2097 /// on ext4 filesystem is passed.
2098 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2099 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2100 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2101 #[test]
2102 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2103 // APEXes are backed by the ext4.
2104 let apk = File::open("/apex/com.android.virt/").unwrap();
2105 let idsig = tempfile::tempfile().unwrap();
2106
2107 let ret = create_or_update_idsig_file(
2108 &ParcelFileDescriptor::new(apk),
2109 &ParcelFileDescriptor::new(idsig),
2110 );
2111 assert!(ret.is_err(), "should fail");
2112 Ok(())
2113 }
Jiyong Park8d192952023-06-26 14:29:51 +09002114
2115 #[test]
2116 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2117 use std::io::Seek;
2118
2119 // Pick any APK
2120 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2121 let mut idsig = tempfile::tempfile().unwrap();
2122
2123 create_or_update_idsig_file(
2124 &ParcelFileDescriptor::new(apk.try_clone()?),
2125 &ParcelFileDescriptor::new(idsig.try_clone()?),
2126 )?;
2127 let modified_orig = idsig.metadata()?.modified()?;
2128 apk.rewind()?;
2129 idsig.rewind()?;
2130
2131 // Call the function again
2132 create_or_update_idsig_file(
2133 &ParcelFileDescriptor::new(apk.try_clone()?),
2134 &ParcelFileDescriptor::new(idsig.try_clone()?),
2135 )?;
2136 let modified_new = idsig.metadata()?.modified()?;
2137 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2138 Ok(())
2139 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002140
2141 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00002142 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2143 use std::io::Read;
2144
2145 // Pick any APK
2146 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2147 let idsig_empty = tempfile::tempfile().unwrap();
2148 let mut idsig_invalid = tempfile::tempfile().unwrap();
2149 idsig_invalid.write_all(b"Oops")?;
2150
2151 // Create new idsig
2152 create_or_update_idsig_file(
2153 &ParcelFileDescriptor::new(apk.try_clone()?),
2154 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2155 )?;
2156 apk.rewind()?;
2157
2158 // Update idsig_invalid
2159 create_or_update_idsig_file(
2160 &ParcelFileDescriptor::new(apk.try_clone()?),
2161 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2162 )?;
2163
2164 // Ensure the 2 idsig files have same size!
2165 assert!(
2166 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2167 "idsig files differ in size"
2168 );
2169 // Ensure the 2 idsig files have same content!
2170 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2171 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2172 }
2173 Ok(())
2174 }
2175 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01002176 fn test_append_kernel_param_first_param() {
2177 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2178 append_kernel_param("foo=1", &mut vm_config);
2179 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2180 }
2181
2182 #[test]
2183 fn test_append_kernel_param() {
2184 let mut vm_config =
2185 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2186 append_kernel_param("bar=42", &mut vm_config);
2187 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2188 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09002189
Inseob Kim46257382024-01-03 15:41:22 +09002190 fn test_extract_os_name_from_config_path(
2191 path: &Path,
2192 expected_result: Option<&str>,
2193 ) -> Result<()> {
2194 let result = extract_os_name_from_config_path(path);
2195 if result.as_deref() != expected_result {
2196 bail!("Expected {:?} but was {:?}", expected_result, &result)
2197 }
2198 Ok(())
2199 }
2200
2201 #[test]
2202 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2203 test_extract_os_name_from_config_path(
2204 Path::new("/apex/com.android.virt/etc/microdroid.json"),
2205 Some("microdroid"),
2206 )
2207 }
2208
2209 #[test]
2210 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2211 test_extract_os_name_from_config_path(
2212 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2213 Some("microdroid_gki-android14-6.1"),
2214 )
2215 }
2216
2217 #[test]
2218 fn test_extract_os_name_from_invalid_path() -> Result<()> {
2219 test_extract_os_name_from_config_path(
2220 Path::new("/apex/com.android.virt/etc/microdroid.img"),
2221 None,
2222 )
2223 }
2224
2225 #[test]
2226 fn test_extract_os_name_from_configs() -> Result<()> {
2227 let tmp_dir = tempfile::TempDir::new()?;
2228 let tmp_dir_path = tmp_dir.path().to_owned();
2229
2230 let mut os_names: HashSet<String> = HashSet::new();
2231 os_names.insert("microdroid".to_owned());
2232 os_names.insert("microdroid_gki-android14-6.1".to_owned());
2233 os_names.insert("microdroid_gki-android15-6.1".to_owned());
2234
2235 // config files
2236 for os_name in &os_names {
2237 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2238 }
2239
2240 // fake files not related to configs
2241 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2242 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2243
2244 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2245 Some(s) => s.to_owned(),
2246 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2247 };
2248
2249 let result = extract_os_names_from_configs(&glob_pattern)?;
2250 if result != os_names {
2251 bail!("Expected {:?} but was {:?}", os_names, result);
2252 }
2253 Ok(())
2254 }
Inseob Kimecde8c02024-09-03 13:11:08 +09002255
2256 #[test]
2257 fn test_find_early_vms_from_xml() -> Result<()> {
2258 let tmp_dir = tempfile::TempDir::new()?;
2259 let tmp_dir_path = tmp_dir.path().to_owned();
2260 let xml_path = tmp_dir_path.join("early_vms.xml");
2261
2262 std::fs::write(
2263 &xml_path,
2264 br#"<?xml version="1.0" encoding="utf-8"?>
2265 <early_vms>
2266 <early_vm>
2267 <name>vm_demo_native_early</name>
2268 <cid>123</cid>
2269 <path>/system/bin/vm_demo_native_early</path>
2270 </early_vm>
2271 <early_vm>
2272 <name>vm_demo_duplicated_name</name>
2273 <cid>456</cid>
2274 <path>/system/bin/vm_demo_duplicated_name_1</path>
2275 </early_vm>
2276 <early_vm>
2277 <name>vm_demo_duplicated_name</name>
2278 <cid>789</cid>
2279 <path>/system/bin/vm_demo_duplicated_name_2</path>
2280 </early_vm>
2281 <early_vm>
2282 <name>vm_demo_invalid_cid_1</name>
2283 <cid>-1</cid>
2284 <path>/system/bin/vm_demo_invalid_cid_1</path>
2285 </early_vm>
2286 <early_vm>
2287 <name>vm_demo_invalid_cid_2</name>
2288 <cid>999999</cid>
2289 <path>/system/bin/vm_demo_invalid_cid_2</path>
2290 </early_vm>
2291 </early_vms>
2292 "#,
2293 )?;
2294
2295 let cid_range = 100..1000;
2296
2297 let result = find_early_vm(&xml_path, &cid_range, "vm_demo_native_early")?;
2298 let expected = EarlyVm {
2299 name: "vm_demo_native_early".to_owned(),
2300 cid: 123,
2301 path: "/system/bin/vm_demo_native_early".to_owned(),
2302 };
2303 assert_eq!(result, expected);
2304
2305 assert!(
2306 find_early_vm(&xml_path, &cid_range, "vm_demo_duplicated_name").is_err(),
2307 "should fail"
2308 );
2309 assert!(
2310 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_1").is_err(),
2311 "should fail"
2312 );
2313 assert!(
2314 find_early_vm(&xml_path, &cid_range, "vm_demo_invalid_cid_2").is_err(),
2315 "should fail"
2316 );
2317
2318 Ok(())
2319 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01002320}