blob: 1ddf129b78d4dcaa28a31c6efdcd48c9c1caafaa [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,
Nikita Ioffef7c742a2023-09-04 16:57:59 +010037 IVirtualizationService::FEATURE_PAYLOAD_NON_ROOT,
Keir Frasercdd4b112022-11-24 14:02:25 +000038 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090039 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000040 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090041 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090042 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000043 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010044 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090045 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000046 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090047};
David Brazdilafc9a9e2023-01-12 16:08:10 +000048use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090049use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000050 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090051};
Alan Stokes25f69362023-03-06 16:51:54 +000052use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090053use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090054use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010055use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000056 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
57 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090058 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000059};
David Brazdilf50c7a62023-04-19 14:22:42 +000060use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000061use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000062use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090063use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090064use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000065use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000066use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090067use semver::VersionReq;
Inseob Kim6ef80972023-07-20 17:23:36 +090068use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000069use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000070use std::ffi::CStr;
Inseob Kim6ef80972023-07-20 17:23:36 +090071use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000072use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000073use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000074use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000075use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000076use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000077use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000078use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000079use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090080use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000081
David Brazdil41d1a872022-10-05 14:44:19 +010082/// The unique ID of a VM used (together with a port number) for vsock communication.
83pub type Cid = u32;
84
David Brazdil4b4c5102022-12-19 22:56:20 +000085pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
86
Jooyung Han95884632021-07-06 22:27:54 +090087/// The size of zero.img.
88/// Gaps in composite disk images are filled with a shared zero.img.
89const ZERO_FILLER_SIZE: u64 = 4096;
90
David Brazdilf50c7a62023-04-19 14:22:42 +000091/// Magic string for the instance image
92const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
93
94/// Version of the instance image format
95const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
96
Alan Stokes0d1ef782022-09-27 13:46:35 +010097const MICRODROID_OS_NAME: &str = "microdroid";
98
David Brazdilf50c7a62023-04-19 14:22:42 +000099const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
100
101/// crosvm requires all partitions to be a multiple of 4KiB.
102const PARTITION_GRANULARITY_BYTES: u64 = 4096;
103
David Brazdil49f96f52022-12-16 21:29:13 +0000104lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000105 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
106 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
107 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000108}
109
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000110fn create_or_update_idsig_file(
111 input_fd: &ParcelFileDescriptor,
112 idsig_fd: &ParcelFileDescriptor,
113) -> Result<()> {
114 let mut input = clone_file(input_fd)?;
115 let metadata = input.metadata().context("failed to get input metadata")?;
116 if !metadata.is_file() {
117 bail!("input is not a regular file");
118 }
Alan Stokes25f69362023-03-06 16:51:54 +0000119 let mut sig =
120 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
121 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000122
123 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900124
125 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
126 // if the idsig file already has the same APK digest.
127 if output.metadata()?.len() > 0 {
128 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
129 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
130 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
131 return Ok(());
132 }
133 }
134 // if we fail to read v4signature from output, that's fine. User can pass a random file.
135 // We will anyway overwrite the file to the v4signature generated from input_fd.
136 }
137
Nikita Ioffec09b0492022-12-14 20:18:33 +0000138 output.set_len(0).context("failed to set_len on the idsig output")?;
139 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000140 Ok(())
141}
142
Alan Stokes25f69362023-03-06 16:51:54 +0000143fn get_current_sdk() -> Result<u32> {
144 let current_sdk = system_properties::read("ro.build.version.sdk")?;
145 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
146 current_sdk.parse().context("Malformed SDK version")
147}
148
David Brazdil4b4c5102022-12-19 22:56:20 +0000149pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
150 for dir_entry in read_dir(path)? {
151 remove_file(dir_entry?.path())?;
152 }
153 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100154}
155
David Brazdil528e0472022-10-10 15:06:02 +0100156/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000157#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000158pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900159 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000160}
161
Shikha Panward8e35422021-10-11 13:51:27 +0000162impl Interface for VirtualizationService {
163 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
164 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
165 let state = &mut *self.state.lock().unwrap();
166 let vms = state.vms();
167 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
168 for vm in vms {
169 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
170 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
171 .or(Err(StatusCode::UNKNOWN_ERROR))?;
172 writeln!(file, "\tPayload state {:?}", vm.payload_state())
173 .or(Err(StatusCode::UNKNOWN_ERROR))?;
174 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
175 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
176 .or(Err(StatusCode::UNKNOWN_ERROR))?;
177 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
178 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000179 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
180 .or(Err(StatusCode::UNKNOWN_ERROR))?;
181 }
182 Ok(())
183 }
184}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000185impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000186 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
187 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000188 ///
189 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000190 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000191 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000192 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900193 console_out_fd: Option<&ParcelFileDescriptor>,
194 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000195 log_fd: Option<&ParcelFileDescriptor>,
196 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000197 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900198 let ret = self.create_vm_internal(
199 config,
200 console_out_fd,
201 console_in_fd,
202 log_fd,
203 &mut is_protected,
204 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000205 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000206 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000207 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000208
Andrew Walbrandff3b942021-06-09 15:20:36 +0000209 /// Initialise an empty partition image of the given size to be used as a writable partition.
210 fn initializeWritablePartition(
211 &self,
212 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000213 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900214 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000215 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900216 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900217 let size_bytes = size_bytes
218 .try_into()
219 .with_context(|| format!("Invalid size: {}", size_bytes))
220 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000221 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
222 let image = clone_file(image_fd)?;
223 // initialize the file. Any data in the file will be erased.
Jiyong Park2227eaa2023-08-04 11:59:18 +0900224 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
225 let mut part = QcowFile::new(image, size_bytes)
226 .context("Failed to create QCOW2 image")
227 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000228
229 match partition_type {
230 PartitionType::RAW => Ok(()),
231 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
232 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
233 _ => Err(Error::new(
234 ErrorKind::Unsupported,
235 format!("Unsupported partition type {:?}", partition_type),
236 )),
237 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900238 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
239 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000240
241 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000242 }
243
Jiyong Park0a248432021-08-20 23:32:39 +0900244 /// Creates or update the idsig file by digesting the input APK file.
245 fn createOrUpdateIdsigFile(
246 &self,
247 input_fd: &ParcelFileDescriptor,
248 idsig_fd: &ParcelFileDescriptor,
249 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900250 check_manage_access()?;
251
Jiyong Park2227eaa2023-08-04 11:59:18 +0900252 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900253 Ok(())
254 }
255
Andrew Walbran320b5602021-03-04 16:11:12 +0000256 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
257 /// and as such is only permitted from the shell user.
258 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000259 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000260 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000261 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900262
263 /// Get a list of assignable device types.
264 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
265 // Delegate to the global service, including checking the permission.
266 GLOBAL_SERVICE.getAssignableDevices()
267 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100268
269 /// Returns whether given feature is enabled
270 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
271 check_manage_access()?;
272
273 // This approach is quite cumbersome, but will do the work for the short term.
274 // TODO(b/298012279): make this scalable.
275 match feature {
276 FEATURE_PAYLOAD_NON_ROOT => Ok(cfg!(payload_not_root)),
277 _ => {
278 warn!("unknown feature {}", feature);
279 Ok(false)
280 }
281 }
282 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000283}
284
Jiyong Park8611a6c2021-07-09 18:17:44 +0900285impl VirtualizationService {
286 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000287 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900288 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000289
David Brazdil209074a2023-01-12 16:44:51 +0000290 fn create_vm_context(
291 &self,
292 requester_debug_pid: pid_t,
293 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000294 const NUM_ATTEMPTS: usize = 5;
295
296 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000297 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000298 let cid = vm_context.getCid()? as Cid;
299 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000300 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
301
302 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000303 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000304 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000305 Ok(vm_server) => {
306 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000307 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000308 }
309 Err(err) => {
310 warn!("Could not start RpcServer on port {}: {}", port, err);
311 }
312 }
313 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900314 Err(anyhow!("Too many attempts to create VM context failed"))
315 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000316 }
317
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000318 fn create_vm_internal(
319 &self,
320 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900321 console_out_fd: Option<&ParcelFileDescriptor>,
322 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000323 log_fd: Option<&ParcelFileDescriptor>,
324 is_protected: &mut bool,
325 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000326 let requester_uid = get_calling_uid();
327 let requester_debug_pid = get_calling_pid();
328
329 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
330 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900331
Alan Stokes7bc146c2022-10-20 17:10:32 +0100332 let is_custom = match config {
333 VirtualMachineConfig::RawConfig(_) => true,
334 VirtualMachineConfig::AppConfig(config) => {
335 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100336 // VirtualMachineAppConfig. Almost all of these features are grouped in the
337 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100338 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100339 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100340 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900341 // - using anything other than the default kernel;
342 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100343 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900344 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100345 };
346 if is_custom {
347 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900348 }
349
Nikita Ioffe5776f082023-02-10 21:38:26 +0000350 let gdb_port = extract_gdb_port(config);
351
352 // Additional permission checks if caller request gdb.
353 if gdb_port.is_some() {
354 check_gdb_allowed(config)?;
355 }
356
Jaewan Kim61f86142023-03-28 15:12:52 +0900357 let debug_level = match config {
358 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
359 _ => DebugLevel::NONE,
360 };
361 let debug_config = DebugConfig::new(debug_level);
362
363 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900364 Some(prepare_ramdump_file(&temporary_directory)?)
365 } else {
366 None
367 };
368
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000369 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900370 let console_out_fd =
371 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
372 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900373 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000374
375 // Counter to generate unique IDs for temporary image files.
376 let mut next_temporary_image_id = 0;
377 // Files which are referred to from composite images. These must be mapped to the crosvm
378 // child process, and not closed before it is started.
379 let mut indirect_files = vec![];
380
Alan Stokes7bc146c2022-10-20 17:10:32 +0100381 let (is_app_config, config) = match config {
382 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
383 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900384 let config = load_app_config(config, &debug_config, &temporary_directory)
385 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900386 *is_protected = config.protectedVm;
387 let message = format!("Failed to load app config: {:?}", e);
388 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900389 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900390 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100391 (true, BorrowedOrOwned::Owned(config))
392 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000393 };
394 let config = config.as_ref();
395 *is_protected = config.protectedVm;
396
397 // Check if partition images are labeled incorrectly. This is to prevent random images
398 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100399 // being loaded in a pVM. This applies to everything in the raw config, and everything but
400 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000401 config
402 .disks
403 .iter()
404 .flat_map(|disk| disk.partitions.iter())
405 .filter(|partition| {
406 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100407 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000408 } else {
409 true // all partitions are checked
410 }
411 })
412 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900413 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000414
Alan Stokes185fe112023-01-10 16:20:55 +0000415 let kernel = maybe_clone_file(&config.kernel)?;
416 let initrd = maybe_clone_file(&config.initrd)?;
417
418 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
419 if config.protectedVm {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900420 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Alan Stokes185fe112023-01-10 16:20:55 +0000421 }
422
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000423 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900424 write_zero_filler(&zero_filler_path)
425 .context("Failed to make composite image")
426 .with_log()
427 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000428
429 // Assemble disk images if needed.
430 let disks = config
431 .disks
432 .iter()
433 .map(|disk| {
434 assemble_disk_image(
435 disk,
436 &zero_filler_path,
437 &temporary_directory,
438 &mut next_temporary_image_id,
439 &mut indirect_files,
440 )
441 })
442 .collect::<Result<Vec<DiskFile>, _>>()?;
443
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000444 let (cpus, host_cpu_topology) = match config.cpuTopology {
445 CpuTopology::MATCH_HOST => (None, true),
446 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
447 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900448 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
449 .with_log()
450 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000451 }
452 };
453
Inseob Kim6ef80972023-07-20 17:23:36 +0900454 let devices_dtbo = if !config.devices.is_empty() {
455 let mut set = HashSet::new();
456 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900457 let path = canonicalize(device)
458 .with_context(|| format!("can't canonicalize {device}"))
459 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900460 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900461 return Err(anyhow!("duplicated device {device}"))
462 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900463 }
464 }
Inseob Kimf36347b2023-08-03 12:52:48 +0900465 let dtbo_path = temporary_directory.join("dtbo");
466 // open a writable file descriptor for vfio_handler
467 let dtbo = File::create(&dtbo_path).map_err(|e| {
468 error!("Failed to create VM DTBO file {dtbo_path:?}: {e:?}");
469 Status::new_service_specific_error_str(
470 -1,
471 Some(format!("Failed to create VM DTBO file {dtbo_path:?}: {e:?}")),
472 )
473 })?;
474 GLOBAL_SERVICE
475 .bindDevicesToVfioDriver(&config.devices, &ParcelFileDescriptor::new(dtbo))?;
476
477 // open (again) a readable file descriptor for crosvm
478 let dtbo = File::open(&dtbo_path).map_err(|e| {
479 error!("Failed to open VM DTBO file {dtbo_path:?}: {e:?}");
480 Status::new_service_specific_error_str(
481 -1,
482 Some(format!("Failed to open VM DTBO file {dtbo_path:?}: {e:?}")),
483 )
484 })?;
485 Some(dtbo)
Inseob Kim6ef80972023-07-20 17:23:36 +0900486 } else {
487 None
488 };
489
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000490 // Actually start the VM.
491 let crosvm_config = CrosvmConfig {
492 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000493 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000494 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000495 kernel,
496 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000497 disks,
498 params: config.params.to_owned(),
499 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900500 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000501 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000502 cpus,
503 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900504 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900505 console_out_fd,
506 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000507 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900508 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000509 indirect_files,
510 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900511 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000512 gdb_port,
Inseob Kim6ef80972023-07-20 17:23:36 +0900513 vfio_devices: config.devices.iter().map(PathBuf::from).collect(),
514 devices_dtbo,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000515 };
516 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100517 VmInstance::new(
518 crosvm_config,
519 temporary_directory,
520 requester_uid,
521 requester_debug_pid,
522 vm_context,
523 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900524 .with_context(|| format!("Failed to create VM with config {:?}", config))
525 .with_log()
526 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000527 );
528 state.add_vm(Arc::downgrade(&instance));
529 Ok(VirtualMachine::create(instance))
530 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900531}
532
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000533fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900534 let file = OpenOptions::new()
535 .create_new(true)
536 .read(true)
537 .write(true)
538 .open(zero_filler_path)
539 .with_context(|| "Failed to create zero.img")?;
540 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000541 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900542}
543
David Brazdilf50c7a62023-04-19 14:22:42 +0000544fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
545 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
546 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
547 part.flush()
548}
549
550fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
551 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
552 part.flush()
553}
554
555fn round_up(input: u64, granularity: u64) -> u64 {
556 if granularity == 0 {
557 return input;
558 }
559 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
560 let result = input.checked_add(granularity - 1).unwrap_or(input);
561 (result / granularity) * granularity
562}
563
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000564/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
565///
566/// This may involve assembling a composite disk from a set of partition images.
567fn assemble_disk_image(
568 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900569 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000570 temporary_directory: &Path,
571 next_temporary_image_id: &mut u64,
572 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000573) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000574 let image = if !disk.partitions.is_empty() {
575 if disk.image.is_some() {
576 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900577 return Err(anyhow!("DiskImage contains both image and partitions"))
578 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000579 }
580
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000581 let composite_image_filenames =
582 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
583 let (image, partition_files) = make_composite_image(
584 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900585 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000586 &composite_image_filenames.composite,
587 &composite_image_filenames.header,
588 &composite_image_filenames.footer,
589 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900590 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
591 .with_log()
592 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000593
594 // Pass the file descriptors for the various partition files to crosvm when it
595 // is run.
596 indirect_files.extend(partition_files);
597
598 image
599 } else if let Some(image) = &disk.image {
600 clone_file(image)?
601 } else {
602 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900603 return Err(anyhow!("DiskImage didn't contain image or partitions."))
604 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000605 };
606
607 Ok(DiskFile { image, writable: disk.writable })
608}
609
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100610fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
611 if let Some(ref mut params) = vm_config.params {
612 params.push(' ');
613 params.push_str(param)
614 } else {
615 vm_config.params = Some(param.to_owned())
616 }
617}
618
Jooyung Han21e9b922021-06-26 04:14:16 +0900619fn load_app_config(
620 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900621 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900622 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900623) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000624 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
625 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900626 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900627
Shikha Panwar22e70452022-10-10 18:32:55 +0000628 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
629 Some(clone_file(file)?)
630 } else {
631 None
632 };
633
Alan Stokes0d1ef782022-09-27 13:46:35 +0100634 let vm_payload_config = match &config.payload {
635 Payload::ConfigPath(config_path) => {
636 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
637 .with_context(|| format!("Couldn't read config from {}", config_path))?
638 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000639 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100640 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900641
Alan Stokes0d1ef782022-09-27 13:46:35 +0100642 // For now, the only supported OS is Microdroid
643 let os_name = vm_payload_config.os.name.as_str();
644 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000645 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900646 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000647
648 // It is safe to construct a filename based on the os_name because we've already checked that it
649 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900650 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
651 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000652 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900653
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100654 if let Some(custom_config) = &config.customConfig {
655 if let Some(file) = custom_config.customKernelImage.as_ref() {
656 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
657 }
658 vm_config.taskProfiles = custom_config.taskProfiles.clone();
659 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100660
661 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100662 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
663 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100664 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900665
666 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100667 }
668
Andrew Walbrancc045902021-07-27 16:06:17 +0000669 if config.memoryMib > 0 {
670 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000671 }
672
Seungjae Yoo62085c02022-08-12 04:44:52 +0000673 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000674 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000675 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900676
Shikha Panwar22e70452022-10-10 18:32:55 +0000677 // Microdroid takes additional init ramdisk & (optionally) storage image
678 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
679
680 // Include Microdroid payload disk (contains apks, idsigs) in vm config
681 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100682 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900683 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100684 temporary_directory,
685 apk_file,
686 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100687 &vm_payload_config,
688 &mut vm_config,
689 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900690
Andrew Walbrancc0db522021-07-12 17:03:42 +0000691 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900692}
693
Alan Stokes0d1ef782022-09-27 13:46:35 +0100694fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
695 let mut apk_zip = ZipArchive::new(apk_file)?;
696 let config_file = apk_zip.by_name(config_path)?;
697 Ok(serde_json::from_reader(config_file)?)
698}
699
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000700fn create_vm_payload_config(
701 payload_config: &VirtualMachinePayloadConfig,
702) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100703 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
704 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
705 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000706
707 let payload_binary_name = &payload_config.payloadBinaryName;
708 if payload_binary_name.contains('/') {
709 bail!("Payload binary name must not specify a path: {payload_binary_name}");
710 }
711
712 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
713 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100714 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
715 task: Some(task),
716 apexes: vec![],
717 extra_apks: vec![],
718 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900719 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100720 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000721 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100722}
723
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000724/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000725fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000726 temporary_directory: &Path,
727 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000728) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000729 let id = *next_temporary_image_id;
730 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000731 CompositeImageFilenames {
732 composite: temporary_directory.join(format!("composite-{}.img", id)),
733 header: temporary_directory.join(format!("composite-{}-header.img", id)),
734 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
735 }
736}
737
738/// Filenames for a composite disk image, including header and footer partitions.
739#[derive(Clone, Debug, Eq, PartialEq)]
740struct CompositeImageFilenames {
741 /// The composite disk image itself.
742 composite: PathBuf,
743 /// The header partition image.
744 header: PathBuf,
745 /// The footer partition image.
746 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000747}
748
Jiyong Park753553b2021-07-12 21:21:09 +0900749/// Checks whether the caller has a specific permission
750fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100751 let calling_pid = get_calling_pid();
752 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900753 // Root can do anything
754 if calling_uid == 0 {
755 return Ok(());
756 }
757 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
758 binder::get_interface("permission")?;
759 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000760 Ok(())
761 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900762 Err(anyhow!("does not have the {} permission", perm))
763 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000764 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000765}
766
Jiyong Park753553b2021-07-12 21:21:09 +0900767/// Check whether the caller of the current Binder method is allowed to manage VMs
768fn check_manage_access() -> binder::Result<()> {
769 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
770}
771
Inseob Kim1119d702022-05-02 18:01:58 +0900772/// Check whether the caller of the current Binder method is allowed to create custom VMs
773fn check_use_custom_virtual_machine() -> binder::Result<()> {
774 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
775}
776
Alan Stokes185fe112023-01-10 16:20:55 +0000777/// Return whether a partition is exempt from selinux label checks, because we know that it does
778/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100779fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000780 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100781 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000782 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100783 || label == "microdroid-apk-idsig"
784 || label == "payload-metadata"
785 || label.starts_with("extra-idsig-")
786}
787
Alan Stokes185fe112023-01-10 16:20:55 +0000788/// Check that a file SELinux label is acceptable.
789///
790/// We only want to allow code in a VM to be sourced from places that apps, and the
791/// system, do not have write access to.
792///
793/// Note that sepolicy must also grant read access for these types to both virtualization
794/// service and crosvm.
795///
796/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
797/// user devices (W^X).
798fn check_label_is_allowed(context: &SeContext) -> Result<()> {
799 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100800 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100801 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000802 | "staging_data_file" // updated/staged APEX images
803 | "system_file" // immutable dm-verity protected partition
804 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100805 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000806 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900807 }
808}
809
Alan Stokes185fe112023-01-10 16:20:55 +0000810fn check_label_for_partition(partition: &Partition) -> Result<()> {
811 let file = partition.image.as_ref().unwrap().as_ref();
812 check_label_is_allowed(&getfilecon(file)?)
813 .with_context(|| format!("Partition {} invalid", &partition.label))
814}
815
816fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
817 if let Some(f) = kernel {
818 check_label_for_file(f, "kernel")?;
819 }
820 if let Some(f) = initrd {
821 check_label_for_file(f, "initrd")?;
822 }
823 Ok(())
824}
825fn check_label_for_file(file: &File, name: &str) -> Result<()> {
826 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
827}
828
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000829/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
830#[derive(Debug)]
831struct VirtualMachine {
832 instance: Arc<VmInstance>,
833}
834
835impl VirtualMachine {
836 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000837 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000838 }
839}
840
841impl Interface for VirtualMachine {}
842
843impl IVirtualMachine for VirtualMachine {
844 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900845 // Don't check permission. The owner of the VM might have passed this binder object to
846 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000847 Ok(self.instance.cid as i32)
848 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000849
Andrew Walbran6b650662021-09-07 13:13:23 +0000850 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900851 // Don't check permission. The owner of the VM might have passed this binder object to
852 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000853 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000854 }
855
856 fn registerCallback(
857 &self,
858 callback: &Strong<dyn IVirtualMachineCallback>,
859 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900860 // Don't check permission. The owner of the VM might have passed this binder object to
861 // others.
862 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000863 // TODO: Should this give an error if the VM is already dead?
864 self.instance.callbacks.add(callback.clone());
865 Ok(())
866 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000867
Andrew Walbranf8d94112021-09-07 11:45:36 +0000868 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900869 self.instance
870 .start()
871 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
872 .with_log()
873 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000874 }
875
Inseob Kima446f802022-07-11 19:46:37 +0900876 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900877 self.instance
878 .kill()
879 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
880 .with_log()
881 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +0900882 }
883
Keir Frasercdd4b112022-11-24 14:02:25 +0000884 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900885 self.instance
886 .trim_memory(level)
887 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
888 .with_log()
889 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +0000890 }
891
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000892 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000893 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900894 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000895 }
Alan Stokes10c47672022-12-13 17:17:08 +0000896 let port = port as u32;
897 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900898 return Err(anyhow!("Can't connect to privileged port {port}"))
899 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +0000900 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900901 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
902 .context("Failed to connect")
903 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000904 Ok(vsock_stream_to_pfd(stream))
905 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000906}
907
908impl Drop for VirtualMachine {
909 fn drop(&mut self) {
910 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900911 if let Err(e) = self.instance.kill() {
912 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
913 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000914 }
915}
916
917/// A set of Binders to be called back in response to various events on the VM, such as when it
918/// dies.
919#[derive(Debug, Default)]
920pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
921
922impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900923 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100924 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900925 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900926 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100927 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100928 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900929 }
930 }
931 }
932
Inseob Kim14cb8692021-08-31 21:50:39 +0900933 /// Call all registered callbacks to notify that the payload is ready to serve.
934 pub fn notify_payload_ready(&self, cid: Cid) {
935 let callbacks = &*self.0.lock().unwrap();
936 for callback in callbacks {
937 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100938 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900939 }
940 }
941 }
942
Inseob Kim2444af92021-08-31 01:22:50 +0900943 /// Call all registered callbacks to notify that the payload has finished.
944 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
945 let callbacks = &*self.0.lock().unwrap();
946 for callback in callbacks {
947 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100948 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900949 }
950 }
951 }
952
Jooyung Handd0a1732021-11-23 15:26:20 +0900953 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100954 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900955 let callbacks = &*self.0.lock().unwrap();
956 for callback in callbacks {
957 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100958 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900959 }
960 }
961 }
962
Andrew Walbrandae07162021-03-12 17:05:20 +0000963 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000964 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000965 let callbacks = &*self.0.lock().unwrap();
966 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000967 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100968 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000969 }
970 }
971 }
972
973 /// Add a new callback to the set.
974 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
975 self.0.lock().unwrap().push(callback);
976 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000977}
978
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000979/// The mutable state of the VirtualizationService. There should only be one instance of this
980/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800981#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000982struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000983 /// The VMs which have been started. When VMs are started a weak reference is added to this list
984 /// while a strong reference is returned to the caller over Binder. Once all copies of the
985 /// Binder client are dropped the weak reference here will become invalid, and will be removed
986 /// from the list opportunistically the next time `add_vm` is called.
987 vms: Vec<Weak<VmInstance>>,
988}
989
990impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000991 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000992 fn vms(&self) -> Vec<Arc<VmInstance>> {
993 // Attempt to upgrade the weak pointers to strong pointers.
994 self.vms.iter().filter_map(Weak::upgrade).collect()
995 }
996
997 /// Add a new VM to the list.
998 fn add_vm(&mut self, vm: Weak<VmInstance>) {
999 // Garbage collect any entries from the stored list which no longer exist.
1000 self.vms.retain(|vm| vm.strong_count() > 0);
1001
1002 // Actually add the new VM.
1003 self.vms.push(vm);
1004 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001005
Jiyong Park8611a6c2021-07-09 18:17:44 +09001006 /// Get a VM that corresponds to the given cid
1007 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1008 self.vms().into_iter().find(|vm| vm.cid == cid)
1009 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001010}
1011
Andrew Walbran6b650662021-09-07 13:13:23 +00001012/// Gets the `VirtualMachineState` of the given `VmInstance`.
1013fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001014 match &*instance.vm_state.lock().unwrap() {
1015 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1016 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001017 PayloadState::Starting => VirtualMachineState::STARTING,
1018 PayloadState::Started => VirtualMachineState::STARTED,
1019 PayloadState::Ready => VirtualMachineState::READY,
1020 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001021 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001022 },
1023 VmState::Dead => VirtualMachineState::DEAD,
1024 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001025 }
1026}
1027
David Brazdilf50c7a62023-04-19 14:22:42 +00001028/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001029pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1030 file.as_ref()
1031 .try_clone()
1032 .context("Failed to clone File from ParcelFileDescriptor")
1033 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
David Brazdilf50c7a62023-04-19 14:22:42 +00001034}
1035
Andrew Walbrand3a84182021-09-07 14:48:52 +00001036/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001037fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001038 file.as_ref().map(clone_file).transpose()
1039}
1040
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001041/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1042fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1043 // SAFETY: ownership is transferred from stream to f
1044 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1045 ParcelFileDescriptor::new(f)
1046}
1047
Jiyong Parkdcf17412022-02-08 15:07:23 +09001048/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001049fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1050 VersionReq::parse(s)
1051 .with_context(|| format!("Invalid platform version requirement {}", s))
1052 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001053}
1054
Jiyong Parked180932023-02-24 19:55:41 +09001055/// Create the empty ramdump file
1056fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1057 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1058 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1059 // owner) for readout.
1060 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001061 let ramdump = File::create(ramdump_path)
1062 .context("Failed to prepare ramdump file")
1063 .with_log()
1064 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001065 Ok(ramdump)
1066}
1067
Nikita Ioffe5776f082023-02-10 21:38:26 +00001068fn is_protected(config: &VirtualMachineConfig) -> bool {
1069 match config {
1070 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1071 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1072 }
1073}
1074
1075fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1076 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001077 return Err(anyhow!("Can't use gdb with protected VMs"))
1078 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001079 }
1080
1081 match config {
1082 VirtualMachineConfig::RawConfig(_) => Ok(()),
1083 VirtualMachineConfig::AppConfig(config) => {
1084 if config.debugLevel != DebugLevel::FULL {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001085 Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1086 .or_binder_exception(ExceptionCode::SECURITY)
Nikita Ioffe5776f082023-02-10 21:38:26 +00001087 } else {
1088 Ok(())
1089 }
1090 }
1091 }
1092}
1093
1094fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1095 match config {
1096 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001097 VirtualMachineConfig::AppConfig(config) => {
1098 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1099 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001100 }
1101}
1102
Inseob Kim0168b462022-12-27 14:54:35 +09001103fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001104 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001105 fd: Option<&ParcelFileDescriptor>,
1106 tag: String,
1107) -> Result<Option<File>, Status> {
1108 if let Some(fd) = fd {
1109 return Ok(Some(clone_file(fd)?));
1110 }
1111
Jaewan Kim61f86142023-03-28 15:12:52 +09001112 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001113 return Ok(None);
1114 };
Inseob Kim0168b462022-12-27 14:54:35 +09001115
Jiyong Park2227eaa2023-08-04 11:59:18 +09001116 let (raw_read_fd, raw_write_fd) =
1117 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001118
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001119 // 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 +09001120 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001121 // 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 +09001122 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1123
1124 std::thread::spawn(move || loop {
1125 let mut buf = vec![];
1126 match reader.read_until(b'\n', &mut buf) {
1127 Ok(0) => {
1128 // EOF
1129 return;
1130 }
1131 Ok(size) => {
1132 if buf[size - 1] == b'\n' {
1133 buf.pop();
1134 }
1135 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1136 }
1137 Err(e) => {
1138 error!("Could not read console pipe: {:?}", e);
1139 return;
1140 }
1141 };
1142 });
1143
1144 Ok(Some(write_fd))
1145}
1146
Jooyung Han35edb8f2021-07-01 16:17:16 +09001147/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1148/// it doesn't require that T implements Clone.
1149enum BorrowedOrOwned<'a, T> {
1150 Borrowed(&'a T),
1151 Owned(T),
1152}
1153
1154impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1155 fn as_ref(&self) -> &T {
1156 match self {
1157 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001158 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001159 }
1160 }
1161}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001162
1163/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1164#[derive(Debug, Default)]
1165struct VirtualMachineService {
1166 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001167 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001168}
1169
1170impl Interface for VirtualMachineService {}
1171
1172impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001173 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1174 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001175 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001176 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001177 vm.update_payload_state(PayloadState::Started)
1178 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001179 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001180
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001181 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1182 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001183 Ok(())
1184 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001185 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001186 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001187 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001188 }
Inseob Kim2444af92021-08-31 01:22:50 +09001189
Inseob Kimc7d28c72021-10-25 14:28:10 +00001190 fn notifyPayloadReady(&self) -> binder::Result<()> {
1191 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001192 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001193 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001194 vm.update_payload_state(PayloadState::Ready)
1195 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001196 vm.callbacks.notify_payload_ready(cid);
1197 Ok(())
1198 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001199 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001200 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001201 }
1202 }
1203
Inseob Kimc7d28c72021-10-25 14:28:10 +00001204 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1205 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001206 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001207 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001208 vm.update_payload_state(PayloadState::Finished)
1209 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001210 vm.callbacks.notify_payload_finished(cid, exit_code);
1211 Ok(())
1212 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001213 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001214 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001215 }
1216 }
1217
Alan Stokes2bead0d2022-09-05 16:58:34 +01001218 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001219 let cid = self.cid;
1220 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001221 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001222 vm.update_payload_state(PayloadState::Finished)
1223 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001224 vm.callbacks.notify_error(cid, error_code, message);
1225 Ok(())
1226 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001227 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001228 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001229 }
1230 }
Alice Wangc2fec932023-02-23 16:24:02 +00001231
1232 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
1233 let cid = self.cid;
1234 let Some(vm) = self.state.lock().unwrap().get_vm(cid) else {
1235 error!("requestCertificate is called from an unknown CID {cid}");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001236 return Err(anyhow!("cannot find a VM with CID {}", cid))
1237 .or_service_specific_exception(-1);
Alice Wangc2fec932023-02-23 16:24:02 +00001238 };
1239 let instance_img_path = vm.temporary_directory.join("rkpvm_instance.img");
1240 let instance_img = OpenOptions::new()
1241 .create(true)
1242 .read(true)
1243 .write(true)
1244 .open(instance_img_path)
Jiyong Park2227eaa2023-08-04 11:59:18 +09001245 .context("Failed to create rkpvm_instance.img file")
1246 .with_log()
1247 .or_service_specific_exception(-1)?;
Alice Wangc2fec932023-02-23 16:24:02 +00001248 GLOBAL_SERVICE.requestCertificate(csr, &ParcelFileDescriptor::new(instance_img))
1249 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001250}
1251
1252impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001253 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001254 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001255 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001256 BinderFeatures::default(),
1257 )
1258 }
1259}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001260
1261#[cfg(test)]
1262mod tests {
1263 use super::*;
1264
1265 #[test]
1266 fn test_is_allowed_label_for_partition() -> Result<()> {
1267 let expected_results = vec![
1268 ("u:object_r:system_file:s0", true),
1269 ("u:object_r:apk_data_file:s0", true),
1270 ("u:object_r:app_data_file:s0", false),
1271 ("u:object_r:app_data_file:s0:c512,c768", false),
1272 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1273 ("invalid", false),
1274 ("user:role:apk_data_file:severity:categories", true),
1275 ("user:role:apk_data_file:severity:categories:extraneous", false),
1276 ];
1277
1278 for (label, expected_valid) in expected_results {
1279 let context = SeContext::new(label)?;
1280 let result = check_label_is_allowed(&context);
1281 if expected_valid {
1282 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1283 } else if result.is_ok() {
1284 bail!("Expected label {} to be disallowed", label);
1285 }
1286 }
1287 Ok(())
1288 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001289
1290 #[test]
1291 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1292 let apk = tempfile::tempfile().unwrap();
1293 let idsig = tempfile::tempfile().unwrap();
1294
1295 let ret = create_or_update_idsig_file(
1296 &ParcelFileDescriptor::new(apk),
1297 &ParcelFileDescriptor::new(idsig),
1298 );
1299 assert!(ret.is_err(), "should fail");
1300 Ok(())
1301 }
1302
1303 #[test]
1304 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1305 let tmp_dir = tempfile::TempDir::new().unwrap();
1306 let apk = File::open(tmp_dir.path()).unwrap();
1307 let idsig = tempfile::tempfile().unwrap();
1308
1309 let ret = create_or_update_idsig_file(
1310 &ParcelFileDescriptor::new(apk),
1311 &ParcelFileDescriptor::new(idsig),
1312 );
1313 assert!(ret.is_err(), "should fail");
1314 Ok(())
1315 }
1316
1317 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1318 /// on ext4 filesystem is passed.
1319 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1320 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1321 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1322 #[test]
1323 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1324 // APEXes are backed by the ext4.
1325 let apk = File::open("/apex/com.android.virt/").unwrap();
1326 let idsig = tempfile::tempfile().unwrap();
1327
1328 let ret = create_or_update_idsig_file(
1329 &ParcelFileDescriptor::new(apk),
1330 &ParcelFileDescriptor::new(idsig),
1331 );
1332 assert!(ret.is_err(), "should fail");
1333 Ok(())
1334 }
Jiyong Park8d192952023-06-26 14:29:51 +09001335
1336 #[test]
1337 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1338 use std::io::Seek;
1339
1340 // Pick any APK
1341 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1342 let mut idsig = tempfile::tempfile().unwrap();
1343
1344 create_or_update_idsig_file(
1345 &ParcelFileDescriptor::new(apk.try_clone()?),
1346 &ParcelFileDescriptor::new(idsig.try_clone()?),
1347 )?;
1348 let modified_orig = idsig.metadata()?.modified()?;
1349 apk.rewind()?;
1350 idsig.rewind()?;
1351
1352 // Call the function again
1353 create_or_update_idsig_file(
1354 &ParcelFileDescriptor::new(apk.try_clone()?),
1355 &ParcelFileDescriptor::new(idsig.try_clone()?),
1356 )?;
1357 let modified_new = idsig.metadata()?.modified()?;
1358 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1359 Ok(())
1360 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001361
1362 #[test]
1363 fn test_append_kernel_param_first_param() {
1364 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1365 append_kernel_param("foo=1", &mut vm_config);
1366 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1367 }
1368
1369 #[test]
1370 fn test_append_kernel_param() {
1371 let mut vm_config =
1372 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1373 append_kernel_param("bar=42", &mut vm_config);
1374 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1375 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001376}