blob: 91bd60b68549b6363d2807ffb1c0e79bac551ef7 [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};
Alan Stokes0e82b502022-08-08 14:44:48 +010053use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000054 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
55 Status, StatusCode, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000056};
David Brazdilf50c7a62023-04-19 14:22:42 +000057use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000058use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000059use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090060use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090061use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000062use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000063use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090064use semver::VersionReq;
Inseob Kim6ef80972023-07-20 17:23:36 +090065use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000066use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000067use std::ffi::CStr;
Inseob Kim6ef80972023-07-20 17:23:36 +090068use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000069use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000070use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000071use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000072use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000073use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000074use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000075use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000076use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090077use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000078
David Brazdil41d1a872022-10-05 14:44:19 +010079/// The unique ID of a VM used (together with a port number) for vsock communication.
80pub type Cid = u32;
81
David Brazdil4b4c5102022-12-19 22:56:20 +000082pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
83
Jooyung Han95884632021-07-06 22:27:54 +090084/// The size of zero.img.
85/// Gaps in composite disk images are filled with a shared zero.img.
86const ZERO_FILLER_SIZE: u64 = 4096;
87
David Brazdilf50c7a62023-04-19 14:22:42 +000088/// Magic string for the instance image
89const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
90
91/// Version of the instance image format
92const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
93
Alan Stokes0d1ef782022-09-27 13:46:35 +010094const MICRODROID_OS_NAME: &str = "microdroid";
95
David Brazdilf50c7a62023-04-19 14:22:42 +000096const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
97
98/// crosvm requires all partitions to be a multiple of 4KiB.
99const PARTITION_GRANULARITY_BYTES: u64 = 4096;
100
David Brazdil49f96f52022-12-16 21:29:13 +0000101lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000102 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
103 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
104 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000105}
106
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000107fn create_or_update_idsig_file(
108 input_fd: &ParcelFileDescriptor,
109 idsig_fd: &ParcelFileDescriptor,
110) -> Result<()> {
111 let mut input = clone_file(input_fd)?;
112 let metadata = input.metadata().context("failed to get input metadata")?;
113 if !metadata.is_file() {
114 bail!("input is not a regular file");
115 }
Alan Stokes25f69362023-03-06 16:51:54 +0000116 let mut sig =
117 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
118 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000119
120 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900121
122 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
123 // if the idsig file already has the same APK digest.
124 if output.metadata()?.len() > 0 {
125 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
126 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
127 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
128 return Ok(());
129 }
130 }
131 // if we fail to read v4signature from output, that's fine. User can pass a random file.
132 // We will anyway overwrite the file to the v4signature generated from input_fd.
133 }
134
Nikita Ioffec09b0492022-12-14 20:18:33 +0000135 output.set_len(0).context("failed to set_len on the idsig output")?;
136 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000137 Ok(())
138}
139
Alan Stokes25f69362023-03-06 16:51:54 +0000140fn get_current_sdk() -> Result<u32> {
141 let current_sdk = system_properties::read("ro.build.version.sdk")?;
142 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
143 current_sdk.parse().context("Malformed SDK version")
144}
145
David Brazdil4b4c5102022-12-19 22:56:20 +0000146pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
147 for dir_entry in read_dir(path)? {
148 remove_file(dir_entry?.path())?;
149 }
150 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100151}
152
David Brazdil528e0472022-10-10 15:06:02 +0100153/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000154#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000155pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900156 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000157}
158
Shikha Panward8e35422021-10-11 13:51:27 +0000159impl Interface for VirtualizationService {
160 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
161 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
162 let state = &mut *self.state.lock().unwrap();
163 let vms = state.vms();
164 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
165 for vm in vms {
166 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
167 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
168 .or(Err(StatusCode::UNKNOWN_ERROR))?;
169 writeln!(file, "\tPayload state {:?}", vm.payload_state())
170 .or(Err(StatusCode::UNKNOWN_ERROR))?;
171 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
172 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
173 .or(Err(StatusCode::UNKNOWN_ERROR))?;
174 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
175 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000176 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
177 .or(Err(StatusCode::UNKNOWN_ERROR))?;
178 }
179 Ok(())
180 }
181}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000182
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000183impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000184 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
185 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000186 ///
187 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000188 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000189 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000190 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900191 console_out_fd: Option<&ParcelFileDescriptor>,
192 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000193 log_fd: Option<&ParcelFileDescriptor>,
194 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000195 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900196 let ret = self.create_vm_internal(
197 config,
198 console_out_fd,
199 console_in_fd,
200 log_fd,
201 &mut is_protected,
202 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000203 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000204 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000205 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000206
Andrew Walbrandff3b942021-06-09 15:20:36 +0000207 /// Initialise an empty partition image of the given size to be used as a writable partition.
208 fn initializeWritablePartition(
209 &self,
210 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000211 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900212 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000213 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900214 check_manage_access()?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000215 let size_bytes = size_bytes.try_into().map_err(|e| {
216 Status::new_exception_str(
217 ExceptionCode::ILLEGAL_ARGUMENT,
218 Some(format!("Invalid size {}: {:?}", size_bytes, e)),
219 )
220 })?;
221 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
222 let image = clone_file(image_fd)?;
223 // initialize the file. Any data in the file will be erased.
224 image.set_len(0).map_err(|e| {
225 Status::new_service_specific_error_str(
226 -1,
227 Some(format!("Failed to reset a file: {:?}", e)),
228 )
229 })?;
230 let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
231 Status::new_service_specific_error_str(
232 -1,
233 Some(format!("Failed to create QCOW2 image: {:?}", e)),
234 )
235 })?;
236
237 match partition_type {
238 PartitionType::RAW => Ok(()),
239 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
240 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
241 _ => Err(Error::new(
242 ErrorKind::Unsupported,
243 format!("Unsupported partition type {:?}", partition_type),
244 )),
245 }
246 .map_err(|e| {
247 Status::new_service_specific_error_str(
248 -1,
249 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
250 )
251 })?;
252
253 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000254 }
255
Jiyong Park0a248432021-08-20 23:32:39 +0900256 /// Creates or update the idsig file by digesting the input APK file.
257 fn createOrUpdateIdsigFile(
258 &self,
259 input_fd: &ParcelFileDescriptor,
260 idsig_fd: &ParcelFileDescriptor,
261 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900262 check_manage_access()?;
263
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000264 create_or_update_idsig_file(input_fd, idsig_fd)
265 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900266 Ok(())
267 }
268
Andrew Walbran320b5602021-03-04 16:11:12 +0000269 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
270 /// and as such is only permitted from the shell user.
271 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000272 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000273 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000274 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900275
276 /// Get a list of assignable device types.
277 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
278 // Delegate to the global service, including checking the permission.
279 GLOBAL_SERVICE.getAssignableDevices()
280 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000281}
282
Jiyong Park8611a6c2021-07-09 18:17:44 +0900283impl VirtualizationService {
284 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000285 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900286 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000287
David Brazdil209074a2023-01-12 16:44:51 +0000288 fn create_vm_context(
289 &self,
290 requester_debug_pid: pid_t,
291 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000292 const NUM_ATTEMPTS: usize = 5;
293
294 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000295 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000296 let cid = vm_context.getCid()? as Cid;
297 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000298 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
299
300 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000301 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000302 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000303 Ok(vm_server) => {
304 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000305 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000306 }
307 Err(err) => {
308 warn!("Could not start RpcServer on port {}: {}", port, err);
309 }
310 }
311 }
David Brazdil209074a2023-01-12 16:44:51 +0000312 Err(Status::new_service_specific_error_str(
313 -1,
314 Some("Too many attempts to create VM context failed."),
315 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000316 }
317
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000318 fn create_vm_internal(
319 &self,
320 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900321 console_out_fd: Option<&ParcelFileDescriptor>,
322 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000323 log_fd: Option<&ParcelFileDescriptor>,
324 is_protected: &mut bool,
325 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000326 let requester_uid = get_calling_uid();
327 let requester_debug_pid = get_calling_pid();
328
329 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
330 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900331
Alan Stokes7bc146c2022-10-20 17:10:32 +0100332 let is_custom = match config {
333 VirtualMachineConfig::RawConfig(_) => true,
334 VirtualMachineConfig::AppConfig(config) => {
335 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100336 // VirtualMachineAppConfig. Almost all of these features are grouped in the
337 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100338 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100339 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100340 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900341 // - using anything other than the default kernel;
342 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100343 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900344 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100345 };
346 if is_custom {
347 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900348 }
349
Nikita Ioffe5776f082023-02-10 21:38:26 +0000350 let gdb_port = extract_gdb_port(config);
351
352 // Additional permission checks if caller request gdb.
353 if gdb_port.is_some() {
354 check_gdb_allowed(config)?;
355 }
356
Jaewan Kim61f86142023-03-28 15:12:52 +0900357 let debug_level = match config {
358 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
359 _ => DebugLevel::NONE,
360 };
361 let debug_config = DebugConfig::new(debug_level);
362
363 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900364 Some(prepare_ramdump_file(&temporary_directory)?)
365 } else {
366 None
367 };
368
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000369 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900370 let console_out_fd =
371 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
372 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900373 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000374
375 // Counter to generate unique IDs for temporary image files.
376 let mut next_temporary_image_id = 0;
377 // Files which are referred to from composite images. These must be mapped to the crosvm
378 // child process, and not closed before it is started.
379 let mut indirect_files = vec![];
380
Alan Stokes7bc146c2022-10-20 17:10:32 +0100381 let (is_app_config, config) = match config {
382 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
383 VirtualMachineConfig::AppConfig(config) => {
Jaewan Kim61f86142023-03-28 15:12:52 +0900384 let config =
385 load_app_config(config, &debug_config, &temporary_directory).map_err(|e| {
386 *is_protected = config.protectedVm;
387 let message = format!("Failed to load app config: {:?}", e);
388 error!("{}", message);
389 Status::new_service_specific_error_str(-1, Some(message))
390 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100391 (true, BorrowedOrOwned::Owned(config))
392 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000393 };
394 let config = config.as_ref();
395 *is_protected = config.protectedVm;
396
397 // Check if partition images are labeled incorrectly. This is to prevent random images
398 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100399 // being loaded in a pVM. This applies to everything in the raw config, and everything but
400 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000401 config
402 .disks
403 .iter()
404 .flat_map(|disk| disk.partitions.iter())
405 .filter(|partition| {
406 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100407 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000408 } else {
409 true // all partitions are checked
410 }
411 })
412 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100413 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000414
Alan Stokes185fe112023-01-10 16:20:55 +0000415 let kernel = maybe_clone_file(&config.kernel)?;
416 let initrd = maybe_clone_file(&config.initrd)?;
417
418 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
419 if config.protectedVm {
420 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
421 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
422 })?;
423 }
424
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000425 let zero_filler_path = temporary_directory.join("zero.img");
426 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100427 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000428 Status::new_service_specific_error_str(
429 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100430 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000431 )
432 })?;
433
434 // Assemble disk images if needed.
435 let disks = config
436 .disks
437 .iter()
438 .map(|disk| {
439 assemble_disk_image(
440 disk,
441 &zero_filler_path,
442 &temporary_directory,
443 &mut next_temporary_image_id,
444 &mut indirect_files,
445 )
446 })
447 .collect::<Result<Vec<DiskFile>, _>>()?;
448
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000449 let (cpus, host_cpu_topology) = match config.cpuTopology {
450 CpuTopology::MATCH_HOST => (None, true),
451 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
452 val => {
453 error!("Unexpected value of CPU topology: {:?}", val);
454 return Err(Status::new_service_specific_error_str(
455 -1,
456 Some(format!("Failed to parse CPU topology value: {:?}", val)),
457 ));
458 }
459 };
460
Inseob Kim6ef80972023-07-20 17:23:36 +0900461 let devices_dtbo = if !config.devices.is_empty() {
462 let mut set = HashSet::new();
463 for device in config.devices.iter() {
464 let path = canonicalize(device).map_err(|e| {
465 Status::new_exception_str(
466 ExceptionCode::ILLEGAL_ARGUMENT,
467 Some(format!("can't canonicalize {device}: {e:?}")),
468 )
469 })?;
470 if !set.insert(path) {
471 return Err(Status::new_exception_str(
472 ExceptionCode::ILLEGAL_ARGUMENT,
473 Some(format!("duplicated device {device}")),
474 ));
475 }
476 }
Inseob Kimf36347b2023-08-03 12:52:48 +0900477 let dtbo_path = temporary_directory.join("dtbo");
478 // open a writable file descriptor for vfio_handler
479 let dtbo = File::create(&dtbo_path).map_err(|e| {
480 error!("Failed to create VM DTBO file {dtbo_path:?}: {e:?}");
481 Status::new_service_specific_error_str(
482 -1,
483 Some(format!("Failed to create VM DTBO file {dtbo_path:?}: {e:?}")),
484 )
485 })?;
486 GLOBAL_SERVICE
487 .bindDevicesToVfioDriver(&config.devices, &ParcelFileDescriptor::new(dtbo))?;
488
489 // open (again) a readable file descriptor for crosvm
490 let dtbo = File::open(&dtbo_path).map_err(|e| {
491 error!("Failed to open VM DTBO file {dtbo_path:?}: {e:?}");
492 Status::new_service_specific_error_str(
493 -1,
494 Some(format!("Failed to open VM DTBO file {dtbo_path:?}: {e:?}")),
495 )
496 })?;
497 Some(dtbo)
Inseob Kim6ef80972023-07-20 17:23:36 +0900498 } else {
499 None
500 };
501
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000502 // Actually start the VM.
503 let crosvm_config = CrosvmConfig {
504 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000505 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000506 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000507 kernel,
508 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000509 disks,
510 params: config.params.to_owned(),
511 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900512 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000513 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000514 cpus,
515 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900516 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900517 console_out_fd,
518 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000519 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900520 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000521 indirect_files,
522 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900523 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000524 gdb_port,
Inseob Kim6ef80972023-07-20 17:23:36 +0900525 vfio_devices: config.devices.iter().map(PathBuf::from).collect(),
526 devices_dtbo,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000527 };
528 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100529 VmInstance::new(
530 crosvm_config,
531 temporary_directory,
532 requester_uid,
533 requester_debug_pid,
534 vm_context,
535 )
536 .map_err(|e| {
537 error!("Failed to create VM with config {:?}: {:?}", config, e);
538 Status::new_service_specific_error_str(
539 -1,
540 Some(format!("Failed to create VM: {:?}", e)),
541 )
542 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000543 );
544 state.add_vm(Arc::downgrade(&instance));
545 Ok(VirtualMachine::create(instance))
546 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900547}
548
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000549fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900550 let file = OpenOptions::new()
551 .create_new(true)
552 .read(true)
553 .write(true)
554 .open(zero_filler_path)
555 .with_context(|| "Failed to create zero.img")?;
556 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000557 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900558}
559
David Brazdilf50c7a62023-04-19 14:22:42 +0000560fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
561 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
562 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
563 part.flush()
564}
565
566fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
567 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
568 part.flush()
569}
570
571fn round_up(input: u64, granularity: u64) -> u64 {
572 if granularity == 0 {
573 return input;
574 }
575 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
576 let result = input.checked_add(granularity - 1).unwrap_or(input);
577 (result / granularity) * granularity
578}
579
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000580/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
581///
582/// This may involve assembling a composite disk from a set of partition images.
583fn assemble_disk_image(
584 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900585 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000586 temporary_directory: &Path,
587 next_temporary_image_id: &mut u64,
588 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000589) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000590 let image = if !disk.partitions.is_empty() {
591 if disk.image.is_some() {
592 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000593 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000594 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000595 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000596 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000597 }
598
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000599 let composite_image_filenames =
600 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
601 let (image, partition_files) = make_composite_image(
602 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900603 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000604 &composite_image_filenames.composite,
605 &composite_image_filenames.header,
606 &composite_image_filenames.footer,
607 )
608 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100609 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000610 Status::new_service_specific_error_str(
611 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100612 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000613 )
614 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000615
616 // Pass the file descriptors for the various partition files to crosvm when it
617 // is run.
618 indirect_files.extend(partition_files);
619
620 image
621 } else if let Some(image) = &disk.image {
622 clone_file(image)?
623 } else {
624 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000625 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000626 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000627 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000628 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000629 };
630
631 Ok(DiskFile { image, writable: disk.writable })
632}
633
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100634fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
635 if let Some(ref mut params) = vm_config.params {
636 params.push(' ');
637 params.push_str(param)
638 } else {
639 vm_config.params = Some(param.to_owned())
640 }
641}
642
Jooyung Han21e9b922021-06-26 04:14:16 +0900643fn load_app_config(
644 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900645 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900646 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900647) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000648 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
649 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900650 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900651
Shikha Panwar22e70452022-10-10 18:32:55 +0000652 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
653 Some(clone_file(file)?)
654 } else {
655 None
656 };
657
Alan Stokes0d1ef782022-09-27 13:46:35 +0100658 let vm_payload_config = match &config.payload {
659 Payload::ConfigPath(config_path) => {
660 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
661 .with_context(|| format!("Couldn't read config from {}", config_path))?
662 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000663 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100664 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900665
Alan Stokes0d1ef782022-09-27 13:46:35 +0100666 // For now, the only supported OS is Microdroid
667 let os_name = vm_payload_config.os.name.as_str();
668 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000669 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900670 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000671
672 // It is safe to construct a filename based on the os_name because we've already checked that it
673 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900674 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
675 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000676 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900677
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100678 if let Some(custom_config) = &config.customConfig {
679 if let Some(file) = custom_config.customKernelImage.as_ref() {
680 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
681 }
682 vm_config.taskProfiles = custom_config.taskProfiles.clone();
683 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100684
685 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100686 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
687 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100688 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900689
690 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100691 }
692
Andrew Walbrancc045902021-07-27 16:06:17 +0000693 if config.memoryMib > 0 {
694 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000695 }
696
Seungjae Yoo62085c02022-08-12 04:44:52 +0000697 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000698 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000699 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900700
Shikha Panwar22e70452022-10-10 18:32:55 +0000701 // Microdroid takes additional init ramdisk & (optionally) storage image
702 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
703
704 // Include Microdroid payload disk (contains apks, idsigs) in vm config
705 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100706 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900707 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100708 temporary_directory,
709 apk_file,
710 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100711 &vm_payload_config,
712 &mut vm_config,
713 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900714
Andrew Walbrancc0db522021-07-12 17:03:42 +0000715 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900716}
717
Alan Stokes0d1ef782022-09-27 13:46:35 +0100718fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
719 let mut apk_zip = ZipArchive::new(apk_file)?;
720 let config_file = apk_zip.by_name(config_path)?;
721 Ok(serde_json::from_reader(config_file)?)
722}
723
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000724fn create_vm_payload_config(
725 payload_config: &VirtualMachinePayloadConfig,
726) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100727 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
728 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
729 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000730
731 let payload_binary_name = &payload_config.payloadBinaryName;
732 if payload_binary_name.contains('/') {
733 bail!("Payload binary name must not specify a path: {payload_binary_name}");
734 }
735
736 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
737 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100738 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
739 task: Some(task),
740 apexes: vec![],
741 extra_apks: vec![],
742 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900743 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100744 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000745 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100746}
747
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000748/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000749fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000750 temporary_directory: &Path,
751 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000752) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000753 let id = *next_temporary_image_id;
754 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000755 CompositeImageFilenames {
756 composite: temporary_directory.join(format!("composite-{}.img", id)),
757 header: temporary_directory.join(format!("composite-{}-header.img", id)),
758 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
759 }
760}
761
762/// Filenames for a composite disk image, including header and footer partitions.
763#[derive(Clone, Debug, Eq, PartialEq)]
764struct CompositeImageFilenames {
765 /// The composite disk image itself.
766 composite: PathBuf,
767 /// The header partition image.
768 header: PathBuf,
769 /// The footer partition image.
770 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000771}
772
Jiyong Park753553b2021-07-12 21:21:09 +0900773/// Checks whether the caller has a specific permission
774fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100775 let calling_pid = get_calling_pid();
776 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900777 // Root can do anything
778 if calling_uid == 0 {
779 return Ok(());
780 }
781 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
782 binder::get_interface("permission")?;
783 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000784 Ok(())
785 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000786 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900787 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000788 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900789 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000790 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000791}
792
Jiyong Park753553b2021-07-12 21:21:09 +0900793/// Check whether the caller of the current Binder method is allowed to manage VMs
794fn check_manage_access() -> binder::Result<()> {
795 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
796}
797
Inseob Kim1119d702022-05-02 18:01:58 +0900798/// Check whether the caller of the current Binder method is allowed to create custom VMs
799fn check_use_custom_virtual_machine() -> binder::Result<()> {
800 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
801}
802
Alan Stokes185fe112023-01-10 16:20:55 +0000803/// Return whether a partition is exempt from selinux label checks, because we know that it does
804/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100805fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000806 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100807 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000808 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100809 || label == "microdroid-apk-idsig"
810 || label == "payload-metadata"
811 || label.starts_with("extra-idsig-")
812}
813
Alan Stokes185fe112023-01-10 16:20:55 +0000814/// Check that a file SELinux label is acceptable.
815///
816/// We only want to allow code in a VM to be sourced from places that apps, and the
817/// system, do not have write access to.
818///
819/// Note that sepolicy must also grant read access for these types to both virtualization
820/// service and crosvm.
821///
822/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
823/// user devices (W^X).
824fn check_label_is_allowed(context: &SeContext) -> Result<()> {
825 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100826 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100827 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000828 | "staging_data_file" // updated/staged APEX images
829 | "system_file" // immutable dm-verity protected partition
830 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100831 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000832 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900833 }
834}
835
Alan Stokes185fe112023-01-10 16:20:55 +0000836fn check_label_for_partition(partition: &Partition) -> Result<()> {
837 let file = partition.image.as_ref().unwrap().as_ref();
838 check_label_is_allowed(&getfilecon(file)?)
839 .with_context(|| format!("Partition {} invalid", &partition.label))
840}
841
842fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
843 if let Some(f) = kernel {
844 check_label_for_file(f, "kernel")?;
845 }
846 if let Some(f) = initrd {
847 check_label_for_file(f, "initrd")?;
848 }
849 Ok(())
850}
851fn check_label_for_file(file: &File, name: &str) -> Result<()> {
852 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
853}
854
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000855/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
856#[derive(Debug)]
857struct VirtualMachine {
858 instance: Arc<VmInstance>,
859}
860
861impl VirtualMachine {
862 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000863 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000864 }
865}
866
867impl Interface for VirtualMachine {}
868
869impl IVirtualMachine for VirtualMachine {
870 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900871 // Don't check permission. The owner of the VM might have passed this binder object to
872 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000873 Ok(self.instance.cid as i32)
874 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000875
Andrew Walbran6b650662021-09-07 13:13:23 +0000876 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900877 // Don't check permission. The owner of the VM might have passed this binder object to
878 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000879 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000880 }
881
882 fn registerCallback(
883 &self,
884 callback: &Strong<dyn IVirtualMachineCallback>,
885 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900886 // Don't check permission. The owner of the VM might have passed this binder object to
887 // others.
888 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000889 // TODO: Should this give an error if the VM is already dead?
890 self.instance.callbacks.add(callback.clone());
891 Ok(())
892 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000893
Andrew Walbranf8d94112021-09-07 11:45:36 +0000894 fn start(&self) -> binder::Result<()> {
895 self.instance.start().map_err(|e| {
896 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000897 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000898 })
899 }
900
Inseob Kima446f802022-07-11 19:46:37 +0900901 fn stop(&self) -> binder::Result<()> {
902 self.instance.kill().map_err(|e| {
903 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000904 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900905 })
906 }
907
Keir Frasercdd4b112022-11-24 14:02:25 +0000908 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
909 self.instance.trim_memory(level).map_err(|e| {
910 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
911 Status::new_service_specific_error_str(-1, Some(e.to_string()))
912 })
913 }
914
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000915 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000916 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000917 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000918 }
Alan Stokes10c47672022-12-13 17:17:08 +0000919 let port = port as u32;
920 if port < 1024 {
921 return Err(Status::new_service_specific_error_str(
922 -1,
923 Some(format!("Can't connect to privileged port {port}")),
924 ));
925 }
926 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
927 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
928 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000929 Ok(vsock_stream_to_pfd(stream))
930 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000931}
932
933impl Drop for VirtualMachine {
934 fn drop(&mut self) {
935 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900936 if let Err(e) = self.instance.kill() {
937 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
938 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000939 }
940}
941
942/// A set of Binders to be called back in response to various events on the VM, such as when it
943/// dies.
944#[derive(Debug, Default)]
945pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
946
947impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900948 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100949 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900950 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900951 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100952 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100953 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900954 }
955 }
956 }
957
Inseob Kim14cb8692021-08-31 21:50:39 +0900958 /// Call all registered callbacks to notify that the payload is ready to serve.
959 pub fn notify_payload_ready(&self, cid: Cid) {
960 let callbacks = &*self.0.lock().unwrap();
961 for callback in callbacks {
962 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100963 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900964 }
965 }
966 }
967
Inseob Kim2444af92021-08-31 01:22:50 +0900968 /// Call all registered callbacks to notify that the payload has finished.
969 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
970 let callbacks = &*self.0.lock().unwrap();
971 for callback in callbacks {
972 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100973 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900974 }
975 }
976 }
977
Jooyung Handd0a1732021-11-23 15:26:20 +0900978 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100979 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900980 let callbacks = &*self.0.lock().unwrap();
981 for callback in callbacks {
982 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100983 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900984 }
985 }
986 }
987
Andrew Walbrandae07162021-03-12 17:05:20 +0000988 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000989 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000990 let callbacks = &*self.0.lock().unwrap();
991 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000992 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100993 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000994 }
995 }
996 }
997
998 /// Add a new callback to the set.
999 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1000 self.0.lock().unwrap().push(callback);
1001 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001002}
1003
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001004/// The mutable state of the VirtualizationService. There should only be one instance of this
1005/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001006#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001007struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +00001008 /// The VMs which have been started. When VMs are started a weak reference is added to this list
1009 /// while a strong reference is returned to the caller over Binder. Once all copies of the
1010 /// Binder client are dropped the weak reference here will become invalid, and will be removed
1011 /// from the list opportunistically the next time `add_vm` is called.
1012 vms: Vec<Weak<VmInstance>>,
1013}
1014
1015impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001016 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001017 fn vms(&self) -> Vec<Arc<VmInstance>> {
1018 // Attempt to upgrade the weak pointers to strong pointers.
1019 self.vms.iter().filter_map(Weak::upgrade).collect()
1020 }
1021
1022 /// Add a new VM to the list.
1023 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1024 // Garbage collect any entries from the stored list which no longer exist.
1025 self.vms.retain(|vm| vm.strong_count() > 0);
1026
1027 // Actually add the new VM.
1028 self.vms.push(vm);
1029 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001030
Jiyong Park8611a6c2021-07-09 18:17:44 +09001031 /// Get a VM that corresponds to the given cid
1032 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1033 self.vms().into_iter().find(|vm| vm.cid == cid)
1034 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001035}
1036
Andrew Walbran6b650662021-09-07 13:13:23 +00001037/// Gets the `VirtualMachineState` of the given `VmInstance`.
1038fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001039 match &*instance.vm_state.lock().unwrap() {
1040 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1041 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001042 PayloadState::Starting => VirtualMachineState::STARTING,
1043 PayloadState::Started => VirtualMachineState::STARTED,
1044 PayloadState::Ready => VirtualMachineState::READY,
1045 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001046 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001047 },
1048 VmState::Dead => VirtualMachineState::DEAD,
1049 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001050 }
1051}
1052
David Brazdilf50c7a62023-04-19 14:22:42 +00001053/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
1054pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
1055 file.as_ref().try_clone().map_err(|e| {
1056 Status::new_exception_str(
1057 ExceptionCode::BAD_PARCELABLE,
1058 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
1059 )
1060 })
1061}
1062
Andrew Walbrand3a84182021-09-07 14:48:52 +00001063/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1064fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1065 file.as_ref().map(clone_file).transpose()
1066}
1067
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001068/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1069fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1070 // SAFETY: ownership is transferred from stream to f
1071 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1072 ParcelFileDescriptor::new(f)
1073}
1074
Jiyong Parkdcf17412022-02-08 15:07:23 +09001075/// Parses the platform version requirement string.
1076fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1077 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001078 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001079 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001080 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001081 )
1082 })
1083}
1084
Jiyong Parked180932023-02-24 19:55:41 +09001085/// Create the empty ramdump file
1086fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1087 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1088 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1089 // owner) for readout.
1090 let ramdump_path = temporary_directory.join("ramdump");
1091 let ramdump = File::create(ramdump_path).map_err(|e| {
1092 error!("Failed to prepare ramdump file: {:?}", e);
1093 Status::new_service_specific_error_str(
1094 -1,
1095 Some(format!("Failed to prepare ramdump file: {:?}", e)),
1096 )
1097 })?;
1098 Ok(ramdump)
1099}
1100
Nikita Ioffe5776f082023-02-10 21:38:26 +00001101fn is_protected(config: &VirtualMachineConfig) -> bool {
1102 match config {
1103 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1104 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1105 }
1106}
1107
1108fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1109 if is_protected(config) {
1110 return Err(Status::new_exception_str(
1111 ExceptionCode::SECURITY,
1112 Some("can't use gdb with protected VMs"),
1113 ));
1114 }
1115
1116 match config {
1117 VirtualMachineConfig::RawConfig(_) => Ok(()),
1118 VirtualMachineConfig::AppConfig(config) => {
1119 if config.debugLevel != DebugLevel::FULL {
1120 Err(Status::new_exception_str(
1121 ExceptionCode::SECURITY,
1122 Some("can't use gdb with non-debuggable VMs"),
1123 ))
1124 } else {
1125 Ok(())
1126 }
1127 }
1128 }
1129}
1130
1131fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1132 match config {
1133 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001134 VirtualMachineConfig::AppConfig(config) => {
1135 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1136 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001137 }
1138}
1139
Inseob Kim0168b462022-12-27 14:54:35 +09001140fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001141 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001142 fd: Option<&ParcelFileDescriptor>,
1143 tag: String,
1144) -> Result<Option<File>, Status> {
1145 if let Some(fd) = fd {
1146 return Ok(Some(clone_file(fd)?));
1147 }
1148
Jaewan Kim61f86142023-03-28 15:12:52 +09001149 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001150 return Ok(None);
1151 };
Inseob Kim0168b462022-12-27 14:54:35 +09001152
1153 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
1154 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
1155 })?;
1156
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001157 // 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 +09001158 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001159 // 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 +09001160 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1161
1162 std::thread::spawn(move || loop {
1163 let mut buf = vec![];
1164 match reader.read_until(b'\n', &mut buf) {
1165 Ok(0) => {
1166 // EOF
1167 return;
1168 }
1169 Ok(size) => {
1170 if buf[size - 1] == b'\n' {
1171 buf.pop();
1172 }
1173 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1174 }
1175 Err(e) => {
1176 error!("Could not read console pipe: {:?}", e);
1177 return;
1178 }
1179 };
1180 });
1181
1182 Ok(Some(write_fd))
1183}
1184
Jooyung Han35edb8f2021-07-01 16:17:16 +09001185/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1186/// it doesn't require that T implements Clone.
1187enum BorrowedOrOwned<'a, T> {
1188 Borrowed(&'a T),
1189 Owned(T),
1190}
1191
1192impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1193 fn as_ref(&self) -> &T {
1194 match self {
1195 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001196 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001197 }
1198 }
1199}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001200
1201/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1202#[derive(Debug, Default)]
1203struct VirtualMachineService {
1204 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001205 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001206}
1207
1208impl Interface for VirtualMachineService {}
1209
1210impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001211 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1212 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001213 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001214 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001215 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1216 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1217 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001218 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001219
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001220 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1221 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001222 Ok(())
1223 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001224 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001225 Err(Status::new_service_specific_error_str(
1226 -1,
1227 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001228 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001229 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001230 }
Inseob Kim2444af92021-08-31 01:22:50 +09001231
Inseob Kimc7d28c72021-10-25 14:28:10 +00001232 fn notifyPayloadReady(&self) -> binder::Result<()> {
1233 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001234 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001235 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001236 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1237 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1238 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001239 vm.callbacks.notify_payload_ready(cid);
1240 Ok(())
1241 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001242 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001243 Err(Status::new_service_specific_error_str(
1244 -1,
1245 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001246 ))
1247 }
1248 }
1249
Inseob Kimc7d28c72021-10-25 14:28:10 +00001250 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1251 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001252 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001253 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001254 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1255 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1256 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001257 vm.callbacks.notify_payload_finished(cid, exit_code);
1258 Ok(())
1259 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001260 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001261 Err(Status::new_service_specific_error_str(
1262 -1,
1263 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001264 ))
1265 }
1266 }
1267
Alan Stokes2bead0d2022-09-05 16:58:34 +01001268 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001269 let cid = self.cid;
1270 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001271 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001272 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1273 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1274 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001275 vm.callbacks.notify_error(cid, error_code, message);
1276 Ok(())
1277 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001278 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001279 Err(Status::new_service_specific_error_str(
1280 -1,
1281 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001282 ))
1283 }
1284 }
Alice Wangc2fec932023-02-23 16:24:02 +00001285
1286 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
1287 let cid = self.cid;
1288 let Some(vm) = self.state.lock().unwrap().get_vm(cid) else {
1289 error!("requestCertificate is called from an unknown CID {cid}");
1290 return Err(Status::new_service_specific_error_str(
1291 -1,
1292 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim53d0b212023-07-20 16:58:37 +09001293 ));
Alice Wangc2fec932023-02-23 16:24:02 +00001294 };
1295 let instance_img_path = vm.temporary_directory.join("rkpvm_instance.img");
1296 let instance_img = OpenOptions::new()
1297 .create(true)
1298 .read(true)
1299 .write(true)
1300 .open(instance_img_path)
1301 .map_err(|e| {
1302 error!("Failed to create rkpvm_instance.img file: {:?}", e);
1303 Status::new_service_specific_error_str(
1304 -1,
1305 Some(format!("Failed to create rkpvm_instance.img file: {:?}", e)),
1306 )
1307 })?;
1308 GLOBAL_SERVICE.requestCertificate(csr, &ParcelFileDescriptor::new(instance_img))
1309 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001310}
1311
1312impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001313 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001314 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001315 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001316 BinderFeatures::default(),
1317 )
1318 }
1319}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001320
1321#[cfg(test)]
1322mod tests {
1323 use super::*;
1324
1325 #[test]
1326 fn test_is_allowed_label_for_partition() -> Result<()> {
1327 let expected_results = vec![
1328 ("u:object_r:system_file:s0", true),
1329 ("u:object_r:apk_data_file:s0", true),
1330 ("u:object_r:app_data_file:s0", false),
1331 ("u:object_r:app_data_file:s0:c512,c768", false),
1332 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1333 ("invalid", false),
1334 ("user:role:apk_data_file:severity:categories", true),
1335 ("user:role:apk_data_file:severity:categories:extraneous", false),
1336 ];
1337
1338 for (label, expected_valid) in expected_results {
1339 let context = SeContext::new(label)?;
1340 let result = check_label_is_allowed(&context);
1341 if expected_valid {
1342 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1343 } else if result.is_ok() {
1344 bail!("Expected label {} to be disallowed", label);
1345 }
1346 }
1347 Ok(())
1348 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001349
1350 #[test]
1351 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1352 let apk = tempfile::tempfile().unwrap();
1353 let idsig = tempfile::tempfile().unwrap();
1354
1355 let ret = create_or_update_idsig_file(
1356 &ParcelFileDescriptor::new(apk),
1357 &ParcelFileDescriptor::new(idsig),
1358 );
1359 assert!(ret.is_err(), "should fail");
1360 Ok(())
1361 }
1362
1363 #[test]
1364 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1365 let tmp_dir = tempfile::TempDir::new().unwrap();
1366 let apk = File::open(tmp_dir.path()).unwrap();
1367 let idsig = tempfile::tempfile().unwrap();
1368
1369 let ret = create_or_update_idsig_file(
1370 &ParcelFileDescriptor::new(apk),
1371 &ParcelFileDescriptor::new(idsig),
1372 );
1373 assert!(ret.is_err(), "should fail");
1374 Ok(())
1375 }
1376
1377 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1378 /// on ext4 filesystem is passed.
1379 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1380 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1381 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1382 #[test]
1383 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1384 // APEXes are backed by the ext4.
1385 let apk = File::open("/apex/com.android.virt/").unwrap();
1386 let idsig = tempfile::tempfile().unwrap();
1387
1388 let ret = create_or_update_idsig_file(
1389 &ParcelFileDescriptor::new(apk),
1390 &ParcelFileDescriptor::new(idsig),
1391 );
1392 assert!(ret.is_err(), "should fail");
1393 Ok(())
1394 }
Jiyong Park8d192952023-06-26 14:29:51 +09001395
1396 #[test]
1397 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1398 use std::io::Seek;
1399
1400 // Pick any APK
1401 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1402 let mut idsig = tempfile::tempfile().unwrap();
1403
1404 create_or_update_idsig_file(
1405 &ParcelFileDescriptor::new(apk.try_clone()?),
1406 &ParcelFileDescriptor::new(idsig.try_clone()?),
1407 )?;
1408 let modified_orig = idsig.metadata()?.modified()?;
1409 apk.rewind()?;
1410 idsig.rewind()?;
1411
1412 // Call the function again
1413 create_or_update_idsig_file(
1414 &ParcelFileDescriptor::new(apk.try_clone()?),
1415 &ParcelFileDescriptor::new(idsig.try_clone()?),
1416 )?;
1417 let modified_new = idsig.metadata()?.modified()?;
1418 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1419 Ok(())
1420 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001421
1422 #[test]
1423 fn test_append_kernel_param_first_param() {
1424 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1425 append_kernel_param("foo=1", &mut vm_config);
1426 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1427 }
1428
1429 #[test]
1430 fn test_append_kernel_param() {
1431 let mut vm_config =
1432 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1433 append_kernel_param("bar=42", &mut vm_config);
1434 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1435 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001436}