blob: f5f2718ca017c6d6d558b746c08eb83e864cde4b [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
David Brazdil1f530702022-10-03 12:18:10 +010017use crate::{get_calling_pid, get_calling_uid};
David Brazdil49f96f52022-12-16 21:29:13 +000018use crate::atom::{
David Brazdil49f96f52022-12-16 21:29:13 +000019 write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000020use crate::composite::make_composite_image;
David Brazdil8cf8f482022-11-23 14:21:26 +000021use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState};
Jaewan Kim61f86142023-03-28 15:12:52 +090022use crate::debug_config::DebugConfig;
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::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000027 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000028 ErrorCode::ErrorCode,
29};
30use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090031 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000032 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000033 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010034 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000035 IVirtualMachineCallback::IVirtualMachineCallback,
36 IVirtualizationService::IVirtualizationService,
Keir Frasercdd4b112022-11-24 14:02:25 +000037 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090038 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000039 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090040 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090041 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000042 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010043 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090044 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000045 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090046};
David Brazdilafc9a9e2023-01-12 16:08:10 +000047use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090048use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000049 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090050};
Alan Stokes25f69362023-03-06 16:51:54 +000051use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090052use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090053use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010054use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000055 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
56 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090057 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000058};
David Brazdilf50c7a62023-04-19 14:22:42 +000059use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000060use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000061use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090062use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090063use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000064use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000065use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090066use semver::VersionReq;
Inseob Kim6ef80972023-07-20 17:23:36 +090067use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000068use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000069use std::ffi::CStr;
Inseob Kim6ef80972023-07-20 17:23:36 +090070use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000071use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000072use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000073use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000074use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000075use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000076use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000077use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000078use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090079use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000080
David Brazdil41d1a872022-10-05 14:44:19 +010081/// The unique ID of a VM used (together with a port number) for vsock communication.
82pub type Cid = u32;
83
David Brazdil4b4c5102022-12-19 22:56:20 +000084pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
85
Jooyung Han95884632021-07-06 22:27:54 +090086/// The size of zero.img.
87/// Gaps in composite disk images are filled with a shared zero.img.
88const ZERO_FILLER_SIZE: u64 = 4096;
89
David Brazdilf50c7a62023-04-19 14:22:42 +000090/// Magic string for the instance image
91const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
92
93/// Version of the instance image format
94const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
95
Alan Stokes0d1ef782022-09-27 13:46:35 +010096const MICRODROID_OS_NAME: &str = "microdroid";
97
David Brazdilf50c7a62023-04-19 14:22:42 +000098const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
99
100/// crosvm requires all partitions to be a multiple of 4KiB.
101const PARTITION_GRANULARITY_BYTES: u64 = 4096;
102
David Brazdil49f96f52022-12-16 21:29:13 +0000103lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000104 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
105 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
106 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000107}
108
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000109fn create_or_update_idsig_file(
110 input_fd: &ParcelFileDescriptor,
111 idsig_fd: &ParcelFileDescriptor,
112) -> Result<()> {
113 let mut input = clone_file(input_fd)?;
114 let metadata = input.metadata().context("failed to get input metadata")?;
115 if !metadata.is_file() {
116 bail!("input is not a regular file");
117 }
Alan Stokes25f69362023-03-06 16:51:54 +0000118 let mut sig =
119 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
120 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000121
122 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900123
124 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
125 // if the idsig file already has the same APK digest.
126 if output.metadata()?.len() > 0 {
127 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
128 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
129 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
130 return Ok(());
131 }
132 }
133 // if we fail to read v4signature from output, that's fine. User can pass a random file.
134 // We will anyway overwrite the file to the v4signature generated from input_fd.
135 }
136
Nikita Ioffec09b0492022-12-14 20:18:33 +0000137 output.set_len(0).context("failed to set_len on the idsig output")?;
138 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000139 Ok(())
140}
141
Alan Stokes25f69362023-03-06 16:51:54 +0000142fn get_current_sdk() -> Result<u32> {
143 let current_sdk = system_properties::read("ro.build.version.sdk")?;
144 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
145 current_sdk.parse().context("Malformed SDK version")
146}
147
David Brazdil4b4c5102022-12-19 22:56:20 +0000148pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
149 for dir_entry in read_dir(path)? {
150 remove_file(dir_entry?.path())?;
151 }
152 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100153}
154
David Brazdil528e0472022-10-10 15:06:02 +0100155/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000156#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000157pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900158 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000159}
160
Shikha Panward8e35422021-10-11 13:51:27 +0000161impl Interface for VirtualizationService {
162 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
163 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
164 let state = &mut *self.state.lock().unwrap();
165 let vms = state.vms();
166 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
167 for vm in vms {
168 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
169 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
170 .or(Err(StatusCode::UNKNOWN_ERROR))?;
171 writeln!(file, "\tPayload state {:?}", vm.payload_state())
172 .or(Err(StatusCode::UNKNOWN_ERROR))?;
173 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
174 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
175 .or(Err(StatusCode::UNKNOWN_ERROR))?;
176 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
177 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000178 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
179 .or(Err(StatusCode::UNKNOWN_ERROR))?;
180 }
181 Ok(())
182 }
183}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000184impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000185 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
186 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000187 ///
188 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000189 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000190 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000191 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900192 console_out_fd: Option<&ParcelFileDescriptor>,
193 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000194 log_fd: Option<&ParcelFileDescriptor>,
195 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000196 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900197 let ret = self.create_vm_internal(
198 config,
199 console_out_fd,
200 console_in_fd,
201 log_fd,
202 &mut is_protected,
203 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000204 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000205 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000206 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000207
Andrew Walbrandff3b942021-06-09 15:20:36 +0000208 /// Initialise an empty partition image of the given size to be used as a writable partition.
209 fn initializeWritablePartition(
210 &self,
211 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000212 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900213 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000214 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900215 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900216 let size_bytes = size_bytes
217 .try_into()
218 .with_context(|| format!("Invalid size: {}", size_bytes))
219 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000220 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
221 let image = clone_file(image_fd)?;
222 // initialize the file. Any data in the file will be erased.
Jiyong Park2227eaa2023-08-04 11:59:18 +0900223 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
224 let mut part = QcowFile::new(image, size_bytes)
225 .context("Failed to create QCOW2 image")
226 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000227
228 match partition_type {
229 PartitionType::RAW => Ok(()),
230 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
231 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
232 _ => Err(Error::new(
233 ErrorKind::Unsupported,
234 format!("Unsupported partition type {:?}", partition_type),
235 )),
236 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900237 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
238 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000239
240 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000241 }
242
Jiyong Park0a248432021-08-20 23:32:39 +0900243 /// Creates or update the idsig file by digesting the input APK file.
244 fn createOrUpdateIdsigFile(
245 &self,
246 input_fd: &ParcelFileDescriptor,
247 idsig_fd: &ParcelFileDescriptor,
248 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900249 check_manage_access()?;
250
Jiyong Park2227eaa2023-08-04 11:59:18 +0900251 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900252 Ok(())
253 }
254
Andrew Walbran320b5602021-03-04 16:11:12 +0000255 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
256 /// and as such is only permitted from the shell user.
257 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000258 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000259 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000260 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900261
262 /// Get a list of assignable device types.
263 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
264 // Delegate to the global service, including checking the permission.
265 GLOBAL_SERVICE.getAssignableDevices()
266 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000267}
268
Jiyong Park8611a6c2021-07-09 18:17:44 +0900269impl VirtualizationService {
270 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000271 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900272 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000273
David Brazdil209074a2023-01-12 16:44:51 +0000274 fn create_vm_context(
275 &self,
276 requester_debug_pid: pid_t,
277 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000278 const NUM_ATTEMPTS: usize = 5;
279
280 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000281 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000282 let cid = vm_context.getCid()? as Cid;
283 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000284 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
285
286 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000287 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000288 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000289 Ok(vm_server) => {
290 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000291 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000292 }
293 Err(err) => {
294 warn!("Could not start RpcServer on port {}: {}", port, err);
295 }
296 }
297 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900298 Err(anyhow!("Too many attempts to create VM context failed"))
299 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000300 }
301
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000302 fn create_vm_internal(
303 &self,
304 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900305 console_out_fd: Option<&ParcelFileDescriptor>,
306 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000307 log_fd: Option<&ParcelFileDescriptor>,
308 is_protected: &mut bool,
309 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000310 let requester_uid = get_calling_uid();
311 let requester_debug_pid = get_calling_pid();
312
313 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
314 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900315
Alan Stokes7bc146c2022-10-20 17:10:32 +0100316 let is_custom = match config {
317 VirtualMachineConfig::RawConfig(_) => true,
318 VirtualMachineConfig::AppConfig(config) => {
319 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100320 // VirtualMachineAppConfig. Almost all of these features are grouped in the
321 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100322 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100323 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100324 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900325 // - using anything other than the default kernel;
326 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100327 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900328 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100329 };
330 if is_custom {
331 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900332 }
333
Nikita Ioffe5776f082023-02-10 21:38:26 +0000334 let gdb_port = extract_gdb_port(config);
335
336 // Additional permission checks if caller request gdb.
337 if gdb_port.is_some() {
338 check_gdb_allowed(config)?;
339 }
340
Jaewan Kim61f86142023-03-28 15:12:52 +0900341 let debug_level = match config {
342 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
343 _ => DebugLevel::NONE,
344 };
345 let debug_config = DebugConfig::new(debug_level);
346
347 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900348 Some(prepare_ramdump_file(&temporary_directory)?)
349 } else {
350 None
351 };
352
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000353 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900354 let console_out_fd =
355 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
356 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900357 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000358
359 // Counter to generate unique IDs for temporary image files.
360 let mut next_temporary_image_id = 0;
361 // Files which are referred to from composite images. These must be mapped to the crosvm
362 // child process, and not closed before it is started.
363 let mut indirect_files = vec![];
364
Alan Stokes7bc146c2022-10-20 17:10:32 +0100365 let (is_app_config, config) = match config {
366 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
367 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900368 let config = load_app_config(config, &debug_config, &temporary_directory)
369 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900370 *is_protected = config.protectedVm;
371 let message = format!("Failed to load app config: {:?}", e);
372 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900373 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900374 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100375 (true, BorrowedOrOwned::Owned(config))
376 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000377 };
378 let config = config.as_ref();
379 *is_protected = config.protectedVm;
380
381 // Check if partition images are labeled incorrectly. This is to prevent random images
382 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alice Wangc206b9b2023-08-28 14:13:51 +0000383 // being loaded in a pVM. This applies to everything but the instance image in the raw config,
384 // and everything but the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000385 config
386 .disks
387 .iter()
388 .flat_map(|disk| disk.partitions.iter())
389 .filter(|partition| {
390 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100391 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000392 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000393 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000394 }
395 })
396 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900397 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000398
Alan Stokes185fe112023-01-10 16:20:55 +0000399 let kernel = maybe_clone_file(&config.kernel)?;
400 let initrd = maybe_clone_file(&config.initrd)?;
401
402 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
403 if config.protectedVm {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900404 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Alan Stokes185fe112023-01-10 16:20:55 +0000405 }
406
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000407 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900408 write_zero_filler(&zero_filler_path)
409 .context("Failed to make composite image")
410 .with_log()
411 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000412
413 // Assemble disk images if needed.
414 let disks = config
415 .disks
416 .iter()
417 .map(|disk| {
418 assemble_disk_image(
419 disk,
420 &zero_filler_path,
421 &temporary_directory,
422 &mut next_temporary_image_id,
423 &mut indirect_files,
424 )
425 })
426 .collect::<Result<Vec<DiskFile>, _>>()?;
427
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000428 let (cpus, host_cpu_topology) = match config.cpuTopology {
429 CpuTopology::MATCH_HOST => (None, true),
430 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
431 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900432 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
433 .with_log()
434 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000435 }
436 };
437
Inseob Kim6ef80972023-07-20 17:23:36 +0900438 let devices_dtbo = if !config.devices.is_empty() {
439 let mut set = HashSet::new();
440 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900441 let path = canonicalize(device)
442 .with_context(|| format!("can't canonicalize {device}"))
443 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900444 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900445 return Err(anyhow!("duplicated device {device}"))
446 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900447 }
448 }
Inseob Kimf36347b2023-08-03 12:52:48 +0900449 let dtbo_path = temporary_directory.join("dtbo");
450 // open a writable file descriptor for vfio_handler
451 let dtbo = File::create(&dtbo_path).map_err(|e| {
452 error!("Failed to create VM DTBO file {dtbo_path:?}: {e:?}");
453 Status::new_service_specific_error_str(
454 -1,
455 Some(format!("Failed to create VM DTBO file {dtbo_path:?}: {e:?}")),
456 )
457 })?;
458 GLOBAL_SERVICE
459 .bindDevicesToVfioDriver(&config.devices, &ParcelFileDescriptor::new(dtbo))?;
460
461 // open (again) a readable file descriptor for crosvm
462 let dtbo = File::open(&dtbo_path).map_err(|e| {
463 error!("Failed to open VM DTBO file {dtbo_path:?}: {e:?}");
464 Status::new_service_specific_error_str(
465 -1,
466 Some(format!("Failed to open VM DTBO file {dtbo_path:?}: {e:?}")),
467 )
468 })?;
469 Some(dtbo)
Inseob Kim6ef80972023-07-20 17:23:36 +0900470 } else {
471 None
472 };
473
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000474 // Actually start the VM.
475 let crosvm_config = CrosvmConfig {
476 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000477 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000478 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000479 kernel,
480 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000481 disks,
482 params: config.params.to_owned(),
483 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900484 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000485 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000486 cpus,
487 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900488 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900489 console_out_fd,
490 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000491 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900492 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000493 indirect_files,
494 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900495 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000496 gdb_port,
Inseob Kim6ef80972023-07-20 17:23:36 +0900497 vfio_devices: config.devices.iter().map(PathBuf::from).collect(),
498 devices_dtbo,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000499 };
500 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100501 VmInstance::new(
502 crosvm_config,
503 temporary_directory,
504 requester_uid,
505 requester_debug_pid,
506 vm_context,
507 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900508 .with_context(|| format!("Failed to create VM with config {:?}", config))
509 .with_log()
510 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000511 );
512 state.add_vm(Arc::downgrade(&instance));
513 Ok(VirtualMachine::create(instance))
514 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900515}
516
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000517fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900518 let file = OpenOptions::new()
519 .create_new(true)
520 .read(true)
521 .write(true)
522 .open(zero_filler_path)
523 .with_context(|| "Failed to create zero.img")?;
524 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000525 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900526}
527
David Brazdilf50c7a62023-04-19 14:22:42 +0000528fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
529 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
530 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
531 part.flush()
532}
533
534fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
535 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
536 part.flush()
537}
538
539fn round_up(input: u64, granularity: u64) -> u64 {
540 if granularity == 0 {
541 return input;
542 }
543 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
544 let result = input.checked_add(granularity - 1).unwrap_or(input);
545 (result / granularity) * granularity
546}
547
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000548/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
549///
550/// This may involve assembling a composite disk from a set of partition images.
551fn assemble_disk_image(
552 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900553 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000554 temporary_directory: &Path,
555 next_temporary_image_id: &mut u64,
556 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000557) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000558 let image = if !disk.partitions.is_empty() {
559 if disk.image.is_some() {
560 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900561 return Err(anyhow!("DiskImage contains both image and partitions"))
562 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000563 }
564
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000565 let composite_image_filenames =
566 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
567 let (image, partition_files) = make_composite_image(
568 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900569 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000570 &composite_image_filenames.composite,
571 &composite_image_filenames.header,
572 &composite_image_filenames.footer,
573 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900574 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
575 .with_log()
576 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000577
578 // Pass the file descriptors for the various partition files to crosvm when it
579 // is run.
580 indirect_files.extend(partition_files);
581
582 image
583 } else if let Some(image) = &disk.image {
584 clone_file(image)?
585 } else {
586 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900587 return Err(anyhow!("DiskImage didn't contain image or partitions."))
588 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000589 };
590
591 Ok(DiskFile { image, writable: disk.writable })
592}
593
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100594fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
595 if let Some(ref mut params) = vm_config.params {
596 params.push(' ');
597 params.push_str(param)
598 } else {
599 vm_config.params = Some(param.to_owned())
600 }
601}
602
Jooyung Han21e9b922021-06-26 04:14:16 +0900603fn load_app_config(
604 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900605 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900606 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900607) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000608 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
609 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900610 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900611
Shikha Panwar22e70452022-10-10 18:32:55 +0000612 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
613 Some(clone_file(file)?)
614 } else {
615 None
616 };
617
Alan Stokes0d1ef782022-09-27 13:46:35 +0100618 let vm_payload_config = match &config.payload {
619 Payload::ConfigPath(config_path) => {
620 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
621 .with_context(|| format!("Couldn't read config from {}", config_path))?
622 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000623 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100624 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900625
Alan Stokes0d1ef782022-09-27 13:46:35 +0100626 // For now, the only supported OS is Microdroid
627 let os_name = vm_payload_config.os.name.as_str();
628 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000629 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900630 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000631
632 // It is safe to construct a filename based on the os_name because we've already checked that it
633 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900634 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
635 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000636 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900637
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100638 if let Some(custom_config) = &config.customConfig {
639 if let Some(file) = custom_config.customKernelImage.as_ref() {
640 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
641 }
642 vm_config.taskProfiles = custom_config.taskProfiles.clone();
643 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100644
645 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100646 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
647 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100648 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900649
650 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100651 }
652
Andrew Walbrancc045902021-07-27 16:06:17 +0000653 if config.memoryMib > 0 {
654 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000655 }
656
Seungjae Yoo62085c02022-08-12 04:44:52 +0000657 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000658 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000659 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900660
Shikha Panwar22e70452022-10-10 18:32:55 +0000661 // Microdroid takes additional init ramdisk & (optionally) storage image
662 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
663
664 // Include Microdroid payload disk (contains apks, idsigs) in vm config
665 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100666 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900667 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100668 temporary_directory,
669 apk_file,
670 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100671 &vm_payload_config,
672 &mut vm_config,
673 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900674
Andrew Walbrancc0db522021-07-12 17:03:42 +0000675 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900676}
677
Alan Stokes0d1ef782022-09-27 13:46:35 +0100678fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
679 let mut apk_zip = ZipArchive::new(apk_file)?;
680 let config_file = apk_zip.by_name(config_path)?;
681 Ok(serde_json::from_reader(config_file)?)
682}
683
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000684fn create_vm_payload_config(
685 payload_config: &VirtualMachinePayloadConfig,
686) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100687 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
688 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
689 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000690
691 let payload_binary_name = &payload_config.payloadBinaryName;
692 if payload_binary_name.contains('/') {
693 bail!("Payload binary name must not specify a path: {payload_binary_name}");
694 }
695
696 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
697 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100698 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
699 task: Some(task),
700 apexes: vec![],
701 extra_apks: vec![],
702 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900703 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100704 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000705 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100706}
707
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000708/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000709fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000710 temporary_directory: &Path,
711 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000712) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000713 let id = *next_temporary_image_id;
714 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000715 CompositeImageFilenames {
716 composite: temporary_directory.join(format!("composite-{}.img", id)),
717 header: temporary_directory.join(format!("composite-{}-header.img", id)),
718 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
719 }
720}
721
722/// Filenames for a composite disk image, including header and footer partitions.
723#[derive(Clone, Debug, Eq, PartialEq)]
724struct CompositeImageFilenames {
725 /// The composite disk image itself.
726 composite: PathBuf,
727 /// The header partition image.
728 header: PathBuf,
729 /// The footer partition image.
730 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000731}
732
Jiyong Park753553b2021-07-12 21:21:09 +0900733/// Checks whether the caller has a specific permission
734fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100735 let calling_pid = get_calling_pid();
736 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900737 // Root can do anything
738 if calling_uid == 0 {
739 return Ok(());
740 }
741 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
742 binder::get_interface("permission")?;
743 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000744 Ok(())
745 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900746 Err(anyhow!("does not have the {} permission", perm))
747 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000748 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000749}
750
Jiyong Park753553b2021-07-12 21:21:09 +0900751/// Check whether the caller of the current Binder method is allowed to manage VMs
752fn check_manage_access() -> binder::Result<()> {
753 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
754}
755
Inseob Kim1119d702022-05-02 18:01:58 +0900756/// Check whether the caller of the current Binder method is allowed to create custom VMs
757fn check_use_custom_virtual_machine() -> binder::Result<()> {
758 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
759}
760
Alan Stokes185fe112023-01-10 16:20:55 +0000761/// Return whether a partition is exempt from selinux label checks, because we know that it does
762/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100763fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000764 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100765 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000766 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100767 || label == "microdroid-apk-idsig"
768 || label == "payload-metadata"
769 || label.starts_with("extra-idsig-")
770}
771
Alice Wangc206b9b2023-08-28 14:13:51 +0000772/// Returns whether a partition with the given label is safe for a raw config VM.
773fn is_safe_raw_partition(label: &str) -> bool {
774 label == "vm-instance"
775}
776
Alan Stokes185fe112023-01-10 16:20:55 +0000777/// Check that a file SELinux label is acceptable.
778///
779/// We only want to allow code in a VM to be sourced from places that apps, and the
780/// system, do not have write access to.
781///
782/// Note that sepolicy must also grant read access for these types to both virtualization
783/// service and crosvm.
784///
785/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
786/// user devices (W^X).
787fn check_label_is_allowed(context: &SeContext) -> Result<()> {
788 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100789 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100790 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000791 | "staging_data_file" // updated/staged APEX images
792 | "system_file" // immutable dm-verity protected partition
793 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100794 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000795 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900796 }
797}
798
Alan Stokes185fe112023-01-10 16:20:55 +0000799fn check_label_for_partition(partition: &Partition) -> Result<()> {
800 let file = partition.image.as_ref().unwrap().as_ref();
801 check_label_is_allowed(&getfilecon(file)?)
802 .with_context(|| format!("Partition {} invalid", &partition.label))
803}
804
805fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
806 if let Some(f) = kernel {
807 check_label_for_file(f, "kernel")?;
808 }
809 if let Some(f) = initrd {
810 check_label_for_file(f, "initrd")?;
811 }
812 Ok(())
813}
814fn check_label_for_file(file: &File, name: &str) -> Result<()> {
815 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
816}
817
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000818/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
819#[derive(Debug)]
820struct VirtualMachine {
821 instance: Arc<VmInstance>,
822}
823
824impl VirtualMachine {
825 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000826 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000827 }
828}
829
830impl Interface for VirtualMachine {}
831
832impl IVirtualMachine for VirtualMachine {
833 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900834 // Don't check permission. The owner of the VM might have passed this binder object to
835 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000836 Ok(self.instance.cid as i32)
837 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000838
Andrew Walbran6b650662021-09-07 13:13:23 +0000839 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900840 // Don't check permission. The owner of the VM might have passed this binder object to
841 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000842 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000843 }
844
845 fn registerCallback(
846 &self,
847 callback: &Strong<dyn IVirtualMachineCallback>,
848 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900849 // Don't check permission. The owner of the VM might have passed this binder object to
850 // others.
851 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000852 // TODO: Should this give an error if the VM is already dead?
853 self.instance.callbacks.add(callback.clone());
854 Ok(())
855 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000856
Andrew Walbranf8d94112021-09-07 11:45:36 +0000857 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900858 self.instance
859 .start()
860 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
861 .with_log()
862 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000863 }
864
Inseob Kima446f802022-07-11 19:46:37 +0900865 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900866 self.instance
867 .kill()
868 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
869 .with_log()
870 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +0900871 }
872
Keir Frasercdd4b112022-11-24 14:02:25 +0000873 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900874 self.instance
875 .trim_memory(level)
876 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
877 .with_log()
878 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +0000879 }
880
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000881 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000882 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900883 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000884 }
Alan Stokes10c47672022-12-13 17:17:08 +0000885 let port = port as u32;
886 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900887 return Err(anyhow!("Can't connect to privileged port {port}"))
888 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +0000889 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900890 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
891 .context("Failed to connect")
892 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000893 Ok(vsock_stream_to_pfd(stream))
894 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000895}
896
897impl Drop for VirtualMachine {
898 fn drop(&mut self) {
899 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900900 if let Err(e) = self.instance.kill() {
901 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
902 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000903 }
904}
905
906/// A set of Binders to be called back in response to various events on the VM, such as when it
907/// dies.
908#[derive(Debug, Default)]
909pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
910
911impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900912 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100913 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900914 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900915 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100916 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100917 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900918 }
919 }
920 }
921
Inseob Kim14cb8692021-08-31 21:50:39 +0900922 /// Call all registered callbacks to notify that the payload is ready to serve.
923 pub fn notify_payload_ready(&self, cid: Cid) {
924 let callbacks = &*self.0.lock().unwrap();
925 for callback in callbacks {
926 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100927 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900928 }
929 }
930 }
931
Inseob Kim2444af92021-08-31 01:22:50 +0900932 /// Call all registered callbacks to notify that the payload has finished.
933 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
934 let callbacks = &*self.0.lock().unwrap();
935 for callback in callbacks {
936 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100937 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900938 }
939 }
940 }
941
Jooyung Handd0a1732021-11-23 15:26:20 +0900942 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100943 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900944 let callbacks = &*self.0.lock().unwrap();
945 for callback in callbacks {
946 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100947 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900948 }
949 }
950 }
951
Andrew Walbrandae07162021-03-12 17:05:20 +0000952 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000953 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000954 let callbacks = &*self.0.lock().unwrap();
955 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000956 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100957 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000958 }
959 }
960 }
961
962 /// Add a new callback to the set.
963 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
964 self.0.lock().unwrap().push(callback);
965 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000966}
967
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000968/// The mutable state of the VirtualizationService. There should only be one instance of this
969/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800970#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000971struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000972 /// The VMs which have been started. When VMs are started a weak reference is added to this list
973 /// while a strong reference is returned to the caller over Binder. Once all copies of the
974 /// Binder client are dropped the weak reference here will become invalid, and will be removed
975 /// from the list opportunistically the next time `add_vm` is called.
976 vms: Vec<Weak<VmInstance>>,
977}
978
979impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000980 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000981 fn vms(&self) -> Vec<Arc<VmInstance>> {
982 // Attempt to upgrade the weak pointers to strong pointers.
983 self.vms.iter().filter_map(Weak::upgrade).collect()
984 }
985
986 /// Add a new VM to the list.
987 fn add_vm(&mut self, vm: Weak<VmInstance>) {
988 // Garbage collect any entries from the stored list which no longer exist.
989 self.vms.retain(|vm| vm.strong_count() > 0);
990
991 // Actually add the new VM.
992 self.vms.push(vm);
993 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000994
Jiyong Park8611a6c2021-07-09 18:17:44 +0900995 /// Get a VM that corresponds to the given cid
996 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
997 self.vms().into_iter().find(|vm| vm.cid == cid)
998 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900999}
1000
Andrew Walbran6b650662021-09-07 13:13:23 +00001001/// Gets the `VirtualMachineState` of the given `VmInstance`.
1002fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001003 match &*instance.vm_state.lock().unwrap() {
1004 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1005 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001006 PayloadState::Starting => VirtualMachineState::STARTING,
1007 PayloadState::Started => VirtualMachineState::STARTED,
1008 PayloadState::Ready => VirtualMachineState::READY,
1009 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001010 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001011 },
1012 VmState::Dead => VirtualMachineState::DEAD,
1013 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001014 }
1015}
1016
David Brazdilf50c7a62023-04-19 14:22:42 +00001017/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001018pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1019 file.as_ref()
1020 .try_clone()
1021 .context("Failed to clone File from ParcelFileDescriptor")
1022 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
David Brazdilf50c7a62023-04-19 14:22:42 +00001023}
1024
Andrew Walbrand3a84182021-09-07 14:48:52 +00001025/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001026fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001027 file.as_ref().map(clone_file).transpose()
1028}
1029
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001030/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1031fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1032 // SAFETY: ownership is transferred from stream to f
1033 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1034 ParcelFileDescriptor::new(f)
1035}
1036
Jiyong Parkdcf17412022-02-08 15:07:23 +09001037/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001038fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1039 VersionReq::parse(s)
1040 .with_context(|| format!("Invalid platform version requirement {}", s))
1041 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001042}
1043
Jiyong Parked180932023-02-24 19:55:41 +09001044/// Create the empty ramdump file
1045fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1046 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1047 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1048 // owner) for readout.
1049 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001050 let ramdump = File::create(ramdump_path)
1051 .context("Failed to prepare ramdump file")
1052 .with_log()
1053 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001054 Ok(ramdump)
1055}
1056
Nikita Ioffe5776f082023-02-10 21:38:26 +00001057fn is_protected(config: &VirtualMachineConfig) -> bool {
1058 match config {
1059 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1060 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1061 }
1062}
1063
1064fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1065 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001066 return Err(anyhow!("Can't use gdb with protected VMs"))
1067 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001068 }
1069
1070 match config {
1071 VirtualMachineConfig::RawConfig(_) => Ok(()),
1072 VirtualMachineConfig::AppConfig(config) => {
1073 if config.debugLevel != DebugLevel::FULL {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001074 Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1075 .or_binder_exception(ExceptionCode::SECURITY)
Nikita Ioffe5776f082023-02-10 21:38:26 +00001076 } else {
1077 Ok(())
1078 }
1079 }
1080 }
1081}
1082
1083fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1084 match config {
1085 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001086 VirtualMachineConfig::AppConfig(config) => {
1087 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1088 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001089 }
1090}
1091
Inseob Kim0168b462022-12-27 14:54:35 +09001092fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001093 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001094 fd: Option<&ParcelFileDescriptor>,
1095 tag: String,
1096) -> Result<Option<File>, Status> {
1097 if let Some(fd) = fd {
1098 return Ok(Some(clone_file(fd)?));
1099 }
1100
Jaewan Kim61f86142023-03-28 15:12:52 +09001101 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001102 return Ok(None);
1103 };
Inseob Kim0168b462022-12-27 14:54:35 +09001104
Jiyong Park2227eaa2023-08-04 11:59:18 +09001105 let (raw_read_fd, raw_write_fd) =
1106 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001107
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001108 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Inseob Kim0168b462022-12-27 14:54:35 +09001109 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001110 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Inseob Kim0168b462022-12-27 14:54:35 +09001111 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1112
1113 std::thread::spawn(move || loop {
1114 let mut buf = vec![];
1115 match reader.read_until(b'\n', &mut buf) {
1116 Ok(0) => {
1117 // EOF
1118 return;
1119 }
1120 Ok(size) => {
1121 if buf[size - 1] == b'\n' {
1122 buf.pop();
1123 }
1124 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1125 }
1126 Err(e) => {
1127 error!("Could not read console pipe: {:?}", e);
1128 return;
1129 }
1130 };
1131 });
1132
1133 Ok(Some(write_fd))
1134}
1135
Jooyung Han35edb8f2021-07-01 16:17:16 +09001136/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1137/// it doesn't require that T implements Clone.
1138enum BorrowedOrOwned<'a, T> {
1139 Borrowed(&'a T),
1140 Owned(T),
1141}
1142
1143impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1144 fn as_ref(&self) -> &T {
1145 match self {
1146 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001147 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001148 }
1149 }
1150}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001151
1152/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1153#[derive(Debug, Default)]
1154struct VirtualMachineService {
1155 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001156 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001157}
1158
1159impl Interface for VirtualMachineService {}
1160
1161impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001162 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1163 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001164 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001165 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001166 vm.update_payload_state(PayloadState::Started)
1167 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001168 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001169
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001170 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1171 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001172 Ok(())
1173 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001174 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001175 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001176 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001177 }
Inseob Kim2444af92021-08-31 01:22:50 +09001178
Inseob Kimc7d28c72021-10-25 14:28:10 +00001179 fn notifyPayloadReady(&self) -> binder::Result<()> {
1180 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001181 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001182 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001183 vm.update_payload_state(PayloadState::Ready)
1184 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001185 vm.callbacks.notify_payload_ready(cid);
1186 Ok(())
1187 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001188 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001189 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001190 }
1191 }
1192
Inseob Kimc7d28c72021-10-25 14:28:10 +00001193 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1194 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001195 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001196 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001197 vm.update_payload_state(PayloadState::Finished)
1198 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001199 vm.callbacks.notify_payload_finished(cid, exit_code);
1200 Ok(())
1201 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001202 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001203 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001204 }
1205 }
1206
Alan Stokes2bead0d2022-09-05 16:58:34 +01001207 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001208 let cid = self.cid;
1209 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001210 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001211 vm.update_payload_state(PayloadState::Finished)
1212 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001213 vm.callbacks.notify_error(cid, error_code, message);
1214 Ok(())
1215 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001216 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001217 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001218 }
1219 }
Alice Wangc2fec932023-02-23 16:24:02 +00001220
1221 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
Alice Wangc206b9b2023-08-28 14:13:51 +00001222 GLOBAL_SERVICE.requestCertificate(csr)
Alice Wangc2fec932023-02-23 16:24:02 +00001223 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001224}
1225
1226impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001227 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001228 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001229 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001230 BinderFeatures::default(),
1231 )
1232 }
1233}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001234
1235#[cfg(test)]
1236mod tests {
1237 use super::*;
1238
1239 #[test]
1240 fn test_is_allowed_label_for_partition() -> Result<()> {
1241 let expected_results = vec![
1242 ("u:object_r:system_file:s0", true),
1243 ("u:object_r:apk_data_file:s0", true),
1244 ("u:object_r:app_data_file:s0", false),
1245 ("u:object_r:app_data_file:s0:c512,c768", false),
1246 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1247 ("invalid", false),
1248 ("user:role:apk_data_file:severity:categories", true),
1249 ("user:role:apk_data_file:severity:categories:extraneous", false),
1250 ];
1251
1252 for (label, expected_valid) in expected_results {
1253 let context = SeContext::new(label)?;
1254 let result = check_label_is_allowed(&context);
1255 if expected_valid {
1256 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1257 } else if result.is_ok() {
1258 bail!("Expected label {} to be disallowed", label);
1259 }
1260 }
1261 Ok(())
1262 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001263
1264 #[test]
1265 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1266 let apk = tempfile::tempfile().unwrap();
1267 let idsig = tempfile::tempfile().unwrap();
1268
1269 let ret = create_or_update_idsig_file(
1270 &ParcelFileDescriptor::new(apk),
1271 &ParcelFileDescriptor::new(idsig),
1272 );
1273 assert!(ret.is_err(), "should fail");
1274 Ok(())
1275 }
1276
1277 #[test]
1278 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1279 let tmp_dir = tempfile::TempDir::new().unwrap();
1280 let apk = File::open(tmp_dir.path()).unwrap();
1281 let idsig = tempfile::tempfile().unwrap();
1282
1283 let ret = create_or_update_idsig_file(
1284 &ParcelFileDescriptor::new(apk),
1285 &ParcelFileDescriptor::new(idsig),
1286 );
1287 assert!(ret.is_err(), "should fail");
1288 Ok(())
1289 }
1290
1291 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1292 /// on ext4 filesystem is passed.
1293 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1294 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1295 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1296 #[test]
1297 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1298 // APEXes are backed by the ext4.
1299 let apk = File::open("/apex/com.android.virt/").unwrap();
1300 let idsig = tempfile::tempfile().unwrap();
1301
1302 let ret = create_or_update_idsig_file(
1303 &ParcelFileDescriptor::new(apk),
1304 &ParcelFileDescriptor::new(idsig),
1305 );
1306 assert!(ret.is_err(), "should fail");
1307 Ok(())
1308 }
Jiyong Park8d192952023-06-26 14:29:51 +09001309
1310 #[test]
1311 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1312 use std::io::Seek;
1313
1314 // Pick any APK
1315 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1316 let mut idsig = tempfile::tempfile().unwrap();
1317
1318 create_or_update_idsig_file(
1319 &ParcelFileDescriptor::new(apk.try_clone()?),
1320 &ParcelFileDescriptor::new(idsig.try_clone()?),
1321 )?;
1322 let modified_orig = idsig.metadata()?.modified()?;
1323 apk.rewind()?;
1324 idsig.rewind()?;
1325
1326 // Call the function again
1327 create_or_update_idsig_file(
1328 &ParcelFileDescriptor::new(apk.try_clone()?),
1329 &ParcelFileDescriptor::new(idsig.try_clone()?),
1330 )?;
1331 let modified_new = idsig.metadata()?.modified()?;
1332 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1333 Ok(())
1334 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001335
1336 #[test]
1337 fn test_append_kernel_param_first_param() {
1338 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1339 append_kernel_param("foo=1", &mut vm_config);
1340 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1341 }
1342
1343 #[test]
1344 fn test_append_kernel_param() {
1345 let mut vm_config =
1346 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1347 append_kernel_param("bar=42", &mut vm_config);
1348 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1349 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001350}