blob: 749d75f35cc38069402b0c5ad8511d3cfc1a4324 [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 Kimc03f6612023-02-20 00:06:26 +090022use crate::debug_config::should_prepare_console_output;
Jiyong Parked180932023-02-24 19:55:41 +090023use crate::debug_config::is_ramdump_needed;
Shikha Panwar22e70452022-10-10 18:32:55 +000024use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090025use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090026use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000027use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
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};
Alan Stokes0e82b502022-08-08 14:44:48 +010053use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000054 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
55 Status, StatusCode, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000056};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000057use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000058use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000059use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090060use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090061use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000062use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000063use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090064use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000065use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000066use std::ffi::CStr;
David Brazdilafc9a9e2023-01-12 16:08:10 +000067use std::fs::{read_dir, remove_file, File, OpenOptions};
68use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000069use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000070use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000071use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000072use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000073use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000074use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000075use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090076use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000077
David Brazdil41d1a872022-10-05 14:44:19 +010078/// The unique ID of a VM used (together with a port number) for vsock communication.
79pub type Cid = u32;
80
David Brazdil4b4c5102022-12-19 22:56:20 +000081pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
82
Jooyung Han95884632021-07-06 22:27:54 +090083/// The size of zero.img.
84/// Gaps in composite disk images are filled with a shared zero.img.
85const ZERO_FILLER_SIZE: u64 = 4096;
86
Jiyong Park9dd389e2021-08-23 20:42:59 +090087/// Magic string for the instance image
88const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
89
90/// Version of the instance image format
91const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
92
Alan Stokes0d1ef782022-09-27 13:46:35 +010093const MICRODROID_OS_NAME: &str = "microdroid";
94
Shikha Panwar9fd198f2022-11-18 17:43:43 +000095const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
96
Alan Stokesff0005f2023-01-30 09:53:00 +000097/// crosvm requires all partitions to be a multiple of 4KiB.
98const PARTITION_GRANULARITY_BYTES: u64 = 4096;
99
David Brazdil49f96f52022-12-16 21:29:13 +0000100lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000101 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
102 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
103 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000104}
105
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000106fn create_or_update_idsig_file(
107 input_fd: &ParcelFileDescriptor,
108 idsig_fd: &ParcelFileDescriptor,
109) -> Result<()> {
110 let mut input = clone_file(input_fd)?;
111 let metadata = input.metadata().context("failed to get input metadata")?;
112 if !metadata.is_file() {
113 bail!("input is not a regular file");
114 }
Alan Stokes25f69362023-03-06 16:51:54 +0000115 let mut sig =
116 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
117 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000118
119 let mut output = clone_file(idsig_fd)?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000120 output.set_len(0).context("failed to set_len on the idsig output")?;
121 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000122 Ok(())
123}
124
Alan Stokes25f69362023-03-06 16:51:54 +0000125fn get_current_sdk() -> Result<u32> {
126 let current_sdk = system_properties::read("ro.build.version.sdk")?;
127 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
128 current_sdk.parse().context("Malformed SDK version")
129}
130
David Brazdil4b4c5102022-12-19 22:56:20 +0000131pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
132 for dir_entry in read_dir(path)? {
133 remove_file(dir_entry?.path())?;
134 }
135 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100136}
137
David Brazdil528e0472022-10-10 15:06:02 +0100138/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000139#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000140pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900141 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000142}
143
Shikha Panward8e35422021-10-11 13:51:27 +0000144impl Interface for VirtualizationService {
145 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
146 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
147 let state = &mut *self.state.lock().unwrap();
148 let vms = state.vms();
149 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
150 for vm in vms {
151 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
152 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
153 .or(Err(StatusCode::UNKNOWN_ERROR))?;
154 writeln!(file, "\tPayload state {:?}", vm.payload_state())
155 .or(Err(StatusCode::UNKNOWN_ERROR))?;
156 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
157 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
158 .or(Err(StatusCode::UNKNOWN_ERROR))?;
159 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
160 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000161 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
162 .or(Err(StatusCode::UNKNOWN_ERROR))?;
163 }
164 Ok(())
165 }
166}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000167
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000168impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000169 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
170 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000171 ///
172 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000173 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000174 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000175 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900176 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000177 log_fd: Option<&ParcelFileDescriptor>,
178 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000179 let mut is_protected = false;
180 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000181 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000182 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000183 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000184
Andrew Walbrandff3b942021-06-09 15:20:36 +0000185 /// Initialise an empty partition image of the given size to be used as a writable partition.
186 fn initializeWritablePartition(
187 &self,
188 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000189 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900190 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000191 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900192 check_manage_access()?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000193 let size_bytes = size_bytes.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000194 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000195 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokesff0005f2023-01-30 09:53:00 +0000196 Some(format!("Invalid size {}: {:?}", size_bytes, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000197 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000198 })?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000199 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000200 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900201 // initialize the file. Any data in the file will be erased.
202 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000203 Status::new_service_specific_error_str(
204 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100205 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900206 )
207 })?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000208 let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000209 Status::new_service_specific_error_str(
210 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100211 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000212 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000213 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000214
Jiyong Park9dd389e2021-08-23 20:42:59 +0900215 match partition_type {
216 PartitionType::RAW => Ok(()),
217 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000218 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900219 _ => Err(Error::new(
220 ErrorKind::Unsupported,
221 format!("Unsupported partition type {:?}", partition_type),
222 )),
223 }
224 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000225 Status::new_service_specific_error_str(
226 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100227 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900228 )
229 })?;
230
Andrew Walbrandff3b942021-06-09 15:20:36 +0000231 Ok(())
232 }
233
Jiyong Park0a248432021-08-20 23:32:39 +0900234 /// Creates or update the idsig file by digesting the input APK file.
235 fn createOrUpdateIdsigFile(
236 &self,
237 input_fd: &ParcelFileDescriptor,
238 idsig_fd: &ParcelFileDescriptor,
239 ) -> binder::Result<()> {
240 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
241 // idsig_fd is different from APK digest in input_fd
242
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900243 check_manage_access()?;
244
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000245 create_or_update_idsig_file(input_fd, idsig_fd)
246 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900247 Ok(())
248 }
249
Andrew Walbran320b5602021-03-04 16:11:12 +0000250 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
251 /// and as such is only permitted from the shell user.
252 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000253 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000254 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000255 }
256}
257
Jiyong Park8611a6c2021-07-09 18:17:44 +0900258impl VirtualizationService {
259 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000260 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900261 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000262
David Brazdil209074a2023-01-12 16:44:51 +0000263 fn create_vm_context(
264 &self,
265 requester_debug_pid: pid_t,
266 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000267 const NUM_ATTEMPTS: usize = 5;
268
269 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000270 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000271 let cid = vm_context.getCid()? as Cid;
272 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000273 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
274
275 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000276 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000277 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000278 Ok(vm_server) => {
279 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000280 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000281 }
282 Err(err) => {
283 warn!("Could not start RpcServer on port {}: {}", port, err);
284 }
285 }
286 }
David Brazdil209074a2023-01-12 16:44:51 +0000287 Err(Status::new_service_specific_error_str(
288 -1,
289 Some("Too many attempts to create VM context failed."),
290 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000291 }
292
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000293 fn create_vm_internal(
294 &self,
295 config: &VirtualMachineConfig,
296 console_fd: Option<&ParcelFileDescriptor>,
297 log_fd: Option<&ParcelFileDescriptor>,
298 is_protected: &mut bool,
299 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000300 let requester_uid = get_calling_uid();
301 let requester_debug_pid = get_calling_pid();
302
303 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
304 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900305
Alan Stokes7bc146c2022-10-20 17:10:32 +0100306 let is_custom = match config {
307 VirtualMachineConfig::RawConfig(_) => true,
308 VirtualMachineConfig::AppConfig(config) => {
309 // Some features are reserved for platform apps only, even when using
310 // VirtualMachineAppConfig:
311 // - controlling CPUs;
Nikita Ioffe5776f082023-02-10 21:38:26 +0000312 // - specifying a config file in the APK;
313 // - gdbPort is set, meaning that crosvm will start a gdb server.
314 !config.taskProfiles.is_empty()
315 || matches!(config.payload, Payload::ConfigPath(_))
316 || config.gdbPort > 0
Inseob Kim1119d702022-05-02 18:01:58 +0900317 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100318 };
319 if is_custom {
320 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900321 }
322
Nikita Ioffe5776f082023-02-10 21:38:26 +0000323 let gdb_port = extract_gdb_port(config);
324
325 // Additional permission checks if caller request gdb.
326 if gdb_port.is_some() {
327 check_gdb_allowed(config)?;
328 }
329
Jiyong Parked180932023-02-24 19:55:41 +0900330 let ramdump = if is_ramdump_needed(config) {
331 Some(prepare_ramdump_file(&temporary_directory)?)
332 } else {
333 None
334 };
335
Jaewan Kim84b91212023-02-28 00:11:57 +0900336 let debug_level = match config {
337 VirtualMachineConfig::AppConfig(app_config) => app_config.debugLevel,
338 _ => DebugLevel::NONE,
339 };
340
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000341 let state = &mut *self.state.lock().unwrap();
Inseob Kim0168b462022-12-27 14:54:35 +0900342 let console_fd =
343 clone_or_prepare_logger_fd(config, console_fd, format!("Console({})", cid))?;
344 let log_fd = clone_or_prepare_logger_fd(config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000345
346 // Counter to generate unique IDs for temporary image files.
347 let mut next_temporary_image_id = 0;
348 // Files which are referred to from composite images. These must be mapped to the crosvm
349 // child process, and not closed before it is started.
350 let mut indirect_files = vec![];
351
Alan Stokes7bc146c2022-10-20 17:10:32 +0100352 let (is_app_config, config) = match config {
353 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
354 VirtualMachineConfig::AppConfig(config) => {
355 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000356 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100357 let message = format!("Failed to load app config: {:?}", e);
358 error!("{}", message);
359 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100360 })?;
361 (true, BorrowedOrOwned::Owned(config))
362 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000363 };
364 let config = config.as_ref();
365 *is_protected = config.protectedVm;
366
367 // Check if partition images are labeled incorrectly. This is to prevent random images
368 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100369 // being loaded in a pVM. This applies to everything in the raw config, and everything but
370 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000371 config
372 .disks
373 .iter()
374 .flat_map(|disk| disk.partitions.iter())
375 .filter(|partition| {
376 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100377 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000378 } else {
379 true // all partitions are checked
380 }
381 })
382 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100383 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000384
Alan Stokes185fe112023-01-10 16:20:55 +0000385 let kernel = maybe_clone_file(&config.kernel)?;
386 let initrd = maybe_clone_file(&config.initrd)?;
387
388 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
389 if config.protectedVm {
390 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
391 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
392 })?;
393 }
394
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000395 let zero_filler_path = temporary_directory.join("zero.img");
396 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100397 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000398 Status::new_service_specific_error_str(
399 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100400 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000401 )
402 })?;
403
404 // Assemble disk images if needed.
405 let disks = config
406 .disks
407 .iter()
408 .map(|disk| {
409 assemble_disk_image(
410 disk,
411 &zero_filler_path,
412 &temporary_directory,
413 &mut next_temporary_image_id,
414 &mut indirect_files,
415 )
416 })
417 .collect::<Result<Vec<DiskFile>, _>>()?;
418
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000419 let (cpus, host_cpu_topology) = match config.cpuTopology {
420 CpuTopology::MATCH_HOST => (None, true),
421 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
422 val => {
423 error!("Unexpected value of CPU topology: {:?}", val);
424 return Err(Status::new_service_specific_error_str(
425 -1,
426 Some(format!("Failed to parse CPU topology value: {:?}", val)),
427 ));
428 }
429 };
430
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000431 // Actually start the VM.
432 let crosvm_config = CrosvmConfig {
433 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000434 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000435 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000436 kernel,
437 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000438 disks,
439 params: config.params.to_owned(),
440 protected: *is_protected,
Jaewan Kim84b91212023-02-28 00:11:57 +0900441 debug_level,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000442 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000443 cpus,
444 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900445 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000446 console_fd,
447 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900448 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000449 indirect_files,
450 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900451 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000452 gdb_port,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000453 };
454 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100455 VmInstance::new(
456 crosvm_config,
457 temporary_directory,
458 requester_uid,
459 requester_debug_pid,
460 vm_context,
461 )
462 .map_err(|e| {
463 error!("Failed to create VM with config {:?}: {:?}", config, e);
464 Status::new_service_specific_error_str(
465 -1,
466 Some(format!("Failed to create VM: {:?}", e)),
467 )
468 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000469 );
470 state.add_vm(Arc::downgrade(&instance));
471 Ok(VirtualMachine::create(instance))
472 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900473}
474
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000475fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900476 let file = OpenOptions::new()
477 .create_new(true)
478 .read(true)
479 .write(true)
480 .open(zero_filler_path)
481 .with_context(|| "Failed to create zero.img")?;
482 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000483 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900484}
485
Jiyong Park9dd389e2021-08-23 20:42:59 +0900486fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
487 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
488 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
489 part.flush()
490}
491
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000492fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
493 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
494 part.flush()
495}
496
Alan Stokesff0005f2023-01-30 09:53:00 +0000497fn round_up(input: u64, granularity: u64) -> u64 {
498 if granularity == 0 {
499 return input;
500 }
501 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
502 let result = input.checked_add(granularity - 1).unwrap_or(input);
503 (result / granularity) * granularity
504}
505
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000506/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
507///
508/// This may involve assembling a composite disk from a set of partition images.
509fn assemble_disk_image(
510 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900511 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000512 temporary_directory: &Path,
513 next_temporary_image_id: &mut u64,
514 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000515) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000516 let image = if !disk.partitions.is_empty() {
517 if disk.image.is_some() {
518 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000519 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000520 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000521 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000522 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000523 }
524
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000525 let composite_image_filenames =
526 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
527 let (image, partition_files) = make_composite_image(
528 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900529 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000530 &composite_image_filenames.composite,
531 &composite_image_filenames.header,
532 &composite_image_filenames.footer,
533 )
534 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100535 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000536 Status::new_service_specific_error_str(
537 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100538 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000539 )
540 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000541
542 // Pass the file descriptors for the various partition files to crosvm when it
543 // is run.
544 indirect_files.extend(partition_files);
545
546 image
547 } else if let Some(image) = &disk.image {
548 clone_file(image)?
549 } else {
550 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000551 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000552 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000553 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000554 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000555 };
556
557 Ok(DiskFile { image, writable: disk.writable })
558}
559
Jooyung Han21e9b922021-06-26 04:14:16 +0900560fn load_app_config(
561 config: &VirtualMachineAppConfig,
562 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900563) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000564 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
565 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900566 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900567
Shikha Panwar22e70452022-10-10 18:32:55 +0000568 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
569 Some(clone_file(file)?)
570 } else {
571 None
572 };
573
Alan Stokes0d1ef782022-09-27 13:46:35 +0100574 let vm_payload_config = match &config.payload {
575 Payload::ConfigPath(config_path) => {
576 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
577 .with_context(|| format!("Couldn't read config from {}", config_path))?
578 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000579 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100580 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900581
Alan Stokes0d1ef782022-09-27 13:46:35 +0100582 // For now, the only supported OS is Microdroid
583 let os_name = vm_payload_config.os.name.as_str();
584 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000585 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900586 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000587
588 // It is safe to construct a filename based on the os_name because we've already checked that it
589 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900590 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
591 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000592 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900593
Andrew Walbrancc045902021-07-27 16:06:17 +0000594 if config.memoryMib > 0 {
595 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000596 }
597
Seungjae Yoo62085c02022-08-12 04:44:52 +0000598 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000599 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000600 vm_config.cpuTopology = config.cpuTopology;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900601 vm_config.taskProfiles = config.taskProfiles.clone();
Nikita Ioffe5776f082023-02-10 21:38:26 +0000602 vm_config.gdbPort = config.gdbPort;
Jiyong Park032615f2022-01-10 13:55:34 +0900603
Shikha Panwar22e70452022-10-10 18:32:55 +0000604 // Microdroid takes additional init ramdisk & (optionally) storage image
605 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
606
607 // Include Microdroid payload disk (contains apks, idsigs) in vm config
608 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100609 config,
610 temporary_directory,
611 apk_file,
612 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100613 &vm_payload_config,
614 &mut vm_config,
615 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900616
Andrew Walbrancc0db522021-07-12 17:03:42 +0000617 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900618}
619
Alan Stokes0d1ef782022-09-27 13:46:35 +0100620fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
621 let mut apk_zip = ZipArchive::new(apk_file)?;
622 let config_file = apk_zip.by_name(config_path)?;
623 Ok(serde_json::from_reader(config_file)?)
624}
625
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000626fn create_vm_payload_config(
627 payload_config: &VirtualMachinePayloadConfig,
628) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100629 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
630 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
631 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000632
633 let payload_binary_name = &payload_config.payloadBinaryName;
634 if payload_binary_name.contains('/') {
635 bail!("Payload binary name must not specify a path: {payload_binary_name}");
636 }
637
638 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
639 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100640 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
641 task: Some(task),
642 apexes: vec![],
643 extra_apks: vec![],
644 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900645 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100646 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000647 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100648}
649
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000650/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000651fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000652 temporary_directory: &Path,
653 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000654) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000655 let id = *next_temporary_image_id;
656 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000657 CompositeImageFilenames {
658 composite: temporary_directory.join(format!("composite-{}.img", id)),
659 header: temporary_directory.join(format!("composite-{}-header.img", id)),
660 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
661 }
662}
663
664/// Filenames for a composite disk image, including header and footer partitions.
665#[derive(Clone, Debug, Eq, PartialEq)]
666struct CompositeImageFilenames {
667 /// The composite disk image itself.
668 composite: PathBuf,
669 /// The header partition image.
670 header: PathBuf,
671 /// The footer partition image.
672 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000673}
674
Jiyong Park753553b2021-07-12 21:21:09 +0900675/// Checks whether the caller has a specific permission
676fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100677 let calling_pid = get_calling_pid();
678 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900679 // Root can do anything
680 if calling_uid == 0 {
681 return Ok(());
682 }
683 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
684 binder::get_interface("permission")?;
685 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000686 Ok(())
687 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000688 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900689 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000690 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900691 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000692 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000693}
694
Jiyong Park753553b2021-07-12 21:21:09 +0900695/// Check whether the caller of the current Binder method is allowed to manage VMs
696fn check_manage_access() -> binder::Result<()> {
697 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
698}
699
Inseob Kim1119d702022-05-02 18:01:58 +0900700/// Check whether the caller of the current Binder method is allowed to create custom VMs
701fn check_use_custom_virtual_machine() -> binder::Result<()> {
702 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
703}
704
Alan Stokes185fe112023-01-10 16:20:55 +0000705/// Return whether a partition is exempt from selinux label checks, because we know that it does
706/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100707fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000708 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100709 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000710 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100711 || label == "microdroid-apk-idsig"
712 || label == "payload-metadata"
713 || label.starts_with("extra-idsig-")
714}
715
Alan Stokes185fe112023-01-10 16:20:55 +0000716/// Check that a file SELinux label is acceptable.
717///
718/// We only want to allow code in a VM to be sourced from places that apps, and the
719/// system, do not have write access to.
720///
721/// Note that sepolicy must also grant read access for these types to both virtualization
722/// service and crosvm.
723///
724/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
725/// user devices (W^X).
726fn check_label_is_allowed(context: &SeContext) -> Result<()> {
727 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100728 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100729 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000730 | "staging_data_file" // updated/staged APEX images
731 | "system_file" // immutable dm-verity protected partition
732 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100733 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000734 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900735 }
736}
737
Alan Stokes185fe112023-01-10 16:20:55 +0000738fn check_label_for_partition(partition: &Partition) -> Result<()> {
739 let file = partition.image.as_ref().unwrap().as_ref();
740 check_label_is_allowed(&getfilecon(file)?)
741 .with_context(|| format!("Partition {} invalid", &partition.label))
742}
743
744fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
745 if let Some(f) = kernel {
746 check_label_for_file(f, "kernel")?;
747 }
748 if let Some(f) = initrd {
749 check_label_for_file(f, "initrd")?;
750 }
751 Ok(())
752}
753fn check_label_for_file(file: &File, name: &str) -> Result<()> {
754 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
755}
756
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000757/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
758#[derive(Debug)]
759struct VirtualMachine {
760 instance: Arc<VmInstance>,
761}
762
763impl VirtualMachine {
764 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000765 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000766 }
767}
768
769impl Interface for VirtualMachine {}
770
771impl IVirtualMachine for VirtualMachine {
772 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900773 // Don't check permission. The owner of the VM might have passed this binder object to
774 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000775 Ok(self.instance.cid as i32)
776 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000777
Andrew Walbran6b650662021-09-07 13:13:23 +0000778 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900779 // Don't check permission. The owner of the VM might have passed this binder object to
780 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000781 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000782 }
783
784 fn registerCallback(
785 &self,
786 callback: &Strong<dyn IVirtualMachineCallback>,
787 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900788 // Don't check permission. The owner of the VM might have passed this binder object to
789 // others.
790 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000791 // TODO: Should this give an error if the VM is already dead?
792 self.instance.callbacks.add(callback.clone());
793 Ok(())
794 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000795
Andrew Walbranf8d94112021-09-07 11:45:36 +0000796 fn start(&self) -> binder::Result<()> {
797 self.instance.start().map_err(|e| {
798 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000799 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000800 })
801 }
802
Inseob Kima446f802022-07-11 19:46:37 +0900803 fn stop(&self) -> binder::Result<()> {
804 self.instance.kill().map_err(|e| {
805 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000806 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900807 })
808 }
809
Keir Frasercdd4b112022-11-24 14:02:25 +0000810 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
811 self.instance.trim_memory(level).map_err(|e| {
812 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
813 Status::new_service_specific_error_str(-1, Some(e.to_string()))
814 })
815 }
816
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000817 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000818 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000819 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000820 }
Alan Stokes10c47672022-12-13 17:17:08 +0000821 let port = port as u32;
822 if port < 1024 {
823 return Err(Status::new_service_specific_error_str(
824 -1,
825 Some(format!("Can't connect to privileged port {port}")),
826 ));
827 }
828 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
829 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
830 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000831 Ok(vsock_stream_to_pfd(stream))
832 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000833}
834
835impl Drop for VirtualMachine {
836 fn drop(&mut self) {
837 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900838 if let Err(e) = self.instance.kill() {
839 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
840 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000841 }
842}
843
844/// A set of Binders to be called back in response to various events on the VM, such as when it
845/// dies.
846#[derive(Debug, Default)]
847pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
848
849impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900850 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100851 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900852 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900853 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100854 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100855 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900856 }
857 }
858 }
859
Inseob Kim14cb8692021-08-31 21:50:39 +0900860 /// Call all registered callbacks to notify that the payload is ready to serve.
861 pub fn notify_payload_ready(&self, cid: Cid) {
862 let callbacks = &*self.0.lock().unwrap();
863 for callback in callbacks {
864 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100865 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900866 }
867 }
868 }
869
Inseob Kim2444af92021-08-31 01:22:50 +0900870 /// Call all registered callbacks to notify that the payload has finished.
871 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
872 let callbacks = &*self.0.lock().unwrap();
873 for callback in callbacks {
874 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100875 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900876 }
877 }
878 }
879
Jooyung Handd0a1732021-11-23 15:26:20 +0900880 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100881 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900882 let callbacks = &*self.0.lock().unwrap();
883 for callback in callbacks {
884 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100885 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900886 }
887 }
888 }
889
Andrew Walbrandae07162021-03-12 17:05:20 +0000890 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000891 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000892 let callbacks = &*self.0.lock().unwrap();
893 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000894 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100895 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000896 }
897 }
898 }
899
900 /// Add a new callback to the set.
901 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
902 self.0.lock().unwrap().push(callback);
903 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000904}
905
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000906/// The mutable state of the VirtualizationService. There should only be one instance of this
907/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800908#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000909struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000910 /// The VMs which have been started. When VMs are started a weak reference is added to this list
911 /// while a strong reference is returned to the caller over Binder. Once all copies of the
912 /// Binder client are dropped the weak reference here will become invalid, and will be removed
913 /// from the list opportunistically the next time `add_vm` is called.
914 vms: Vec<Weak<VmInstance>>,
915}
916
917impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000918 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000919 fn vms(&self) -> Vec<Arc<VmInstance>> {
920 // Attempt to upgrade the weak pointers to strong pointers.
921 self.vms.iter().filter_map(Weak::upgrade).collect()
922 }
923
924 /// Add a new VM to the list.
925 fn add_vm(&mut self, vm: Weak<VmInstance>) {
926 // Garbage collect any entries from the stored list which no longer exist.
927 self.vms.retain(|vm| vm.strong_count() > 0);
928
929 // Actually add the new VM.
930 self.vms.push(vm);
931 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000932
Jiyong Park8611a6c2021-07-09 18:17:44 +0900933 /// Get a VM that corresponds to the given cid
934 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
935 self.vms().into_iter().find(|vm| vm.cid == cid)
936 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900937}
938
Andrew Walbran6b650662021-09-07 13:13:23 +0000939/// Gets the `VirtualMachineState` of the given `VmInstance`.
940fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000941 match &*instance.vm_state.lock().unwrap() {
942 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
943 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000944 PayloadState::Starting => VirtualMachineState::STARTING,
945 PayloadState::Started => VirtualMachineState::STARTED,
946 PayloadState::Ready => VirtualMachineState::READY,
947 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900948 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000949 },
950 VmState::Dead => VirtualMachineState::DEAD,
951 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000952 }
953}
954
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000955/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000956pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000957 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000958 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000959 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100960 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000961 )
962 })
963}
964
Andrew Walbrand3a84182021-09-07 14:48:52 +0000965/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
966fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
967 file.as_ref().map(clone_file).transpose()
968}
969
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000970/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
971fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
972 // SAFETY: ownership is transferred from stream to f
973 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
974 ParcelFileDescriptor::new(f)
975}
976
Jiyong Parkdcf17412022-02-08 15:07:23 +0900977/// Parses the platform version requirement string.
978fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
979 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000980 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +0900981 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100982 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +0900983 )
984 })
985}
986
Jiyong Parked180932023-02-24 19:55:41 +0900987/// Create the empty ramdump file
988fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
989 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
990 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
991 // owner) for readout.
992 let ramdump_path = temporary_directory.join("ramdump");
993 let ramdump = File::create(ramdump_path).map_err(|e| {
994 error!("Failed to prepare ramdump file: {:?}", e);
995 Status::new_service_specific_error_str(
996 -1,
997 Some(format!("Failed to prepare ramdump file: {:?}", e)),
998 )
999 })?;
1000 Ok(ramdump)
1001}
1002
Nikita Ioffe5776f082023-02-10 21:38:26 +00001003fn is_protected(config: &VirtualMachineConfig) -> bool {
1004 match config {
1005 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1006 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1007 }
1008}
1009
1010fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1011 if is_protected(config) {
1012 return Err(Status::new_exception_str(
1013 ExceptionCode::SECURITY,
1014 Some("can't use gdb with protected VMs"),
1015 ));
1016 }
1017
1018 match config {
1019 VirtualMachineConfig::RawConfig(_) => Ok(()),
1020 VirtualMachineConfig::AppConfig(config) => {
1021 if config.debugLevel != DebugLevel::FULL {
1022 Err(Status::new_exception_str(
1023 ExceptionCode::SECURITY,
1024 Some("can't use gdb with non-debuggable VMs"),
1025 ))
1026 } else {
1027 Ok(())
1028 }
1029 }
1030 }
1031}
1032
1033fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1034 match config {
1035 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1036 VirtualMachineConfig::AppConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1037 }
1038}
1039
Inseob Kim0168b462022-12-27 14:54:35 +09001040fn clone_or_prepare_logger_fd(
1041 config: &VirtualMachineConfig,
1042 fd: Option<&ParcelFileDescriptor>,
1043 tag: String,
1044) -> Result<Option<File>, Status> {
1045 if let Some(fd) = fd {
1046 return Ok(Some(clone_file(fd)?));
1047 }
1048
Jaewan Kim66f062e2023-02-25 01:07:43 +09001049 let VirtualMachineConfig::AppConfig(app_config) = config else {
Inseob Kim0168b462022-12-27 14:54:35 +09001050 return Ok(None);
Jaewan Kim66f062e2023-02-25 01:07:43 +09001051 };
1052 if !should_prepare_console_output(app_config.debugLevel) {
1053 return Ok(None);
1054 };
Inseob Kim0168b462022-12-27 14:54:35 +09001055
1056 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
1057 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
1058 })?;
1059
1060 // SAFETY: We are the sole owners of these fds as they were just created.
1061 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
1062 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1063
1064 std::thread::spawn(move || loop {
1065 let mut buf = vec![];
1066 match reader.read_until(b'\n', &mut buf) {
1067 Ok(0) => {
1068 // EOF
1069 return;
1070 }
1071 Ok(size) => {
1072 if buf[size - 1] == b'\n' {
1073 buf.pop();
1074 }
1075 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1076 }
1077 Err(e) => {
1078 error!("Could not read console pipe: {:?}", e);
1079 return;
1080 }
1081 };
1082 });
1083
1084 Ok(Some(write_fd))
1085}
1086
Jooyung Han35edb8f2021-07-01 16:17:16 +09001087/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1088/// it doesn't require that T implements Clone.
1089enum BorrowedOrOwned<'a, T> {
1090 Borrowed(&'a T),
1091 Owned(T),
1092}
1093
1094impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1095 fn as_ref(&self) -> &T {
1096 match self {
1097 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001098 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001099 }
1100 }
1101}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001102
1103/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1104#[derive(Debug, Default)]
1105struct VirtualMachineService {
1106 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001107 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001108}
1109
1110impl Interface for VirtualMachineService {}
1111
1112impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001113 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1114 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001115 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001116 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001117 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1118 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1119 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001120 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001121
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001122 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1123 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001124 Ok(())
1125 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001126 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001127 Err(Status::new_service_specific_error_str(
1128 -1,
1129 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001130 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001131 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001132 }
Inseob Kim2444af92021-08-31 01:22:50 +09001133
Inseob Kimc7d28c72021-10-25 14:28:10 +00001134 fn notifyPayloadReady(&self) -> binder::Result<()> {
1135 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001136 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001137 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001138 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1139 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1140 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001141 vm.callbacks.notify_payload_ready(cid);
1142 Ok(())
1143 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001144 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001145 Err(Status::new_service_specific_error_str(
1146 -1,
1147 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001148 ))
1149 }
1150 }
1151
Inseob Kimc7d28c72021-10-25 14:28:10 +00001152 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1153 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001154 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001155 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001156 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1157 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1158 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001159 vm.callbacks.notify_payload_finished(cid, exit_code);
1160 Ok(())
1161 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001162 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001163 Err(Status::new_service_specific_error_str(
1164 -1,
1165 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001166 ))
1167 }
1168 }
1169
Alan Stokes2bead0d2022-09-05 16:58:34 +01001170 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001171 let cid = self.cid;
1172 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001173 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001174 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1175 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1176 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001177 vm.callbacks.notify_error(cid, error_code, message);
1178 Ok(())
1179 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001180 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001181 Err(Status::new_service_specific_error_str(
1182 -1,
1183 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001184 ))
1185 }
1186 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001187}
1188
1189impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001190 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001191 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001192 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001193 BinderFeatures::default(),
1194 )
1195 }
1196}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001197
1198#[cfg(test)]
1199mod tests {
1200 use super::*;
1201
1202 #[test]
1203 fn test_is_allowed_label_for_partition() -> Result<()> {
1204 let expected_results = vec![
1205 ("u:object_r:system_file:s0", true),
1206 ("u:object_r:apk_data_file:s0", true),
1207 ("u:object_r:app_data_file:s0", false),
1208 ("u:object_r:app_data_file:s0:c512,c768", false),
1209 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1210 ("invalid", false),
1211 ("user:role:apk_data_file:severity:categories", true),
1212 ("user:role:apk_data_file:severity:categories:extraneous", false),
1213 ];
1214
1215 for (label, expected_valid) in expected_results {
1216 let context = SeContext::new(label)?;
1217 let result = check_label_is_allowed(&context);
1218 if expected_valid {
1219 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1220 } else if result.is_ok() {
1221 bail!("Expected label {} to be disallowed", label);
1222 }
1223 }
1224 Ok(())
1225 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001226
1227 #[test]
1228 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1229 let apk = tempfile::tempfile().unwrap();
1230 let idsig = tempfile::tempfile().unwrap();
1231
1232 let ret = create_or_update_idsig_file(
1233 &ParcelFileDescriptor::new(apk),
1234 &ParcelFileDescriptor::new(idsig),
1235 );
1236 assert!(ret.is_err(), "should fail");
1237 Ok(())
1238 }
1239
1240 #[test]
1241 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1242 let tmp_dir = tempfile::TempDir::new().unwrap();
1243 let apk = File::open(tmp_dir.path()).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 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1255 /// on ext4 filesystem is passed.
1256 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1257 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1258 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1259 #[test]
1260 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1261 // APEXes are backed by the ext4.
1262 let apk = File::open("/apex/com.android.virt/").unwrap();
1263 let idsig = tempfile::tempfile().unwrap();
1264
1265 let ret = create_or_update_idsig_file(
1266 &ParcelFileDescriptor::new(apk),
1267 &ParcelFileDescriptor::new(idsig),
1268 );
1269 assert!(ret.is_err(), "should fail");
1270 Ok(())
1271 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001272}