blob: fa99c6366a1896a205f95592f827d89dea24d260 [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
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900438 if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900439 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 }
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900449 GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
450 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900451
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000452 // Actually start the VM.
453 let crosvm_config = CrosvmConfig {
454 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000455 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000456 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000457 kernel,
458 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000459 disks,
460 params: config.params.to_owned(),
461 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900462 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000463 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000464 cpus,
465 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900466 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900467 console_out_fd,
468 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000469 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900470 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000471 indirect_files,
472 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900473 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000474 gdb_port,
Inseob Kim6ef80972023-07-20 17:23:36 +0900475 vfio_devices: config.devices.iter().map(PathBuf::from).collect(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000476 };
477 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100478 VmInstance::new(
479 crosvm_config,
480 temporary_directory,
481 requester_uid,
482 requester_debug_pid,
483 vm_context,
484 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900485 .with_context(|| format!("Failed to create VM with config {:?}", config))
486 .with_log()
487 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000488 );
489 state.add_vm(Arc::downgrade(&instance));
490 Ok(VirtualMachine::create(instance))
491 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900492}
493
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000494fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900495 let file = OpenOptions::new()
496 .create_new(true)
497 .read(true)
498 .write(true)
499 .open(zero_filler_path)
500 .with_context(|| "Failed to create zero.img")?;
501 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000502 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900503}
504
David Brazdilf50c7a62023-04-19 14:22:42 +0000505fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
506 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
507 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
508 part.flush()
509}
510
511fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
512 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
513 part.flush()
514}
515
516fn round_up(input: u64, granularity: u64) -> u64 {
517 if granularity == 0 {
518 return input;
519 }
520 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
521 let result = input.checked_add(granularity - 1).unwrap_or(input);
522 (result / granularity) * granularity
523}
524
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000525/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
526///
527/// This may involve assembling a composite disk from a set of partition images.
528fn assemble_disk_image(
529 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900530 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000531 temporary_directory: &Path,
532 next_temporary_image_id: &mut u64,
533 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000534) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000535 let image = if !disk.partitions.is_empty() {
536 if disk.image.is_some() {
537 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900538 return Err(anyhow!("DiskImage contains both image and partitions"))
539 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000540 }
541
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000542 let composite_image_filenames =
543 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
544 let (image, partition_files) = make_composite_image(
545 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900546 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000547 &composite_image_filenames.composite,
548 &composite_image_filenames.header,
549 &composite_image_filenames.footer,
550 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900551 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
552 .with_log()
553 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000554
555 // Pass the file descriptors for the various partition files to crosvm when it
556 // is run.
557 indirect_files.extend(partition_files);
558
559 image
560 } else if let Some(image) = &disk.image {
561 clone_file(image)?
562 } else {
563 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900564 return Err(anyhow!("DiskImage didn't contain image or partitions."))
565 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000566 };
567
568 Ok(DiskFile { image, writable: disk.writable })
569}
570
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100571fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
572 if let Some(ref mut params) = vm_config.params {
573 params.push(' ');
574 params.push_str(param)
575 } else {
576 vm_config.params = Some(param.to_owned())
577 }
578}
579
Jooyung Han21e9b922021-06-26 04:14:16 +0900580fn load_app_config(
581 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900582 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900583 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900584) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000585 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
586 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900587 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900588
Shikha Panwar22e70452022-10-10 18:32:55 +0000589 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
590 Some(clone_file(file)?)
591 } else {
592 None
593 };
594
Alan Stokes0d1ef782022-09-27 13:46:35 +0100595 let vm_payload_config = match &config.payload {
596 Payload::ConfigPath(config_path) => {
597 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
598 .with_context(|| format!("Couldn't read config from {}", config_path))?
599 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000600 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100601 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900602
Alan Stokes0d1ef782022-09-27 13:46:35 +0100603 // For now, the only supported OS is Microdroid
604 let os_name = vm_payload_config.os.name.as_str();
605 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000606 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900607 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000608
609 // It is safe to construct a filename based on the os_name because we've already checked that it
610 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900611 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
612 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000613 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900614
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100615 if let Some(custom_config) = &config.customConfig {
616 if let Some(file) = custom_config.customKernelImage.as_ref() {
617 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
618 }
619 vm_config.taskProfiles = custom_config.taskProfiles.clone();
620 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100621
622 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100623 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
624 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100625 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900626
627 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100628 }
629
Andrew Walbrancc045902021-07-27 16:06:17 +0000630 if config.memoryMib > 0 {
631 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000632 }
633
Seungjae Yoo62085c02022-08-12 04:44:52 +0000634 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000635 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000636 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900637
Shikha Panwar22e70452022-10-10 18:32:55 +0000638 // Microdroid takes additional init ramdisk & (optionally) storage image
639 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
640
641 // Include Microdroid payload disk (contains apks, idsigs) in vm config
642 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100643 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900644 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100645 temporary_directory,
646 apk_file,
647 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100648 &vm_payload_config,
649 &mut vm_config,
650 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900651
Andrew Walbrancc0db522021-07-12 17:03:42 +0000652 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900653}
654
Alan Stokes0d1ef782022-09-27 13:46:35 +0100655fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
656 let mut apk_zip = ZipArchive::new(apk_file)?;
657 let config_file = apk_zip.by_name(config_path)?;
658 Ok(serde_json::from_reader(config_file)?)
659}
660
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000661fn create_vm_payload_config(
662 payload_config: &VirtualMachinePayloadConfig,
663) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100664 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
665 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
666 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000667
668 let payload_binary_name = &payload_config.payloadBinaryName;
669 if payload_binary_name.contains('/') {
670 bail!("Payload binary name must not specify a path: {payload_binary_name}");
671 }
672
673 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
674 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100675 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
676 task: Some(task),
677 apexes: vec![],
678 extra_apks: vec![],
679 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900680 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100681 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000682 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100683}
684
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000685/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000686fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000687 temporary_directory: &Path,
688 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000689) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000690 let id = *next_temporary_image_id;
691 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000692 CompositeImageFilenames {
693 composite: temporary_directory.join(format!("composite-{}.img", id)),
694 header: temporary_directory.join(format!("composite-{}-header.img", id)),
695 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
696 }
697}
698
699/// Filenames for a composite disk image, including header and footer partitions.
700#[derive(Clone, Debug, Eq, PartialEq)]
701struct CompositeImageFilenames {
702 /// The composite disk image itself.
703 composite: PathBuf,
704 /// The header partition image.
705 header: PathBuf,
706 /// The footer partition image.
707 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000708}
709
Jiyong Park753553b2021-07-12 21:21:09 +0900710/// Checks whether the caller has a specific permission
711fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100712 let calling_pid = get_calling_pid();
713 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900714 // Root can do anything
715 if calling_uid == 0 {
716 return Ok(());
717 }
718 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
719 binder::get_interface("permission")?;
720 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000721 Ok(())
722 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900723 Err(anyhow!("does not have the {} permission", perm))
724 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000725 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000726}
727
Jiyong Park753553b2021-07-12 21:21:09 +0900728/// Check whether the caller of the current Binder method is allowed to manage VMs
729fn check_manage_access() -> binder::Result<()> {
730 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
731}
732
Inseob Kim1119d702022-05-02 18:01:58 +0900733/// Check whether the caller of the current Binder method is allowed to create custom VMs
734fn check_use_custom_virtual_machine() -> binder::Result<()> {
735 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
736}
737
Alan Stokes185fe112023-01-10 16:20:55 +0000738/// Return whether a partition is exempt from selinux label checks, because we know that it does
739/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100740fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000741 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100742 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000743 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100744 || label == "microdroid-apk-idsig"
745 || label == "payload-metadata"
746 || label.starts_with("extra-idsig-")
747}
748
Alice Wangc206b9b2023-08-28 14:13:51 +0000749/// Returns whether a partition with the given label is safe for a raw config VM.
750fn is_safe_raw_partition(label: &str) -> bool {
751 label == "vm-instance"
752}
753
Alan Stokes185fe112023-01-10 16:20:55 +0000754/// Check that a file SELinux label is acceptable.
755///
756/// We only want to allow code in a VM to be sourced from places that apps, and the
757/// system, do not have write access to.
758///
759/// Note that sepolicy must also grant read access for these types to both virtualization
760/// service and crosvm.
761///
762/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
763/// user devices (W^X).
764fn check_label_is_allowed(context: &SeContext) -> Result<()> {
765 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100766 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100767 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000768 | "staging_data_file" // updated/staged APEX images
769 | "system_file" // immutable dm-verity protected partition
770 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100771 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000772 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900773 }
774}
775
Alan Stokes185fe112023-01-10 16:20:55 +0000776fn check_label_for_partition(partition: &Partition) -> Result<()> {
777 let file = partition.image.as_ref().unwrap().as_ref();
778 check_label_is_allowed(&getfilecon(file)?)
779 .with_context(|| format!("Partition {} invalid", &partition.label))
780}
781
782fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
783 if let Some(f) = kernel {
784 check_label_for_file(f, "kernel")?;
785 }
786 if let Some(f) = initrd {
787 check_label_for_file(f, "initrd")?;
788 }
789 Ok(())
790}
791fn check_label_for_file(file: &File, name: &str) -> Result<()> {
792 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
793}
794
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000795/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
796#[derive(Debug)]
797struct VirtualMachine {
798 instance: Arc<VmInstance>,
799}
800
801impl VirtualMachine {
802 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000803 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000804 }
805}
806
807impl Interface for VirtualMachine {}
808
809impl IVirtualMachine for VirtualMachine {
810 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900811 // Don't check permission. The owner of the VM might have passed this binder object to
812 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000813 Ok(self.instance.cid as i32)
814 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000815
Andrew Walbran6b650662021-09-07 13:13:23 +0000816 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900817 // Don't check permission. The owner of the VM might have passed this binder object to
818 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000819 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000820 }
821
822 fn registerCallback(
823 &self,
824 callback: &Strong<dyn IVirtualMachineCallback>,
825 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900826 // Don't check permission. The owner of the VM might have passed this binder object to
827 // others.
828 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000829 // TODO: Should this give an error if the VM is already dead?
830 self.instance.callbacks.add(callback.clone());
831 Ok(())
832 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000833
Andrew Walbranf8d94112021-09-07 11:45:36 +0000834 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900835 self.instance
836 .start()
837 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
838 .with_log()
839 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000840 }
841
Inseob Kima446f802022-07-11 19:46:37 +0900842 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900843 self.instance
844 .kill()
845 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
846 .with_log()
847 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +0900848 }
849
Keir Frasercdd4b112022-11-24 14:02:25 +0000850 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900851 self.instance
852 .trim_memory(level)
853 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
854 .with_log()
855 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +0000856 }
857
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000858 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000859 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900860 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000861 }
Alan Stokes10c47672022-12-13 17:17:08 +0000862 let port = port as u32;
863 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900864 return Err(anyhow!("Can't connect to privileged port {port}"))
865 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +0000866 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900867 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
868 .context("Failed to connect")
869 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000870 Ok(vsock_stream_to_pfd(stream))
871 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000872}
873
874impl Drop for VirtualMachine {
875 fn drop(&mut self) {
876 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900877 if let Err(e) = self.instance.kill() {
878 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
879 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000880 }
881}
882
883/// A set of Binders to be called back in response to various events on the VM, such as when it
884/// dies.
885#[derive(Debug, Default)]
886pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
887
888impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900889 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100890 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900891 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900892 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100893 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100894 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900895 }
896 }
897 }
898
Inseob Kim14cb8692021-08-31 21:50:39 +0900899 /// Call all registered callbacks to notify that the payload is ready to serve.
900 pub fn notify_payload_ready(&self, cid: Cid) {
901 let callbacks = &*self.0.lock().unwrap();
902 for callback in callbacks {
903 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100904 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900905 }
906 }
907 }
908
Inseob Kim2444af92021-08-31 01:22:50 +0900909 /// Call all registered callbacks to notify that the payload has finished.
910 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
911 let callbacks = &*self.0.lock().unwrap();
912 for callback in callbacks {
913 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100914 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900915 }
916 }
917 }
918
Jooyung Handd0a1732021-11-23 15:26:20 +0900919 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100920 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900921 let callbacks = &*self.0.lock().unwrap();
922 for callback in callbacks {
923 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100924 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900925 }
926 }
927 }
928
Andrew Walbrandae07162021-03-12 17:05:20 +0000929 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000930 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000931 let callbacks = &*self.0.lock().unwrap();
932 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000933 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100934 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000935 }
936 }
937 }
938
939 /// Add a new callback to the set.
940 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
941 self.0.lock().unwrap().push(callback);
942 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000943}
944
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000945/// The mutable state of the VirtualizationService. There should only be one instance of this
946/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800947#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000948struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000949 /// The VMs which have been started. When VMs are started a weak reference is added to this list
950 /// while a strong reference is returned to the caller over Binder. Once all copies of the
951 /// Binder client are dropped the weak reference here will become invalid, and will be removed
952 /// from the list opportunistically the next time `add_vm` is called.
953 vms: Vec<Weak<VmInstance>>,
954}
955
956impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000957 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000958 fn vms(&self) -> Vec<Arc<VmInstance>> {
959 // Attempt to upgrade the weak pointers to strong pointers.
960 self.vms.iter().filter_map(Weak::upgrade).collect()
961 }
962
963 /// Add a new VM to the list.
964 fn add_vm(&mut self, vm: Weak<VmInstance>) {
965 // Garbage collect any entries from the stored list which no longer exist.
966 self.vms.retain(|vm| vm.strong_count() > 0);
967
968 // Actually add the new VM.
969 self.vms.push(vm);
970 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000971
Jiyong Park8611a6c2021-07-09 18:17:44 +0900972 /// Get a VM that corresponds to the given cid
973 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
974 self.vms().into_iter().find(|vm| vm.cid == cid)
975 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900976}
977
Andrew Walbran6b650662021-09-07 13:13:23 +0000978/// Gets the `VirtualMachineState` of the given `VmInstance`.
979fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000980 match &*instance.vm_state.lock().unwrap() {
981 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
982 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000983 PayloadState::Starting => VirtualMachineState::STARTING,
984 PayloadState::Started => VirtualMachineState::STARTED,
985 PayloadState::Ready => VirtualMachineState::READY,
986 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900987 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000988 },
989 VmState::Dead => VirtualMachineState::DEAD,
990 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000991 }
992}
993
David Brazdilf50c7a62023-04-19 14:22:42 +0000994/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +0900995pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
996 file.as_ref()
997 .try_clone()
998 .context("Failed to clone File from ParcelFileDescriptor")
999 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
David Brazdilf50c7a62023-04-19 14:22:42 +00001000}
1001
Andrew Walbrand3a84182021-09-07 14:48:52 +00001002/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001003fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001004 file.as_ref().map(clone_file).transpose()
1005}
1006
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001007/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1008fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1009 // SAFETY: ownership is transferred from stream to f
1010 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1011 ParcelFileDescriptor::new(f)
1012}
1013
Jiyong Parkdcf17412022-02-08 15:07:23 +09001014/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001015fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1016 VersionReq::parse(s)
1017 .with_context(|| format!("Invalid platform version requirement {}", s))
1018 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001019}
1020
Jiyong Parked180932023-02-24 19:55:41 +09001021/// Create the empty ramdump file
1022fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1023 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1024 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1025 // owner) for readout.
1026 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001027 let ramdump = File::create(ramdump_path)
1028 .context("Failed to prepare ramdump file")
1029 .with_log()
1030 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001031 Ok(ramdump)
1032}
1033
Nikita Ioffe5776f082023-02-10 21:38:26 +00001034fn is_protected(config: &VirtualMachineConfig) -> bool {
1035 match config {
1036 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1037 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1038 }
1039}
1040
1041fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1042 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001043 return Err(anyhow!("Can't use gdb with protected VMs"))
1044 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001045 }
1046
1047 match config {
1048 VirtualMachineConfig::RawConfig(_) => Ok(()),
1049 VirtualMachineConfig::AppConfig(config) => {
1050 if config.debugLevel != DebugLevel::FULL {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001051 Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1052 .or_binder_exception(ExceptionCode::SECURITY)
Nikita Ioffe5776f082023-02-10 21:38:26 +00001053 } else {
1054 Ok(())
1055 }
1056 }
1057 }
1058}
1059
1060fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1061 match config {
1062 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001063 VirtualMachineConfig::AppConfig(config) => {
1064 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1065 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001066 }
1067}
1068
Inseob Kim0168b462022-12-27 14:54:35 +09001069fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001070 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001071 fd: Option<&ParcelFileDescriptor>,
1072 tag: String,
1073) -> Result<Option<File>, Status> {
1074 if let Some(fd) = fd {
1075 return Ok(Some(clone_file(fd)?));
1076 }
1077
Jaewan Kim61f86142023-03-28 15:12:52 +09001078 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001079 return Ok(None);
1080 };
Inseob Kim0168b462022-12-27 14:54:35 +09001081
Jiyong Park2227eaa2023-08-04 11:59:18 +09001082 let (raw_read_fd, raw_write_fd) =
1083 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001084
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001085 // 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 +09001086 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001087 // 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 +09001088 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1089
1090 std::thread::spawn(move || loop {
1091 let mut buf = vec![];
1092 match reader.read_until(b'\n', &mut buf) {
1093 Ok(0) => {
1094 // EOF
1095 return;
1096 }
1097 Ok(size) => {
1098 if buf[size - 1] == b'\n' {
1099 buf.pop();
1100 }
1101 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1102 }
1103 Err(e) => {
1104 error!("Could not read console pipe: {:?}", e);
1105 return;
1106 }
1107 };
1108 });
1109
1110 Ok(Some(write_fd))
1111}
1112
Jooyung Han35edb8f2021-07-01 16:17:16 +09001113/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1114/// it doesn't require that T implements Clone.
1115enum BorrowedOrOwned<'a, T> {
1116 Borrowed(&'a T),
1117 Owned(T),
1118}
1119
1120impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1121 fn as_ref(&self) -> &T {
1122 match self {
1123 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001124 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001125 }
1126 }
1127}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001128
1129/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1130#[derive(Debug, Default)]
1131struct VirtualMachineService {
1132 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001133 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001134}
1135
1136impl Interface for VirtualMachineService {}
1137
1138impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001139 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1140 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001141 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001142 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001143 vm.update_payload_state(PayloadState::Started)
1144 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001145 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001146
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001147 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1148 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001149 Ok(())
1150 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001151 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001152 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001153 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001154 }
Inseob Kim2444af92021-08-31 01:22:50 +09001155
Inseob Kimc7d28c72021-10-25 14:28:10 +00001156 fn notifyPayloadReady(&self) -> binder::Result<()> {
1157 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001158 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001159 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001160 vm.update_payload_state(PayloadState::Ready)
1161 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001162 vm.callbacks.notify_payload_ready(cid);
1163 Ok(())
1164 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001165 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001166 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001167 }
1168 }
1169
Inseob Kimc7d28c72021-10-25 14:28:10 +00001170 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1171 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001172 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001173 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001174 vm.update_payload_state(PayloadState::Finished)
1175 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001176 vm.callbacks.notify_payload_finished(cid, exit_code);
1177 Ok(())
1178 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001179 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001180 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001181 }
1182 }
1183
Alan Stokes2bead0d2022-09-05 16:58:34 +01001184 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001185 let cid = self.cid;
1186 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001187 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001188 vm.update_payload_state(PayloadState::Finished)
1189 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001190 vm.callbacks.notify_error(cid, error_code, message);
1191 Ok(())
1192 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001193 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001194 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001195 }
1196 }
Alice Wangc2fec932023-02-23 16:24:02 +00001197
1198 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
Alice Wangc206b9b2023-08-28 14:13:51 +00001199 GLOBAL_SERVICE.requestCertificate(csr)
Alice Wangc2fec932023-02-23 16:24:02 +00001200 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001201}
1202
1203impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001204 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001205 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001206 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001207 BinderFeatures::default(),
1208 )
1209 }
1210}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001211
1212#[cfg(test)]
1213mod tests {
1214 use super::*;
1215
1216 #[test]
1217 fn test_is_allowed_label_for_partition() -> Result<()> {
1218 let expected_results = vec![
1219 ("u:object_r:system_file:s0", true),
1220 ("u:object_r:apk_data_file:s0", true),
1221 ("u:object_r:app_data_file:s0", false),
1222 ("u:object_r:app_data_file:s0:c512,c768", false),
1223 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1224 ("invalid", false),
1225 ("user:role:apk_data_file:severity:categories", true),
1226 ("user:role:apk_data_file:severity:categories:extraneous", false),
1227 ];
1228
1229 for (label, expected_valid) in expected_results {
1230 let context = SeContext::new(label)?;
1231 let result = check_label_is_allowed(&context);
1232 if expected_valid {
1233 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1234 } else if result.is_ok() {
1235 bail!("Expected label {} to be disallowed", label);
1236 }
1237 }
1238 Ok(())
1239 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001240
1241 #[test]
1242 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1243 let apk = tempfile::tempfile().unwrap();
1244 let idsig = tempfile::tempfile().unwrap();
1245
1246 let ret = create_or_update_idsig_file(
1247 &ParcelFileDescriptor::new(apk),
1248 &ParcelFileDescriptor::new(idsig),
1249 );
1250 assert!(ret.is_err(), "should fail");
1251 Ok(())
1252 }
1253
1254 #[test]
1255 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1256 let tmp_dir = tempfile::TempDir::new().unwrap();
1257 let apk = File::open(tmp_dir.path()).unwrap();
1258 let idsig = tempfile::tempfile().unwrap();
1259
1260 let ret = create_or_update_idsig_file(
1261 &ParcelFileDescriptor::new(apk),
1262 &ParcelFileDescriptor::new(idsig),
1263 );
1264 assert!(ret.is_err(), "should fail");
1265 Ok(())
1266 }
1267
1268 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1269 /// on ext4 filesystem is passed.
1270 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1271 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1272 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1273 #[test]
1274 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1275 // APEXes are backed by the ext4.
1276 let apk = File::open("/apex/com.android.virt/").unwrap();
1277 let idsig = tempfile::tempfile().unwrap();
1278
1279 let ret = create_or_update_idsig_file(
1280 &ParcelFileDescriptor::new(apk),
1281 &ParcelFileDescriptor::new(idsig),
1282 );
1283 assert!(ret.is_err(), "should fail");
1284 Ok(())
1285 }
Jiyong Park8d192952023-06-26 14:29:51 +09001286
1287 #[test]
1288 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1289 use std::io::Seek;
1290
1291 // Pick any APK
1292 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1293 let mut idsig = tempfile::tempfile().unwrap();
1294
1295 create_or_update_idsig_file(
1296 &ParcelFileDescriptor::new(apk.try_clone()?),
1297 &ParcelFileDescriptor::new(idsig.try_clone()?),
1298 )?;
1299 let modified_orig = idsig.metadata()?.modified()?;
1300 apk.rewind()?;
1301 idsig.rewind()?;
1302
1303 // Call the function again
1304 create_or_update_idsig_file(
1305 &ParcelFileDescriptor::new(apk.try_clone()?),
1306 &ParcelFileDescriptor::new(idsig.try_clone()?),
1307 )?;
1308 let modified_new = idsig.metadata()?.modified()?;
1309 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1310 Ok(())
1311 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001312
1313 #[test]
1314 fn test_append_kernel_param_first_param() {
1315 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1316 append_kernel_param("foo=1", &mut vm_config);
1317 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1318 }
1319
1320 #[test]
1321 fn test_append_kernel_param() {
1322 let mut vm_config =
1323 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1324 append_kernel_param("bar=42", &mut vm_config);
1325 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1326 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001327}