blob: 4bc25daca8d5bb91ce42e3faeda063998c72f951 [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;
Shikha Panwar22e70452022-10-10 18:32:55 +000023use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
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::{
David Brazdil7d1e5ec2023-02-06 17:56:29 +000031 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000032 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010033 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000034 IVirtualMachineCallback::IVirtualMachineCallback,
35 IVirtualizationService::IVirtualizationService,
Keir Frasercdd4b112022-11-24 14:02:25 +000036 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090037 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000038 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090039 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090040 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000041 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010042 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090043 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000044 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090045};
David Brazdilafc9a9e2023-01-12 16:08:10 +000046use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090047use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000048 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090049};
Alan Stokes25f69362023-03-06 16:51:54 +000050use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090051use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010052use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000053 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
54 Status, StatusCode, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000055};
David Brazdil49f96f52022-12-16 21:29:13 +000056use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000057use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090058use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090059use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000060use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000061use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090062use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000063use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000064use std::ffi::CStr;
David Brazdilafc9a9e2023-01-12 16:08:10 +000065use std::fs::{read_dir, remove_file, File, OpenOptions};
Alice Wang0547e862023-04-18 09:32:26 +000066use std::io::{BufRead, BufReader, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000067use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000068use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000069use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000070use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000071use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000072use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000073use vsock::VsockStream;
Alice Wang0547e862023-04-18 09:32:26 +000074use vsutil::{clone_file, init_writable_partition};
Jooyung Han35edb8f2021-07-01 16:17:16 +090075use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000076
David Brazdil41d1a872022-10-05 14:44:19 +010077/// The unique ID of a VM used (together with a port number) for vsock communication.
78pub type Cid = u32;
79
David Brazdil4b4c5102022-12-19 22:56:20 +000080pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
81
Jooyung Han95884632021-07-06 22:27:54 +090082/// The size of zero.img.
83/// Gaps in composite disk images are filled with a shared zero.img.
84const ZERO_FILLER_SIZE: u64 = 4096;
85
Alan Stokes0d1ef782022-09-27 13:46:35 +010086const MICRODROID_OS_NAME: &str = "microdroid";
87
David Brazdil49f96f52022-12-16 21:29:13 +000088lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +000089 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
90 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
91 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +000092}
93
Nikita Ioffef1ce9872022-12-09 13:31:59 +000094fn create_or_update_idsig_file(
95 input_fd: &ParcelFileDescriptor,
96 idsig_fd: &ParcelFileDescriptor,
97) -> Result<()> {
98 let mut input = clone_file(input_fd)?;
99 let metadata = input.metadata().context("failed to get input metadata")?;
100 if !metadata.is_file() {
101 bail!("input is not a regular file");
102 }
Alan Stokes25f69362023-03-06 16:51:54 +0000103 let mut sig =
104 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
105 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000106
107 let mut output = clone_file(idsig_fd)?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000108 output.set_len(0).context("failed to set_len on the idsig output")?;
109 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000110 Ok(())
111}
112
Alan Stokes25f69362023-03-06 16:51:54 +0000113fn get_current_sdk() -> Result<u32> {
114 let current_sdk = system_properties::read("ro.build.version.sdk")?;
115 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
116 current_sdk.parse().context("Malformed SDK version")
117}
118
David Brazdil4b4c5102022-12-19 22:56:20 +0000119pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
120 for dir_entry in read_dir(path)? {
121 remove_file(dir_entry?.path())?;
122 }
123 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100124}
125
David Brazdil528e0472022-10-10 15:06:02 +0100126/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000127#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000128pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900129 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000130}
131
Shikha Panward8e35422021-10-11 13:51:27 +0000132impl Interface for VirtualizationService {
133 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
134 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
135 let state = &mut *self.state.lock().unwrap();
136 let vms = state.vms();
137 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
138 for vm in vms {
139 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
140 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
141 .or(Err(StatusCode::UNKNOWN_ERROR))?;
142 writeln!(file, "\tPayload state {:?}", vm.payload_state())
143 .or(Err(StatusCode::UNKNOWN_ERROR))?;
144 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
145 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
146 .or(Err(StatusCode::UNKNOWN_ERROR))?;
147 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
148 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000149 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
150 .or(Err(StatusCode::UNKNOWN_ERROR))?;
151 }
152 Ok(())
153 }
154}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000155
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000156impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000157 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
158 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000159 ///
160 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000161 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000162 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000163 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900164 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000165 log_fd: Option<&ParcelFileDescriptor>,
166 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000167 let mut is_protected = false;
168 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000169 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000170 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000171 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000172
Andrew Walbrandff3b942021-06-09 15:20:36 +0000173 /// Initialise an empty partition image of the given size to be used as a writable partition.
174 fn initializeWritablePartition(
175 &self,
176 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000177 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900178 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000179 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900180 check_manage_access()?;
Alice Wang0547e862023-04-18 09:32:26 +0000181 init_writable_partition(image_fd, size_bytes, partition_type)
Andrew Walbrandff3b942021-06-09 15:20:36 +0000182 }
183
Jiyong Park0a248432021-08-20 23:32:39 +0900184 /// Creates or update the idsig file by digesting the input APK file.
185 fn createOrUpdateIdsigFile(
186 &self,
187 input_fd: &ParcelFileDescriptor,
188 idsig_fd: &ParcelFileDescriptor,
189 ) -> binder::Result<()> {
190 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
191 // idsig_fd is different from APK digest in input_fd
192
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900193 check_manage_access()?;
194
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000195 create_or_update_idsig_file(input_fd, idsig_fd)
196 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900197 Ok(())
198 }
199
Andrew Walbran320b5602021-03-04 16:11:12 +0000200 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
201 /// and as such is only permitted from the shell user.
202 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000203 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000204 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000205 }
206}
207
Jiyong Park8611a6c2021-07-09 18:17:44 +0900208impl VirtualizationService {
209 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000210 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900211 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000212
David Brazdil209074a2023-01-12 16:44:51 +0000213 fn create_vm_context(
214 &self,
215 requester_debug_pid: pid_t,
216 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000217 const NUM_ATTEMPTS: usize = 5;
218
219 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000220 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000221 let cid = vm_context.getCid()? as Cid;
222 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000223 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
224
225 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000226 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000227 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000228 Ok(vm_server) => {
229 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000230 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000231 }
232 Err(err) => {
233 warn!("Could not start RpcServer on port {}: {}", port, err);
234 }
235 }
236 }
David Brazdil209074a2023-01-12 16:44:51 +0000237 Err(Status::new_service_specific_error_str(
238 -1,
239 Some("Too many attempts to create VM context failed."),
240 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000241 }
242
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000243 fn create_vm_internal(
244 &self,
245 config: &VirtualMachineConfig,
246 console_fd: Option<&ParcelFileDescriptor>,
247 log_fd: Option<&ParcelFileDescriptor>,
248 is_protected: &mut bool,
249 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000250 let requester_uid = get_calling_uid();
251 let requester_debug_pid = get_calling_pid();
252
253 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
254 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900255
Alan Stokes7bc146c2022-10-20 17:10:32 +0100256 let is_custom = match config {
257 VirtualMachineConfig::RawConfig(_) => true,
258 VirtualMachineConfig::AppConfig(config) => {
259 // Some features are reserved for platform apps only, even when using
260 // VirtualMachineAppConfig:
261 // - controlling CPUs;
Nikita Ioffe5776f082023-02-10 21:38:26 +0000262 // - specifying a config file in the APK;
263 // - gdbPort is set, meaning that crosvm will start a gdb server.
264 !config.taskProfiles.is_empty()
265 || matches!(config.payload, Payload::ConfigPath(_))
266 || config.gdbPort > 0
Inseob Kim1119d702022-05-02 18:01:58 +0900267 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100268 };
269 if is_custom {
270 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900271 }
272
Nikita Ioffe5776f082023-02-10 21:38:26 +0000273 let gdb_port = extract_gdb_port(config);
274
275 // Additional permission checks if caller request gdb.
276 if gdb_port.is_some() {
277 check_gdb_allowed(config)?;
278 }
279
Jaewan Kim61f86142023-03-28 15:12:52 +0900280 let debug_level = match config {
281 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
282 _ => DebugLevel::NONE,
283 };
284 let debug_config = DebugConfig::new(debug_level);
285
286 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900287 Some(prepare_ramdump_file(&temporary_directory)?)
288 } else {
289 None
290 };
291
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000292 let state = &mut *self.state.lock().unwrap();
Inseob Kim0168b462022-12-27 14:54:35 +0900293 let console_fd =
Jaewan Kim61f86142023-03-28 15:12:52 +0900294 clone_or_prepare_logger_fd(&debug_config, console_fd, format!("Console({})", cid))?;
295 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000296
297 // Counter to generate unique IDs for temporary image files.
298 let mut next_temporary_image_id = 0;
299 // Files which are referred to from composite images. These must be mapped to the crosvm
300 // child process, and not closed before it is started.
301 let mut indirect_files = vec![];
302
Alan Stokes7bc146c2022-10-20 17:10:32 +0100303 let (is_app_config, config) = match config {
304 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
305 VirtualMachineConfig::AppConfig(config) => {
Jaewan Kim61f86142023-03-28 15:12:52 +0900306 let config =
307 load_app_config(config, &debug_config, &temporary_directory).map_err(|e| {
308 *is_protected = config.protectedVm;
309 let message = format!("Failed to load app config: {:?}", e);
310 error!("{}", message);
311 Status::new_service_specific_error_str(-1, Some(message))
312 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100313 (true, BorrowedOrOwned::Owned(config))
314 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000315 };
316 let config = config.as_ref();
317 *is_protected = config.protectedVm;
318
319 // Check if partition images are labeled incorrectly. This is to prevent random images
320 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100321 // being loaded in a pVM. This applies to everything in the raw config, and everything but
322 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000323 config
324 .disks
325 .iter()
326 .flat_map(|disk| disk.partitions.iter())
327 .filter(|partition| {
328 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100329 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000330 } else {
331 true // all partitions are checked
332 }
333 })
334 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100335 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000336
Alan Stokes185fe112023-01-10 16:20:55 +0000337 let kernel = maybe_clone_file(&config.kernel)?;
338 let initrd = maybe_clone_file(&config.initrd)?;
339
340 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
341 if config.protectedVm {
342 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
343 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
344 })?;
345 }
346
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000347 let zero_filler_path = temporary_directory.join("zero.img");
348 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100349 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000350 Status::new_service_specific_error_str(
351 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100352 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000353 )
354 })?;
355
356 // Assemble disk images if needed.
357 let disks = config
358 .disks
359 .iter()
360 .map(|disk| {
361 assemble_disk_image(
362 disk,
363 &zero_filler_path,
364 &temporary_directory,
365 &mut next_temporary_image_id,
366 &mut indirect_files,
367 )
368 })
369 .collect::<Result<Vec<DiskFile>, _>>()?;
370
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000371 let (cpus, host_cpu_topology) = match config.cpuTopology {
372 CpuTopology::MATCH_HOST => (None, true),
373 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
374 val => {
375 error!("Unexpected value of CPU topology: {:?}", val);
376 return Err(Status::new_service_specific_error_str(
377 -1,
378 Some(format!("Failed to parse CPU topology value: {:?}", val)),
379 ));
380 }
381 };
382
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000383 // Actually start the VM.
384 let crosvm_config = CrosvmConfig {
385 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000386 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000387 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000388 kernel,
389 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000390 disks,
391 params: config.params.to_owned(),
392 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900393 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000394 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000395 cpus,
396 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900397 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000398 console_fd,
399 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900400 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000401 indirect_files,
402 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900403 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000404 gdb_port,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000405 };
406 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100407 VmInstance::new(
408 crosvm_config,
409 temporary_directory,
410 requester_uid,
411 requester_debug_pid,
412 vm_context,
413 )
414 .map_err(|e| {
415 error!("Failed to create VM with config {:?}: {:?}", config, e);
416 Status::new_service_specific_error_str(
417 -1,
418 Some(format!("Failed to create VM: {:?}", e)),
419 )
420 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000421 );
422 state.add_vm(Arc::downgrade(&instance));
423 Ok(VirtualMachine::create(instance))
424 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900425}
426
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000427fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900428 let file = OpenOptions::new()
429 .create_new(true)
430 .read(true)
431 .write(true)
432 .open(zero_filler_path)
433 .with_context(|| "Failed to create zero.img")?;
434 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000435 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900436}
437
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000438/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
439///
440/// This may involve assembling a composite disk from a set of partition images.
441fn assemble_disk_image(
442 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900443 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000444 temporary_directory: &Path,
445 next_temporary_image_id: &mut u64,
446 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000447) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000448 let image = if !disk.partitions.is_empty() {
449 if disk.image.is_some() {
450 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000451 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000452 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000453 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000454 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000455 }
456
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000457 let composite_image_filenames =
458 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
459 let (image, partition_files) = make_composite_image(
460 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900461 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000462 &composite_image_filenames.composite,
463 &composite_image_filenames.header,
464 &composite_image_filenames.footer,
465 )
466 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100467 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000468 Status::new_service_specific_error_str(
469 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100470 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000471 )
472 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000473
474 // Pass the file descriptors for the various partition files to crosvm when it
475 // is run.
476 indirect_files.extend(partition_files);
477
478 image
479 } else if let Some(image) = &disk.image {
480 clone_file(image)?
481 } else {
482 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000483 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000484 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000485 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000486 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000487 };
488
489 Ok(DiskFile { image, writable: disk.writable })
490}
491
Jooyung Han21e9b922021-06-26 04:14:16 +0900492fn load_app_config(
493 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900494 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900495 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900496) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000497 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
498 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900499 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900500
Shikha Panwar22e70452022-10-10 18:32:55 +0000501 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
502 Some(clone_file(file)?)
503 } else {
504 None
505 };
506
Alan Stokes0d1ef782022-09-27 13:46:35 +0100507 let vm_payload_config = match &config.payload {
508 Payload::ConfigPath(config_path) => {
509 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
510 .with_context(|| format!("Couldn't read config from {}", config_path))?
511 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000512 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100513 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900514
Alan Stokes0d1ef782022-09-27 13:46:35 +0100515 // For now, the only supported OS is Microdroid
516 let os_name = vm_payload_config.os.name.as_str();
517 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000518 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900519 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000520
521 // It is safe to construct a filename based on the os_name because we've already checked that it
522 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900523 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
524 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000525 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900526
Andrew Walbrancc045902021-07-27 16:06:17 +0000527 if config.memoryMib > 0 {
528 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000529 }
530
Seungjae Yoo62085c02022-08-12 04:44:52 +0000531 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000532 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000533 vm_config.cpuTopology = config.cpuTopology;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900534 vm_config.taskProfiles = config.taskProfiles.clone();
Nikita Ioffe5776f082023-02-10 21:38:26 +0000535 vm_config.gdbPort = config.gdbPort;
Jiyong Park032615f2022-01-10 13:55:34 +0900536
Shikha Panwar22e70452022-10-10 18:32:55 +0000537 // Microdroid takes additional init ramdisk & (optionally) storage image
538 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
539
540 // Include Microdroid payload disk (contains apks, idsigs) in vm config
541 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100542 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900543 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100544 temporary_directory,
545 apk_file,
546 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100547 &vm_payload_config,
548 &mut vm_config,
549 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900550
Andrew Walbrancc0db522021-07-12 17:03:42 +0000551 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900552}
553
Alan Stokes0d1ef782022-09-27 13:46:35 +0100554fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
555 let mut apk_zip = ZipArchive::new(apk_file)?;
556 let config_file = apk_zip.by_name(config_path)?;
557 Ok(serde_json::from_reader(config_file)?)
558}
559
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000560fn create_vm_payload_config(
561 payload_config: &VirtualMachinePayloadConfig,
562) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100563 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
564 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
565 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000566
567 let payload_binary_name = &payload_config.payloadBinaryName;
568 if payload_binary_name.contains('/') {
569 bail!("Payload binary name must not specify a path: {payload_binary_name}");
570 }
571
572 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
573 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100574 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
575 task: Some(task),
576 apexes: vec![],
577 extra_apks: vec![],
578 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900579 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100580 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000581 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100582}
583
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000584/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000585fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000586 temporary_directory: &Path,
587 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000588) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000589 let id = *next_temporary_image_id;
590 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000591 CompositeImageFilenames {
592 composite: temporary_directory.join(format!("composite-{}.img", id)),
593 header: temporary_directory.join(format!("composite-{}-header.img", id)),
594 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
595 }
596}
597
598/// Filenames for a composite disk image, including header and footer partitions.
599#[derive(Clone, Debug, Eq, PartialEq)]
600struct CompositeImageFilenames {
601 /// The composite disk image itself.
602 composite: PathBuf,
603 /// The header partition image.
604 header: PathBuf,
605 /// The footer partition image.
606 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000607}
608
Jiyong Park753553b2021-07-12 21:21:09 +0900609/// Checks whether the caller has a specific permission
610fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100611 let calling_pid = get_calling_pid();
612 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900613 // Root can do anything
614 if calling_uid == 0 {
615 return Ok(());
616 }
617 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
618 binder::get_interface("permission")?;
619 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000620 Ok(())
621 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000622 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900623 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000624 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900625 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000626 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000627}
628
Jiyong Park753553b2021-07-12 21:21:09 +0900629/// Check whether the caller of the current Binder method is allowed to manage VMs
630fn check_manage_access() -> binder::Result<()> {
631 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
632}
633
Inseob Kim1119d702022-05-02 18:01:58 +0900634/// Check whether the caller of the current Binder method is allowed to create custom VMs
635fn check_use_custom_virtual_machine() -> binder::Result<()> {
636 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
637}
638
Alan Stokes185fe112023-01-10 16:20:55 +0000639/// Return whether a partition is exempt from selinux label checks, because we know that it does
640/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100641fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000642 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100643 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000644 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100645 || label == "microdroid-apk-idsig"
646 || label == "payload-metadata"
647 || label.starts_with("extra-idsig-")
648}
649
Alan Stokes185fe112023-01-10 16:20:55 +0000650/// Check that a file SELinux label is acceptable.
651///
652/// We only want to allow code in a VM to be sourced from places that apps, and the
653/// system, do not have write access to.
654///
655/// Note that sepolicy must also grant read access for these types to both virtualization
656/// service and crosvm.
657///
658/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
659/// user devices (W^X).
660fn check_label_is_allowed(context: &SeContext) -> Result<()> {
661 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100662 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100663 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000664 | "staging_data_file" // updated/staged APEX images
665 | "system_file" // immutable dm-verity protected partition
666 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100667 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000668 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900669 }
670}
671
Alan Stokes185fe112023-01-10 16:20:55 +0000672fn check_label_for_partition(partition: &Partition) -> Result<()> {
673 let file = partition.image.as_ref().unwrap().as_ref();
674 check_label_is_allowed(&getfilecon(file)?)
675 .with_context(|| format!("Partition {} invalid", &partition.label))
676}
677
678fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
679 if let Some(f) = kernel {
680 check_label_for_file(f, "kernel")?;
681 }
682 if let Some(f) = initrd {
683 check_label_for_file(f, "initrd")?;
684 }
685 Ok(())
686}
687fn check_label_for_file(file: &File, name: &str) -> Result<()> {
688 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
689}
690
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000691/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
692#[derive(Debug)]
693struct VirtualMachine {
694 instance: Arc<VmInstance>,
695}
696
697impl VirtualMachine {
698 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000699 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000700 }
701}
702
703impl Interface for VirtualMachine {}
704
705impl IVirtualMachine for VirtualMachine {
706 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900707 // Don't check permission. The owner of the VM might have passed this binder object to
708 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000709 Ok(self.instance.cid as i32)
710 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000711
Andrew Walbran6b650662021-09-07 13:13:23 +0000712 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900713 // Don't check permission. The owner of the VM might have passed this binder object to
714 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000715 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000716 }
717
718 fn registerCallback(
719 &self,
720 callback: &Strong<dyn IVirtualMachineCallback>,
721 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900722 // Don't check permission. The owner of the VM might have passed this binder object to
723 // others.
724 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000725 // TODO: Should this give an error if the VM is already dead?
726 self.instance.callbacks.add(callback.clone());
727 Ok(())
728 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000729
Andrew Walbranf8d94112021-09-07 11:45:36 +0000730 fn start(&self) -> binder::Result<()> {
731 self.instance.start().map_err(|e| {
732 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000733 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000734 })
735 }
736
Inseob Kima446f802022-07-11 19:46:37 +0900737 fn stop(&self) -> binder::Result<()> {
738 self.instance.kill().map_err(|e| {
739 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000740 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900741 })
742 }
743
Keir Frasercdd4b112022-11-24 14:02:25 +0000744 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
745 self.instance.trim_memory(level).map_err(|e| {
746 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
747 Status::new_service_specific_error_str(-1, Some(e.to_string()))
748 })
749 }
750
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000751 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000752 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000753 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000754 }
Alan Stokes10c47672022-12-13 17:17:08 +0000755 let port = port as u32;
756 if port < 1024 {
757 return Err(Status::new_service_specific_error_str(
758 -1,
759 Some(format!("Can't connect to privileged port {port}")),
760 ));
761 }
762 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
763 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
764 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000765 Ok(vsock_stream_to_pfd(stream))
766 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000767}
768
769impl Drop for VirtualMachine {
770 fn drop(&mut self) {
771 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900772 if let Err(e) = self.instance.kill() {
773 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
774 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000775 }
776}
777
778/// A set of Binders to be called back in response to various events on the VM, such as when it
779/// dies.
780#[derive(Debug, Default)]
781pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
782
783impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900784 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100785 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900786 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900787 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100788 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100789 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900790 }
791 }
792 }
793
Inseob Kim14cb8692021-08-31 21:50:39 +0900794 /// Call all registered callbacks to notify that the payload is ready to serve.
795 pub fn notify_payload_ready(&self, cid: Cid) {
796 let callbacks = &*self.0.lock().unwrap();
797 for callback in callbacks {
798 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100799 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900800 }
801 }
802 }
803
Inseob Kim2444af92021-08-31 01:22:50 +0900804 /// Call all registered callbacks to notify that the payload has finished.
805 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
806 let callbacks = &*self.0.lock().unwrap();
807 for callback in callbacks {
808 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100809 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900810 }
811 }
812 }
813
Jooyung Handd0a1732021-11-23 15:26:20 +0900814 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100815 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900816 let callbacks = &*self.0.lock().unwrap();
817 for callback in callbacks {
818 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100819 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900820 }
821 }
822 }
823
Andrew Walbrandae07162021-03-12 17:05:20 +0000824 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000825 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000826 let callbacks = &*self.0.lock().unwrap();
827 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000828 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100829 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000830 }
831 }
832 }
833
834 /// Add a new callback to the set.
835 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
836 self.0.lock().unwrap().push(callback);
837 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000838}
839
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000840/// The mutable state of the VirtualizationService. There should only be one instance of this
841/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800842#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000843struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000844 /// The VMs which have been started. When VMs are started a weak reference is added to this list
845 /// while a strong reference is returned to the caller over Binder. Once all copies of the
846 /// Binder client are dropped the weak reference here will become invalid, and will be removed
847 /// from the list opportunistically the next time `add_vm` is called.
848 vms: Vec<Weak<VmInstance>>,
849}
850
851impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000852 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000853 fn vms(&self) -> Vec<Arc<VmInstance>> {
854 // Attempt to upgrade the weak pointers to strong pointers.
855 self.vms.iter().filter_map(Weak::upgrade).collect()
856 }
857
858 /// Add a new VM to the list.
859 fn add_vm(&mut self, vm: Weak<VmInstance>) {
860 // Garbage collect any entries from the stored list which no longer exist.
861 self.vms.retain(|vm| vm.strong_count() > 0);
862
863 // Actually add the new VM.
864 self.vms.push(vm);
865 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000866
Jiyong Park8611a6c2021-07-09 18:17:44 +0900867 /// Get a VM that corresponds to the given cid
868 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
869 self.vms().into_iter().find(|vm| vm.cid == cid)
870 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900871}
872
Andrew Walbran6b650662021-09-07 13:13:23 +0000873/// Gets the `VirtualMachineState` of the given `VmInstance`.
874fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000875 match &*instance.vm_state.lock().unwrap() {
876 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
877 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000878 PayloadState::Starting => VirtualMachineState::STARTING,
879 PayloadState::Started => VirtualMachineState::STARTED,
880 PayloadState::Ready => VirtualMachineState::READY,
881 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900882 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000883 },
884 VmState::Dead => VirtualMachineState::DEAD,
885 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000886 }
887}
888
Andrew Walbrand3a84182021-09-07 14:48:52 +0000889/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
890fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
891 file.as_ref().map(clone_file).transpose()
892}
893
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000894/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
895fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
896 // SAFETY: ownership is transferred from stream to f
897 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
898 ParcelFileDescriptor::new(f)
899}
900
Jiyong Parkdcf17412022-02-08 15:07:23 +0900901/// Parses the platform version requirement string.
902fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
903 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000904 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +0900905 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100906 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +0900907 )
908 })
909}
910
Jiyong Parked180932023-02-24 19:55:41 +0900911/// Create the empty ramdump file
912fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
913 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
914 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
915 // owner) for readout.
916 let ramdump_path = temporary_directory.join("ramdump");
917 let ramdump = File::create(ramdump_path).map_err(|e| {
918 error!("Failed to prepare ramdump file: {:?}", e);
919 Status::new_service_specific_error_str(
920 -1,
921 Some(format!("Failed to prepare ramdump file: {:?}", e)),
922 )
923 })?;
924 Ok(ramdump)
925}
926
Nikita Ioffe5776f082023-02-10 21:38:26 +0000927fn is_protected(config: &VirtualMachineConfig) -> bool {
928 match config {
929 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
930 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
931 }
932}
933
934fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
935 if is_protected(config) {
936 return Err(Status::new_exception_str(
937 ExceptionCode::SECURITY,
938 Some("can't use gdb with protected VMs"),
939 ));
940 }
941
942 match config {
943 VirtualMachineConfig::RawConfig(_) => Ok(()),
944 VirtualMachineConfig::AppConfig(config) => {
945 if config.debugLevel != DebugLevel::FULL {
946 Err(Status::new_exception_str(
947 ExceptionCode::SECURITY,
948 Some("can't use gdb with non-debuggable VMs"),
949 ))
950 } else {
951 Ok(())
952 }
953 }
954 }
955}
956
957fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
958 match config {
959 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
960 VirtualMachineConfig::AppConfig(config) => NonZeroU16::new(config.gdbPort as u16),
961 }
962}
963
Inseob Kim0168b462022-12-27 14:54:35 +0900964fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +0900965 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +0900966 fd: Option<&ParcelFileDescriptor>,
967 tag: String,
968) -> Result<Option<File>, Status> {
969 if let Some(fd) = fd {
970 return Ok(Some(clone_file(fd)?));
971 }
972
Jaewan Kim61f86142023-03-28 15:12:52 +0900973 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +0900974 return Ok(None);
975 };
Inseob Kim0168b462022-12-27 14:54:35 +0900976
977 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
978 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
979 })?;
980
981 // SAFETY: We are the sole owners of these fds as they were just created.
982 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
983 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
984
985 std::thread::spawn(move || loop {
986 let mut buf = vec![];
987 match reader.read_until(b'\n', &mut buf) {
988 Ok(0) => {
989 // EOF
990 return;
991 }
992 Ok(size) => {
993 if buf[size - 1] == b'\n' {
994 buf.pop();
995 }
996 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
997 }
998 Err(e) => {
999 error!("Could not read console pipe: {:?}", e);
1000 return;
1001 }
1002 };
1003 });
1004
1005 Ok(Some(write_fd))
1006}
1007
Jooyung Han35edb8f2021-07-01 16:17:16 +09001008/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1009/// it doesn't require that T implements Clone.
1010enum BorrowedOrOwned<'a, T> {
1011 Borrowed(&'a T),
1012 Owned(T),
1013}
1014
1015impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1016 fn as_ref(&self) -> &T {
1017 match self {
1018 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001019 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001020 }
1021 }
1022}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001023
1024/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1025#[derive(Debug, Default)]
1026struct VirtualMachineService {
1027 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001028 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001029}
1030
1031impl Interface for VirtualMachineService {}
1032
1033impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001034 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1035 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001036 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001037 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001038 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1039 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1040 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001041 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001042
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001043 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1044 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001045 Ok(())
1046 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001047 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001048 Err(Status::new_service_specific_error_str(
1049 -1,
1050 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001051 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001052 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001053 }
Inseob Kim2444af92021-08-31 01:22:50 +09001054
Inseob Kimc7d28c72021-10-25 14:28:10 +00001055 fn notifyPayloadReady(&self) -> binder::Result<()> {
1056 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001057 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001058 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001059 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1060 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1061 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001062 vm.callbacks.notify_payload_ready(cid);
1063 Ok(())
1064 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001065 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001066 Err(Status::new_service_specific_error_str(
1067 -1,
1068 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001069 ))
1070 }
1071 }
1072
Inseob Kimc7d28c72021-10-25 14:28:10 +00001073 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1074 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001075 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001076 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001077 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1078 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1079 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001080 vm.callbacks.notify_payload_finished(cid, exit_code);
1081 Ok(())
1082 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001083 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001084 Err(Status::new_service_specific_error_str(
1085 -1,
1086 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001087 ))
1088 }
1089 }
1090
Alan Stokes2bead0d2022-09-05 16:58:34 +01001091 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001092 let cid = self.cid;
1093 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001094 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001095 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1096 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1097 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001098 vm.callbacks.notify_error(cid, error_code, message);
1099 Ok(())
1100 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001101 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001102 Err(Status::new_service_specific_error_str(
1103 -1,
1104 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001105 ))
1106 }
1107 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001108}
1109
1110impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001111 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001112 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001113 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001114 BinderFeatures::default(),
1115 )
1116 }
1117}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001118
1119#[cfg(test)]
1120mod tests {
1121 use super::*;
1122
1123 #[test]
1124 fn test_is_allowed_label_for_partition() -> Result<()> {
1125 let expected_results = vec![
1126 ("u:object_r:system_file:s0", true),
1127 ("u:object_r:apk_data_file:s0", true),
1128 ("u:object_r:app_data_file:s0", false),
1129 ("u:object_r:app_data_file:s0:c512,c768", false),
1130 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1131 ("invalid", false),
1132 ("user:role:apk_data_file:severity:categories", true),
1133 ("user:role:apk_data_file:severity:categories:extraneous", false),
1134 ];
1135
1136 for (label, expected_valid) in expected_results {
1137 let context = SeContext::new(label)?;
1138 let result = check_label_is_allowed(&context);
1139 if expected_valid {
1140 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1141 } else if result.is_ok() {
1142 bail!("Expected label {} to be disallowed", label);
1143 }
1144 }
1145 Ok(())
1146 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001147
1148 #[test]
1149 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1150 let apk = tempfile::tempfile().unwrap();
1151 let idsig = tempfile::tempfile().unwrap();
1152
1153 let ret = create_or_update_idsig_file(
1154 &ParcelFileDescriptor::new(apk),
1155 &ParcelFileDescriptor::new(idsig),
1156 );
1157 assert!(ret.is_err(), "should fail");
1158 Ok(())
1159 }
1160
1161 #[test]
1162 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1163 let tmp_dir = tempfile::TempDir::new().unwrap();
1164 let apk = File::open(tmp_dir.path()).unwrap();
1165 let idsig = tempfile::tempfile().unwrap();
1166
1167 let ret = create_or_update_idsig_file(
1168 &ParcelFileDescriptor::new(apk),
1169 &ParcelFileDescriptor::new(idsig),
1170 );
1171 assert!(ret.is_err(), "should fail");
1172 Ok(())
1173 }
1174
1175 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1176 /// on ext4 filesystem is passed.
1177 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1178 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1179 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1180 #[test]
1181 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1182 // APEXes are backed by the ext4.
1183 let apk = File::open("/apex/com.android.virt/").unwrap();
1184 let idsig = tempfile::tempfile().unwrap();
1185
1186 let ret = create_or_update_idsig_file(
1187 &ParcelFileDescriptor::new(apk),
1188 &ParcelFileDescriptor::new(idsig),
1189 );
1190 assert!(ret.is_err(), "should fail");
1191 Ok(())
1192 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001193}