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