blob: bf00852babc2f41d3ef49f379d19fc6aeb7cafe0 [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;
Inseob Kim7307a892023-09-14 13:37:58 +090021use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VfioDevice, 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::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090032 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000033 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010035 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000036 IVirtualMachineCallback::IVirtualMachineCallback,
37 IVirtualizationService::IVirtualizationService,
Alan Stokes27f3ef02023-09-29 15:09:35 +010038 IVirtualizationService::FEATURE_MULTI_TENANT,
Nikita Ioffe631717e2023-09-05 13:38:07 +010039 IVirtualizationService::FEATURE_VENDOR_MODULES,
Alan Stokes7f27c0d2023-09-07 16:22:58 +010040 IVirtualizationService::FEATURE_DICE_CHANGES,
Keir Frasercdd4b112022-11-24 14:02:25 +000041 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090042 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000043 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090044 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090045 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000046 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010047 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090048 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000049 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090050};
David Brazdilafc9a9e2023-01-12 16:08:10 +000051use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090052use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000053 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090054};
Alan Stokes25f69362023-03-06 16:51:54 +000055use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090056use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090057use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010058use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000059 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
60 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090061 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000062};
David Brazdilf50c7a62023-04-19 14:22:42 +000063use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000064use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000065use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090066use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090067use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000068use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000069use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090070use semver::VersionReq;
Inseob Kim6ef80972023-07-20 17:23:36 +090071use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000072use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000073use std::ffi::CStr;
Inseob Kim6ef80972023-07-20 17:23:36 +090074use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000075use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000076use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000077use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000078use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000079use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000080use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000081use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000082use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090083use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000084
David Brazdil41d1a872022-10-05 14:44:19 +010085/// The unique ID of a VM used (together with a port number) for vsock communication.
86pub type Cid = u32;
87
David Brazdil4b4c5102022-12-19 22:56:20 +000088pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
89
Jooyung Han95884632021-07-06 22:27:54 +090090/// The size of zero.img.
91/// Gaps in composite disk images are filled with a shared zero.img.
92const ZERO_FILLER_SIZE: u64 = 4096;
93
David Brazdilf50c7a62023-04-19 14:22:42 +000094/// Magic string for the instance image
95const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
96
97/// Version of the instance image format
98const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
99
Alan Stokes0d1ef782022-09-27 13:46:35 +0100100const MICRODROID_OS_NAME: &str = "microdroid";
101
David Brazdilf50c7a62023-04-19 14:22:42 +0000102const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
103
104/// crosvm requires all partitions to be a multiple of 4KiB.
105const PARTITION_GRANULARITY_BYTES: u64 = 4096;
106
David Brazdil49f96f52022-12-16 21:29:13 +0000107lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000108 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
109 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
110 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000111}
112
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000113fn create_or_update_idsig_file(
114 input_fd: &ParcelFileDescriptor,
115 idsig_fd: &ParcelFileDescriptor,
116) -> Result<()> {
117 let mut input = clone_file(input_fd)?;
118 let metadata = input.metadata().context("failed to get input metadata")?;
119 if !metadata.is_file() {
120 bail!("input is not a regular file");
121 }
Alan Stokes25f69362023-03-06 16:51:54 +0000122 let mut sig =
123 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
124 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000125
126 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900127
128 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
129 // if the idsig file already has the same APK digest.
130 if output.metadata()?.len() > 0 {
131 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
132 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
133 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
134 return Ok(());
135 }
136 }
137 // if we fail to read v4signature from output, that's fine. User can pass a random file.
138 // We will anyway overwrite the file to the v4signature generated from input_fd.
139 }
140
Nikita Ioffec09b0492022-12-14 20:18:33 +0000141 output.set_len(0).context("failed to set_len on the idsig output")?;
142 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000143 Ok(())
144}
145
Alan Stokes25f69362023-03-06 16:51:54 +0000146fn get_current_sdk() -> Result<u32> {
147 let current_sdk = system_properties::read("ro.build.version.sdk")?;
148 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
149 current_sdk.parse().context("Malformed SDK version")
150}
151
David Brazdil4b4c5102022-12-19 22:56:20 +0000152pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
153 for dir_entry in read_dir(path)? {
154 remove_file(dir_entry?.path())?;
155 }
156 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100157}
158
David Brazdil528e0472022-10-10 15:06:02 +0100159/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000160#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000161pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900162 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000163}
164
Shikha Panward8e35422021-10-11 13:51:27 +0000165impl Interface for VirtualizationService {
166 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
167 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
168 let state = &mut *self.state.lock().unwrap();
169 let vms = state.vms();
170 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
171 for vm in vms {
172 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
173 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
174 .or(Err(StatusCode::UNKNOWN_ERROR))?;
175 writeln!(file, "\tPayload state {:?}", vm.payload_state())
176 .or(Err(StatusCode::UNKNOWN_ERROR))?;
177 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
178 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
179 .or(Err(StatusCode::UNKNOWN_ERROR))?;
180 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
181 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000182 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
183 .or(Err(StatusCode::UNKNOWN_ERROR))?;
184 }
185 Ok(())
186 }
187}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000188impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000189 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
190 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000191 ///
192 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000193 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000194 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000195 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900196 console_out_fd: Option<&ParcelFileDescriptor>,
197 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000198 log_fd: Option<&ParcelFileDescriptor>,
199 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000200 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900201 let ret = self.create_vm_internal(
202 config,
203 console_out_fd,
204 console_in_fd,
205 log_fd,
206 &mut is_protected,
207 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000208 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000209 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000210 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000211
Andrew Walbrandff3b942021-06-09 15:20:36 +0000212 /// Initialise an empty partition image of the given size to be used as a writable partition.
213 fn initializeWritablePartition(
214 &self,
215 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000216 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900217 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000218 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900219 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900220 let size_bytes = size_bytes
221 .try_into()
222 .with_context(|| format!("Invalid size: {}", size_bytes))
223 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000224 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
225 let image = clone_file(image_fd)?;
226 // initialize the file. Any data in the file will be erased.
Jiyong Park2227eaa2023-08-04 11:59:18 +0900227 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
228 let mut part = QcowFile::new(image, size_bytes)
229 .context("Failed to create QCOW2 image")
230 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000231
232 match partition_type {
233 PartitionType::RAW => Ok(()),
234 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
235 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
236 _ => Err(Error::new(
237 ErrorKind::Unsupported,
238 format!("Unsupported partition type {:?}", partition_type),
239 )),
240 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900241 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
242 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000243
244 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000245 }
246
Jiyong Park0a248432021-08-20 23:32:39 +0900247 /// Creates or update the idsig file by digesting the input APK file.
248 fn createOrUpdateIdsigFile(
249 &self,
250 input_fd: &ParcelFileDescriptor,
251 idsig_fd: &ParcelFileDescriptor,
252 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900253 check_manage_access()?;
254
Jiyong Park2227eaa2023-08-04 11:59:18 +0900255 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900256 Ok(())
257 }
258
Andrew Walbran320b5602021-03-04 16:11:12 +0000259 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
260 /// and as such is only permitted from the shell user.
261 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000262 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000263 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000264 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900265
266 /// Get a list of assignable device types.
267 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
268 // Delegate to the global service, including checking the permission.
269 GLOBAL_SERVICE.getAssignableDevices()
270 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100271
272 /// Returns whether given feature is enabled
273 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
274 check_manage_access()?;
275
276 // This approach is quite cumbersome, but will do the work for the short term.
277 // TODO(b/298012279): make this scalable.
278 match feature {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100279 FEATURE_DICE_CHANGES => Ok(cfg!(dice_changes)),
Alan Stokes27f3ef02023-09-29 15:09:35 +0100280 FEATURE_MULTI_TENANT => Ok(cfg!(multi_tenant)),
Nikita Ioffe631717e2023-09-05 13:38:07 +0100281 FEATURE_VENDOR_MODULES => Ok(cfg!(vendor_modules)),
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100282 _ => {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100283 warn!("unknown feature {feature}");
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100284 Ok(false)
285 }
286 }
287 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000288}
289
Jiyong Park8611a6c2021-07-09 18:17:44 +0900290impl VirtualizationService {
291 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000292 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900293 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000294
David Brazdil209074a2023-01-12 16:44:51 +0000295 fn create_vm_context(
296 &self,
297 requester_debug_pid: pid_t,
298 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000299 const NUM_ATTEMPTS: usize = 5;
300
301 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000302 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000303 let cid = vm_context.getCid()? as Cid;
304 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000305 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
306
307 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000308 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000309 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000310 Ok(vm_server) => {
311 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000312 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000313 }
314 Err(err) => {
315 warn!("Could not start RpcServer on port {}: {}", port, err);
316 }
317 }
318 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900319 Err(anyhow!("Too many attempts to create VM context failed"))
320 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000321 }
322
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000323 fn create_vm_internal(
324 &self,
325 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900326 console_out_fd: Option<&ParcelFileDescriptor>,
327 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000328 log_fd: Option<&ParcelFileDescriptor>,
329 is_protected: &mut bool,
330 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000331 let requester_uid = get_calling_uid();
332 let requester_debug_pid = get_calling_pid();
333
Nikita Ioffe631717e2023-09-05 13:38:07 +0100334 check_config_features(config)?;
335
David Brazdil209074a2023-01-12 16:44:51 +0000336 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
337 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900338
Alan Stokes7bc146c2022-10-20 17:10:32 +0100339 let is_custom = match config {
340 VirtualMachineConfig::RawConfig(_) => true,
341 VirtualMachineConfig::AppConfig(config) => {
342 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100343 // VirtualMachineAppConfig. Almost all of these features are grouped in the
344 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100345 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100346 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100347 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900348 // - using anything other than the default kernel;
349 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100350 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900351 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100352 };
353 if is_custom {
354 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900355 }
356
Nikita Ioffe5776f082023-02-10 21:38:26 +0000357 let gdb_port = extract_gdb_port(config);
358
359 // Additional permission checks if caller request gdb.
360 if gdb_port.is_some() {
361 check_gdb_allowed(config)?;
362 }
363
Jaewan Kim61f86142023-03-28 15:12:52 +0900364 let debug_level = match config {
365 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
366 _ => DebugLevel::NONE,
367 };
368 let debug_config = DebugConfig::new(debug_level);
369
370 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900371 Some(prepare_ramdump_file(&temporary_directory)?)
372 } else {
373 None
374 };
375
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000376 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900377 let console_out_fd =
378 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
379 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900380 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000381
382 // Counter to generate unique IDs for temporary image files.
383 let mut next_temporary_image_id = 0;
384 // Files which are referred to from composite images. These must be mapped to the crosvm
385 // child process, and not closed before it is started.
386 let mut indirect_files = vec![];
387
Alan Stokes7bc146c2022-10-20 17:10:32 +0100388 let (is_app_config, config) = match config {
389 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
390 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900391 let config = load_app_config(config, &debug_config, &temporary_directory)
392 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900393 *is_protected = config.protectedVm;
394 let message = format!("Failed to load app config: {:?}", e);
395 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900396 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900397 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100398 (true, BorrowedOrOwned::Owned(config))
399 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000400 };
401 let config = config.as_ref();
402 *is_protected = config.protectedVm;
403
404 // Check if partition images are labeled incorrectly. This is to prevent random images
405 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100406 // being loaded in a pVM. This applies to everything but the instance image in the raw
407 // config, and everything but the non-executable, generated partitions in the app
408 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000409 config
410 .disks
411 .iter()
412 .flat_map(|disk| disk.partitions.iter())
413 .filter(|partition| {
414 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100415 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000416 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000417 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000418 }
419 })
420 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900421 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000422
Alan Stokes185fe112023-01-10 16:20:55 +0000423 let kernel = maybe_clone_file(&config.kernel)?;
424 let initrd = maybe_clone_file(&config.initrd)?;
425
426 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
427 if config.protectedVm {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900428 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Alan Stokes185fe112023-01-10 16:20:55 +0000429 }
430
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000431 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900432 write_zero_filler(&zero_filler_path)
433 .context("Failed to make composite image")
434 .with_log()
435 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000436
437 // Assemble disk images if needed.
438 let disks = config
439 .disks
440 .iter()
441 .map(|disk| {
442 assemble_disk_image(
443 disk,
444 &zero_filler_path,
445 &temporary_directory,
446 &mut next_temporary_image_id,
447 &mut indirect_files,
448 )
449 })
450 .collect::<Result<Vec<DiskFile>, _>>()?;
451
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000452 let (cpus, host_cpu_topology) = match config.cpuTopology {
453 CpuTopology::MATCH_HOST => (None, true),
454 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
455 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900456 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
457 .with_log()
458 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000459 }
460 };
461
Inseob Kim7307a892023-09-14 13:37:58 +0900462 let vfio_devices = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900463 let mut set = HashSet::new();
464 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900465 let path = canonicalize(device)
466 .with_context(|| format!("can't canonicalize {device}"))
467 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900468 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900469 return Err(anyhow!("duplicated device {device}"))
470 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900471 }
472 }
Inseob Kim7307a892023-09-14 13:37:58 +0900473 GLOBAL_SERVICE
474 .bindDevicesToVfioDriver(&config.devices)?
475 .into_iter()
476 .map(|x| VfioDevice {
477 sysfs_path: PathBuf::from(&x.sysfsPath),
Jaewan Kim35e818d2023-10-18 05:36:38 +0000478 dtbo_label: x.dtboLabel,
Inseob Kim7307a892023-09-14 13:37:58 +0900479 })
480 .collect::<Vec<_>>()
481 } else {
482 vec![]
483 };
Inseob Kim6ef80972023-07-20 17:23:36 +0900484
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000485 // Actually start the VM.
486 let crosvm_config = CrosvmConfig {
487 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000488 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000489 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000490 kernel,
491 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000492 disks,
493 params: config.params.to_owned(),
494 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900495 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000496 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000497 cpus,
498 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900499 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900500 console_out_fd,
501 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000502 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900503 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000504 indirect_files,
505 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900506 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000507 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900508 vfio_devices,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000509 };
510 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100511 VmInstance::new(
512 crosvm_config,
513 temporary_directory,
514 requester_uid,
515 requester_debug_pid,
516 vm_context,
517 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900518 .with_context(|| format!("Failed to create VM with config {:?}", config))
519 .with_log()
520 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000521 );
522 state.add_vm(Arc::downgrade(&instance));
523 Ok(VirtualMachine::create(instance))
524 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900525}
526
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000527fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900528 let file = OpenOptions::new()
529 .create_new(true)
530 .read(true)
531 .write(true)
532 .open(zero_filler_path)
533 .with_context(|| "Failed to create zero.img")?;
534 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000535 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900536}
537
David Brazdilf50c7a62023-04-19 14:22:42 +0000538fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
539 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
540 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
541 part.flush()
542}
543
544fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
545 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
546 part.flush()
547}
548
549fn round_up(input: u64, granularity: u64) -> u64 {
550 if granularity == 0 {
551 return input;
552 }
553 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
554 let result = input.checked_add(granularity - 1).unwrap_or(input);
555 (result / granularity) * granularity
556}
557
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000558/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
559///
560/// This may involve assembling a composite disk from a set of partition images.
561fn assemble_disk_image(
562 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900563 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000564 temporary_directory: &Path,
565 next_temporary_image_id: &mut u64,
566 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000567) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000568 let image = if !disk.partitions.is_empty() {
569 if disk.image.is_some() {
570 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900571 return Err(anyhow!("DiskImage contains both image and partitions"))
572 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000573 }
574
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000575 let composite_image_filenames =
576 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
577 let (image, partition_files) = make_composite_image(
578 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900579 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000580 &composite_image_filenames.composite,
581 &composite_image_filenames.header,
582 &composite_image_filenames.footer,
583 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900584 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
585 .with_log()
586 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000587
588 // Pass the file descriptors for the various partition files to crosvm when it
589 // is run.
590 indirect_files.extend(partition_files);
591
592 image
593 } else if let Some(image) = &disk.image {
594 clone_file(image)?
595 } else {
596 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900597 return Err(anyhow!("DiskImage didn't contain image or partitions."))
598 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000599 };
600
601 Ok(DiskFile { image, writable: disk.writable })
602}
603
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100604fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
605 if let Some(ref mut params) = vm_config.params {
606 params.push(' ');
607 params.push_str(param)
608 } else {
609 vm_config.params = Some(param.to_owned())
610 }
611}
612
Jooyung Han21e9b922021-06-26 04:14:16 +0900613fn load_app_config(
614 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900615 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900616 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900617) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000618 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
619 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900620 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900621
Shikha Panwar22e70452022-10-10 18:32:55 +0000622 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
623 Some(clone_file(file)?)
624 } else {
625 None
626 };
627
Alan Stokes0d1ef782022-09-27 13:46:35 +0100628 let vm_payload_config = match &config.payload {
629 Payload::ConfigPath(config_path) => {
630 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
631 .with_context(|| format!("Couldn't read config from {}", config_path))?
632 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000633 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100634 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900635
Alan Stokes0d1ef782022-09-27 13:46:35 +0100636 // For now, the only supported OS is Microdroid
637 let os_name = vm_payload_config.os.name.as_str();
638 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000639 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900640 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000641
642 // It is safe to construct a filename based on the os_name because we've already checked that it
643 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900644 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
645 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000646 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900647
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100648 if let Some(custom_config) = &config.customConfig {
649 if let Some(file) = custom_config.customKernelImage.as_ref() {
650 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
651 }
652 vm_config.taskProfiles = custom_config.taskProfiles.clone();
653 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100654
655 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100656 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
657 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100658 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900659
660 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100661 }
662
Andrew Walbrancc045902021-07-27 16:06:17 +0000663 if config.memoryMib > 0 {
664 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000665 }
666
Seungjae Yoo62085c02022-08-12 04:44:52 +0000667 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000668 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000669 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900670
Shikha Panwar22e70452022-10-10 18:32:55 +0000671 // Microdroid takes additional init ramdisk & (optionally) storage image
672 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
673
674 // Include Microdroid payload disk (contains apks, idsigs) in vm config
675 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100676 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900677 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100678 temporary_directory,
679 apk_file,
680 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100681 &vm_payload_config,
682 &mut vm_config,
683 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900684
Andrew Walbrancc0db522021-07-12 17:03:42 +0000685 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900686}
687
Alan Stokes0d1ef782022-09-27 13:46:35 +0100688fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
689 let mut apk_zip = ZipArchive::new(apk_file)?;
690 let config_file = apk_zip.by_name(config_path)?;
691 Ok(serde_json::from_reader(config_file)?)
692}
693
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000694fn create_vm_payload_config(
695 payload_config: &VirtualMachinePayloadConfig,
696) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100697 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
698 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
699 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000700
701 let payload_binary_name = &payload_config.payloadBinaryName;
702 if payload_binary_name.contains('/') {
703 bail!("Payload binary name must not specify a path: {payload_binary_name}");
704 }
705
706 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
707 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100708 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
709 task: Some(task),
710 apexes: vec![],
711 extra_apks: vec![],
712 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900713 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100714 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000715 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100716}
717
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000718/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000719fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000720 temporary_directory: &Path,
721 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000722) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000723 let id = *next_temporary_image_id;
724 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000725 CompositeImageFilenames {
726 composite: temporary_directory.join(format!("composite-{}.img", id)),
727 header: temporary_directory.join(format!("composite-{}-header.img", id)),
728 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
729 }
730}
731
732/// Filenames for a composite disk image, including header and footer partitions.
733#[derive(Clone, Debug, Eq, PartialEq)]
734struct CompositeImageFilenames {
735 /// The composite disk image itself.
736 composite: PathBuf,
737 /// The header partition image.
738 header: PathBuf,
739 /// The footer partition image.
740 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000741}
742
Jiyong Park753553b2021-07-12 21:21:09 +0900743/// Checks whether the caller has a specific permission
744fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100745 let calling_pid = get_calling_pid();
746 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900747 // Root can do anything
748 if calling_uid == 0 {
749 return Ok(());
750 }
751 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
752 binder::get_interface("permission")?;
753 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000754 Ok(())
755 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900756 Err(anyhow!("does not have the {} permission", perm))
757 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000758 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000759}
760
Jiyong Park753553b2021-07-12 21:21:09 +0900761/// Check whether the caller of the current Binder method is allowed to manage VMs
762fn check_manage_access() -> binder::Result<()> {
763 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
764}
765
Inseob Kim1119d702022-05-02 18:01:58 +0900766/// Check whether the caller of the current Binder method is allowed to create custom VMs
767fn check_use_custom_virtual_machine() -> binder::Result<()> {
768 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
769}
770
Alan Stokes185fe112023-01-10 16:20:55 +0000771/// Return whether a partition is exempt from selinux label checks, because we know that it does
772/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100773fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000774 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100775 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000776 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100777 || label == "microdroid-apk-idsig"
778 || label == "payload-metadata"
779 || label.starts_with("extra-idsig-")
780}
781
Alice Wangc206b9b2023-08-28 14:13:51 +0000782/// Returns whether a partition with the given label is safe for a raw config VM.
783fn is_safe_raw_partition(label: &str) -> bool {
784 label == "vm-instance"
785}
786
Alan Stokes185fe112023-01-10 16:20:55 +0000787/// Check that a file SELinux label is acceptable.
788///
789/// We only want to allow code in a VM to be sourced from places that apps, and the
790/// system, do not have write access to.
791///
792/// Note that sepolicy must also grant read access for these types to both virtualization
793/// service and crosvm.
794///
795/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
796/// user devices (W^X).
797fn check_label_is_allowed(context: &SeContext) -> Result<()> {
798 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100799 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100800 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000801 | "staging_data_file" // updated/staged APEX images
802 | "system_file" // immutable dm-verity protected partition
803 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100804 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000805 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900806 }
807}
808
Alan Stokes185fe112023-01-10 16:20:55 +0000809fn check_label_for_partition(partition: &Partition) -> Result<()> {
810 let file = partition.image.as_ref().unwrap().as_ref();
811 check_label_is_allowed(&getfilecon(file)?)
812 .with_context(|| format!("Partition {} invalid", &partition.label))
813}
814
815fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
816 if let Some(f) = kernel {
817 check_label_for_file(f, "kernel")?;
818 }
819 if let Some(f) = initrd {
820 check_label_for_file(f, "initrd")?;
821 }
822 Ok(())
823}
824fn check_label_for_file(file: &File, name: &str) -> Result<()> {
825 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
826}
827
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000828/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
829#[derive(Debug)]
830struct VirtualMachine {
831 instance: Arc<VmInstance>,
832}
833
834impl VirtualMachine {
835 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000836 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000837 }
838}
839
840impl Interface for VirtualMachine {}
841
842impl IVirtualMachine for VirtualMachine {
843 fn getCid(&self) -> binder::Result<i32> {
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.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000846 Ok(self.instance.cid as i32)
847 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000848
Andrew Walbran6b650662021-09-07 13:13:23 +0000849 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900850 // Don't check permission. The owner of the VM might have passed this binder object to
851 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000852 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000853 }
854
855 fn registerCallback(
856 &self,
857 callback: &Strong<dyn IVirtualMachineCallback>,
858 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900859 // Don't check permission. The owner of the VM might have passed this binder object to
860 // others.
861 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000862 // TODO: Should this give an error if the VM is already dead?
863 self.instance.callbacks.add(callback.clone());
864 Ok(())
865 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000866
Andrew Walbranf8d94112021-09-07 11:45:36 +0000867 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900868 self.instance
869 .start()
870 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
871 .with_log()
872 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000873 }
874
Inseob Kima446f802022-07-11 19:46:37 +0900875 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900876 self.instance
877 .kill()
878 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
879 .with_log()
880 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +0900881 }
882
Keir Frasercdd4b112022-11-24 14:02:25 +0000883 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900884 self.instance
885 .trim_memory(level)
886 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
887 .with_log()
888 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +0000889 }
890
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000891 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000892 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900893 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000894 }
Alan Stokes10c47672022-12-13 17:17:08 +0000895 let port = port as u32;
896 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900897 return Err(anyhow!("Can't connect to privileged port {port}"))
898 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +0000899 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900900 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
901 .context("Failed to connect")
902 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000903 Ok(vsock_stream_to_pfd(stream))
904 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000905}
906
907impl Drop for VirtualMachine {
908 fn drop(&mut self) {
909 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900910 if let Err(e) = self.instance.kill() {
911 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
912 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000913 }
914}
915
916/// A set of Binders to be called back in response to various events on the VM, such as when it
917/// dies.
918#[derive(Debug, Default)]
919pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
920
921impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900922 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100923 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900924 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900925 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100926 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100927 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900928 }
929 }
930 }
931
Inseob Kim14cb8692021-08-31 21:50:39 +0900932 /// Call all registered callbacks to notify that the payload is ready to serve.
933 pub fn notify_payload_ready(&self, cid: Cid) {
934 let callbacks = &*self.0.lock().unwrap();
935 for callback in callbacks {
936 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100937 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900938 }
939 }
940 }
941
Inseob Kim2444af92021-08-31 01:22:50 +0900942 /// Call all registered callbacks to notify that the payload has finished.
943 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
944 let callbacks = &*self.0.lock().unwrap();
945 for callback in callbacks {
946 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100947 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900948 }
949 }
950 }
951
Jooyung Handd0a1732021-11-23 15:26:20 +0900952 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100953 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900954 let callbacks = &*self.0.lock().unwrap();
955 for callback in callbacks {
956 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100957 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900958 }
959 }
960 }
961
Andrew Walbrandae07162021-03-12 17:05:20 +0000962 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000963 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000964 let callbacks = &*self.0.lock().unwrap();
965 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000966 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100967 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000968 }
969 }
970 }
971
972 /// Add a new callback to the set.
973 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
974 self.0.lock().unwrap().push(callback);
975 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000976}
977
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000978/// The mutable state of the VirtualizationService. There should only be one instance of this
979/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800980#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000981struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +0100982 /// The VMs which have been started. When VMs are started a weak reference is added to this
983 /// list while a strong reference is returned to the caller over Binder. Once all copies of
984 /// the Binder client are dropped the weak reference here will become invalid, and will be
985 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +0000986 vms: Vec<Weak<VmInstance>>,
987}
988
989impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000990 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000991 fn vms(&self) -> Vec<Arc<VmInstance>> {
992 // Attempt to upgrade the weak pointers to strong pointers.
993 self.vms.iter().filter_map(Weak::upgrade).collect()
994 }
995
996 /// Add a new VM to the list.
997 fn add_vm(&mut self, vm: Weak<VmInstance>) {
998 // Garbage collect any entries from the stored list which no longer exist.
999 self.vms.retain(|vm| vm.strong_count() > 0);
1000
1001 // Actually add the new VM.
1002 self.vms.push(vm);
1003 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001004
Jiyong Park8611a6c2021-07-09 18:17:44 +09001005 /// Get a VM that corresponds to the given cid
1006 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1007 self.vms().into_iter().find(|vm| vm.cid == cid)
1008 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001009}
1010
Andrew Walbran6b650662021-09-07 13:13:23 +00001011/// Gets the `VirtualMachineState` of the given `VmInstance`.
1012fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001013 match &*instance.vm_state.lock().unwrap() {
1014 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1015 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001016 PayloadState::Starting => VirtualMachineState::STARTING,
1017 PayloadState::Started => VirtualMachineState::STARTED,
1018 PayloadState::Ready => VirtualMachineState::READY,
1019 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001020 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001021 },
1022 VmState::Dead => VirtualMachineState::DEAD,
1023 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001024 }
1025}
1026
David Brazdilf50c7a62023-04-19 14:22:42 +00001027/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001028pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1029 file.as_ref()
1030 .try_clone()
1031 .context("Failed to clone File from ParcelFileDescriptor")
1032 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001033 .map(File::from)
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
Nikita Ioffe631717e2023-09-05 13:38:07 +01001103fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1104 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1105 if let Some(custom_config) = &config.customConfig {
1106 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1107 return Err(anyhow!("vendor modules feature is disabled"))
1108 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1109 }
1110 }
1111 Ok(())
1112}
1113
1114fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1115 if !cfg!(vendor_modules) {
1116 check_no_vendor_modules(config)?;
1117 }
1118 Ok(())
1119}
1120
Inseob Kim0168b462022-12-27 14:54:35 +09001121fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001122 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001123 fd: Option<&ParcelFileDescriptor>,
1124 tag: String,
1125) -> Result<Option<File>, Status> {
1126 if let Some(fd) = fd {
1127 return Ok(Some(clone_file(fd)?));
1128 }
1129
Jaewan Kim61f86142023-03-28 15:12:52 +09001130 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001131 return Ok(None);
1132 };
Inseob Kim0168b462022-12-27 14:54:35 +09001133
Jiyong Park2227eaa2023-08-04 11:59:18 +09001134 let (raw_read_fd, raw_write_fd) =
1135 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001136
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001137 // 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 +09001138 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001139 // 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 +09001140 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1141
1142 std::thread::spawn(move || loop {
1143 let mut buf = vec![];
1144 match reader.read_until(b'\n', &mut buf) {
1145 Ok(0) => {
1146 // EOF
1147 return;
1148 }
1149 Ok(size) => {
1150 if buf[size - 1] == b'\n' {
1151 buf.pop();
1152 }
1153 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1154 }
1155 Err(e) => {
1156 error!("Could not read console pipe: {:?}", e);
1157 return;
1158 }
1159 };
1160 });
1161
1162 Ok(Some(write_fd))
1163}
1164
Jooyung Han35edb8f2021-07-01 16:17:16 +09001165/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1166/// it doesn't require that T implements Clone.
1167enum BorrowedOrOwned<'a, T> {
1168 Borrowed(&'a T),
1169 Owned(T),
1170}
1171
1172impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1173 fn as_ref(&self) -> &T {
1174 match self {
1175 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001176 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001177 }
1178 }
1179}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001180
1181/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1182#[derive(Debug, Default)]
1183struct VirtualMachineService {
1184 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001185 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001186}
1187
1188impl Interface for VirtualMachineService {}
1189
1190impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001191 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1192 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001193 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001194 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001195 vm.update_payload_state(PayloadState::Started)
1196 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001197 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001198
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001199 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1200 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001201 Ok(())
1202 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001203 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001204 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001205 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001206 }
Inseob Kim2444af92021-08-31 01:22:50 +09001207
Inseob Kimc7d28c72021-10-25 14:28:10 +00001208 fn notifyPayloadReady(&self) -> binder::Result<()> {
1209 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001210 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001211 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001212 vm.update_payload_state(PayloadState::Ready)
1213 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001214 vm.callbacks.notify_payload_ready(cid);
1215 Ok(())
1216 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001217 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001218 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001219 }
1220 }
1221
Inseob Kimc7d28c72021-10-25 14:28:10 +00001222 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1223 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001224 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001225 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001226 vm.update_payload_state(PayloadState::Finished)
1227 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001228 vm.callbacks.notify_payload_finished(cid, exit_code);
1229 Ok(())
1230 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001231 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001232 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001233 }
1234 }
1235
Alan Stokes2bead0d2022-09-05 16:58:34 +01001236 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001237 let cid = self.cid;
1238 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001239 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001240 vm.update_payload_state(PayloadState::Finished)
1241 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001242 vm.callbacks.notify_error(cid, error_code, message);
1243 Ok(())
1244 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001245 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001246 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001247 }
1248 }
Alice Wangc2fec932023-02-23 16:24:02 +00001249
Alice Wang4e3015d2023-10-10 09:35:37 +00001250 fn requestAttestation(&self, csr: &[u8]) -> binder::Result<Vec<Certificate>> {
Alice Wanga410b642023-10-18 09:05:15 +00001251 GLOBAL_SERVICE.requestAttestation(csr)
Alice Wangc2fec932023-02-23 16:24:02 +00001252 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001253}
1254
1255impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001256 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001257 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001258 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001259 BinderFeatures::default(),
1260 )
1261 }
1262}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001263
1264#[cfg(test)]
1265mod tests {
1266 use super::*;
1267
1268 #[test]
1269 fn test_is_allowed_label_for_partition() -> Result<()> {
1270 let expected_results = vec![
1271 ("u:object_r:system_file:s0", true),
1272 ("u:object_r:apk_data_file:s0", true),
1273 ("u:object_r:app_data_file:s0", false),
1274 ("u:object_r:app_data_file:s0:c512,c768", false),
1275 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1276 ("invalid", false),
1277 ("user:role:apk_data_file:severity:categories", true),
1278 ("user:role:apk_data_file:severity:categories:extraneous", false),
1279 ];
1280
1281 for (label, expected_valid) in expected_results {
1282 let context = SeContext::new(label)?;
1283 let result = check_label_is_allowed(&context);
1284 if expected_valid {
1285 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1286 } else if result.is_ok() {
1287 bail!("Expected label {} to be disallowed", label);
1288 }
1289 }
1290 Ok(())
1291 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001292
1293 #[test]
1294 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1295 let apk = tempfile::tempfile().unwrap();
1296 let idsig = tempfile::tempfile().unwrap();
1297
1298 let ret = create_or_update_idsig_file(
1299 &ParcelFileDescriptor::new(apk),
1300 &ParcelFileDescriptor::new(idsig),
1301 );
1302 assert!(ret.is_err(), "should fail");
1303 Ok(())
1304 }
1305
1306 #[test]
1307 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1308 let tmp_dir = tempfile::TempDir::new().unwrap();
1309 let apk = File::open(tmp_dir.path()).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 }
1319
1320 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1321 /// on ext4 filesystem is passed.
1322 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1323 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1324 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1325 #[test]
1326 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1327 // APEXes are backed by the ext4.
1328 let apk = File::open("/apex/com.android.virt/").unwrap();
1329 let idsig = tempfile::tempfile().unwrap();
1330
1331 let ret = create_or_update_idsig_file(
1332 &ParcelFileDescriptor::new(apk),
1333 &ParcelFileDescriptor::new(idsig),
1334 );
1335 assert!(ret.is_err(), "should fail");
1336 Ok(())
1337 }
Jiyong Park8d192952023-06-26 14:29:51 +09001338
1339 #[test]
1340 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1341 use std::io::Seek;
1342
1343 // Pick any APK
1344 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1345 let mut idsig = tempfile::tempfile().unwrap();
1346
1347 create_or_update_idsig_file(
1348 &ParcelFileDescriptor::new(apk.try_clone()?),
1349 &ParcelFileDescriptor::new(idsig.try_clone()?),
1350 )?;
1351 let modified_orig = idsig.metadata()?.modified()?;
1352 apk.rewind()?;
1353 idsig.rewind()?;
1354
1355 // Call the function again
1356 create_or_update_idsig_file(
1357 &ParcelFileDescriptor::new(apk.try_clone()?),
1358 &ParcelFileDescriptor::new(idsig.try_clone()?),
1359 )?;
1360 let modified_new = idsig.metadata()?.modified()?;
1361 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1362 Ok(())
1363 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001364
1365 #[test]
1366 fn test_append_kernel_param_first_param() {
1367 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1368 append_kernel_param("foo=1", &mut vm_config);
1369 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1370 }
1371
1372 #[test]
1373 fn test_append_kernel_param() {
1374 let mut vm_config =
1375 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1376 append_kernel_param("bar=42", &mut vm_config);
1377 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1378 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001379}