blob: 678c91f7131e2d6412602c1c724d77cea449ebd8 [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};
Shikha Panwar22e70452022-10-10 18:32:55 +000022use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090023use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090024use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000025use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000026 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000027 ErrorCode::ErrorCode,
28};
29use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbran6b650662021-09-07 13:13:23 +000030 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010031 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000032 IVirtualMachineCallback::IVirtualMachineCallback,
33 IVirtualizationService::IVirtualizationService,
Keir Frasercdd4b112022-11-24 14:02:25 +000034 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090035 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000036 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090037 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090038 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000039 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010040 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090041 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000042 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090043};
David Brazdilafc9a9e2023-01-12 16:08:10 +000044use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090045use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000046 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090047};
David Brazdilafc9a9e2023-01-12 16:08:10 +000048use anyhow::{bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090049use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010050use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000051 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
52 Status, StatusCode, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000053};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000054use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000055use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000056use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090057use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090058use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000059use rpcbinder::RpcServer;
Jiyong Parkdcf17412022-02-08 15:07:23 +090060use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000061use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000062use std::ffi::CStr;
David Brazdilafc9a9e2023-01-12 16:08:10 +000063use std::fs::{read_dir, remove_file, File, OpenOptions};
64use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000065use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000066use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000067use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000068use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000069use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000070use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000071use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090072use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000073
David Brazdil41d1a872022-10-05 14:44:19 +010074/// The unique ID of a VM used (together with a port number) for vsock communication.
75pub type Cid = u32;
76
David Brazdil4b4c5102022-12-19 22:56:20 +000077pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
78
Jooyung Han95884632021-07-06 22:27:54 +090079/// The size of zero.img.
80/// Gaps in composite disk images are filled with a shared zero.img.
81const ZERO_FILLER_SIZE: u64 = 4096;
82
Jiyong Park9dd389e2021-08-23 20:42:59 +090083/// Magic string for the instance image
84const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
85
86/// Version of the instance image format
87const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
88
Alan Stokes0d1ef782022-09-27 13:46:35 +010089const MICRODROID_OS_NAME: &str = "microdroid";
90
Shikha Panwar9fd198f2022-11-18 17:43:43 +000091const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
92
Alan Stokesff0005f2023-01-30 09:53:00 +000093/// crosvm requires all partitions to be a multiple of 4KiB.
94const PARTITION_GRANULARITY_BYTES: u64 = 4096;
95
David Brazdil49f96f52022-12-16 21:29:13 +000096lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +000097 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
98 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
99 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000100}
101
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000102fn create_or_update_idsig_file(
103 input_fd: &ParcelFileDescriptor,
104 idsig_fd: &ParcelFileDescriptor,
105) -> Result<()> {
106 let mut input = clone_file(input_fd)?;
107 let metadata = input.metadata().context("failed to get input metadata")?;
108 if !metadata.is_file() {
109 bail!("input is not a regular file");
110 }
111 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256)
112 .context("failed to create idsig")?;
113
114 let mut output = clone_file(idsig_fd)?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000115 output.set_len(0).context("failed to set_len on the idsig output")?;
116 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000117 Ok(())
118}
119
David Brazdil4b4c5102022-12-19 22:56:20 +0000120pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
121 for dir_entry in read_dir(path)? {
122 remove_file(dir_entry?.path())?;
123 }
124 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100125}
126
David Brazdil528e0472022-10-10 15:06:02 +0100127/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000128#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000129pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900130 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000131}
132
Shikha Panward8e35422021-10-11 13:51:27 +0000133impl Interface for VirtualizationService {
134 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
135 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
136 let state = &mut *self.state.lock().unwrap();
137 let vms = state.vms();
138 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
139 for vm in vms {
140 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
141 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
142 .or(Err(StatusCode::UNKNOWN_ERROR))?;
143 writeln!(file, "\tPayload state {:?}", vm.payload_state())
144 .or(Err(StatusCode::UNKNOWN_ERROR))?;
145 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
146 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
147 .or(Err(StatusCode::UNKNOWN_ERROR))?;
148 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
149 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000150 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
151 .or(Err(StatusCode::UNKNOWN_ERROR))?;
152 }
153 Ok(())
154 }
155}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000156
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000157impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000158 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
159 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000160 ///
161 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000162 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000163 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000164 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900165 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000166 log_fd: Option<&ParcelFileDescriptor>,
167 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000168 let mut is_protected = false;
169 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000170 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000171 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000172 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000173
Andrew Walbrandff3b942021-06-09 15:20:36 +0000174 /// Initialise an empty partition image of the given size to be used as a writable partition.
175 fn initializeWritablePartition(
176 &self,
177 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000178 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900179 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000180 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900181 check_manage_access()?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000182 let size_bytes = size_bytes.try_into().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000183 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000184 ExceptionCode::ILLEGAL_ARGUMENT,
Alan Stokesff0005f2023-01-30 09:53:00 +0000185 Some(format!("Invalid size {}: {:?}", size_bytes, e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000186 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000187 })?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000188 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000189 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900190 // initialize the file. Any data in the file will be erased.
191 image.set_len(0).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000192 Status::new_service_specific_error_str(
193 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100194 Some(format!("Failed to reset a file: {:?}", e)),
Jooyung Han1edd5b92021-10-28 10:58:05 +0900195 )
196 })?;
Alan Stokesff0005f2023-01-30 09:53:00 +0000197 let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000198 Status::new_service_specific_error_str(
199 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100200 Some(format!("Failed to create QCOW2 image: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000201 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000202 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000203
Jiyong Park9dd389e2021-08-23 20:42:59 +0900204 match partition_type {
205 PartitionType::RAW => Ok(()),
206 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000207 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900208 _ => Err(Error::new(
209 ErrorKind::Unsupported,
210 format!("Unsupported partition type {:?}", partition_type),
211 )),
212 }
213 .map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000214 Status::new_service_specific_error_str(
215 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100216 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900217 )
218 })?;
219
Andrew Walbrandff3b942021-06-09 15:20:36 +0000220 Ok(())
221 }
222
Jiyong Park0a248432021-08-20 23:32:39 +0900223 /// Creates or update the idsig file by digesting the input APK file.
224 fn createOrUpdateIdsigFile(
225 &self,
226 input_fd: &ParcelFileDescriptor,
227 idsig_fd: &ParcelFileDescriptor,
228 ) -> binder::Result<()> {
229 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
230 // idsig_fd is different from APK digest in input_fd
231
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900232 check_manage_access()?;
233
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000234 create_or_update_idsig_file(input_fd, idsig_fd)
235 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900236 Ok(())
237 }
238
Andrew Walbran320b5602021-03-04 16:11:12 +0000239 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
240 /// and as such is only permitted from the shell user.
241 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000242 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000243 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000244 }
245}
246
Jiyong Park8611a6c2021-07-09 18:17:44 +0900247impl VirtualizationService {
248 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000249 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900250 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000251
David Brazdil209074a2023-01-12 16:44:51 +0000252 fn create_vm_context(
253 &self,
254 requester_debug_pid: pid_t,
255 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000256 const NUM_ATTEMPTS: usize = 5;
257
258 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000259 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000260 let cid = vm_context.getCid()? as Cid;
261 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000262 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
263
264 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000265 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000266 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000267 Ok(vm_server) => {
268 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000269 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000270 }
271 Err(err) => {
272 warn!("Could not start RpcServer on port {}: {}", port, err);
273 }
274 }
275 }
David Brazdil209074a2023-01-12 16:44:51 +0000276 Err(Status::new_service_specific_error_str(
277 -1,
278 Some("Too many attempts to create VM context failed."),
279 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000280 }
281
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000282 fn create_vm_internal(
283 &self,
284 config: &VirtualMachineConfig,
285 console_fd: Option<&ParcelFileDescriptor>,
286 log_fd: Option<&ParcelFileDescriptor>,
287 is_protected: &mut bool,
288 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000289 let requester_uid = get_calling_uid();
290 let requester_debug_pid = get_calling_pid();
291
292 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
293 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900294
Alan Stokes7bc146c2022-10-20 17:10:32 +0100295 let is_custom = match config {
296 VirtualMachineConfig::RawConfig(_) => true,
297 VirtualMachineConfig::AppConfig(config) => {
298 // Some features are reserved for platform apps only, even when using
299 // VirtualMachineAppConfig:
300 // - controlling CPUs;
301 // - specifying a config file in the APK.
302 !config.taskProfiles.is_empty() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900303 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100304 };
305 if is_custom {
306 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900307 }
308
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000309 let state = &mut *self.state.lock().unwrap();
Inseob Kim0168b462022-12-27 14:54:35 +0900310 let console_fd =
311 clone_or_prepare_logger_fd(config, console_fd, format!("Console({})", cid))?;
312 let log_fd = clone_or_prepare_logger_fd(config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000313
314 // Counter to generate unique IDs for temporary image files.
315 let mut next_temporary_image_id = 0;
316 // Files which are referred to from composite images. These must be mapped to the crosvm
317 // child process, and not closed before it is started.
318 let mut indirect_files = vec![];
319
Alan Stokes7bc146c2022-10-20 17:10:32 +0100320 let (is_app_config, config) = match config {
321 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
322 VirtualMachineConfig::AppConfig(config) => {
323 let config = load_app_config(config, &temporary_directory).map_err(|e| {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000324 *is_protected = config.protectedVm;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100325 let message = format!("Failed to load app config: {:?}", e);
326 error!("{}", message);
327 Status::new_service_specific_error_str(-1, Some(message))
Alan Stokes7bc146c2022-10-20 17:10:32 +0100328 })?;
329 (true, BorrowedOrOwned::Owned(config))
330 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000331 };
332 let config = config.as_ref();
333 *is_protected = config.protectedVm;
334
335 // Check if partition images are labeled incorrectly. This is to prevent random images
336 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100337 // being loaded in a pVM. This applies to everything in the raw config, and everything but
338 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000339 config
340 .disks
341 .iter()
342 .flat_map(|disk| disk.partitions.iter())
343 .filter(|partition| {
344 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100345 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000346 } else {
347 true // all partitions are checked
348 }
349 })
350 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100351 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000352
Alan Stokes185fe112023-01-10 16:20:55 +0000353 let kernel = maybe_clone_file(&config.kernel)?;
354 let initrd = maybe_clone_file(&config.initrd)?;
355
356 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
357 if config.protectedVm {
358 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
359 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
360 })?;
361 }
362
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000363 let zero_filler_path = temporary_directory.join("zero.img");
364 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100365 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000366 Status::new_service_specific_error_str(
367 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100368 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000369 )
370 })?;
371
372 // Assemble disk images if needed.
373 let disks = config
374 .disks
375 .iter()
376 .map(|disk| {
377 assemble_disk_image(
378 disk,
379 &zero_filler_path,
380 &temporary_directory,
381 &mut next_temporary_image_id,
382 &mut indirect_files,
383 )
384 })
385 .collect::<Result<Vec<DiskFile>, _>>()?;
386
Jiyong Parke558ab12022-07-07 20:18:55 +0900387 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
388 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900389 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900390 // will be sent back to the client (i.e. the VM owner) for readout.
391 let ramdump_path = temporary_directory.join("ramdump");
392 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100393 error!("Failed to prepare ramdump file: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000394 Status::new_service_specific_error_str(
395 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100396 Some(format!("Failed to prepare ramdump file: {:?}", e)),
Jiyong Parke558ab12022-07-07 20:18:55 +0900397 )
398 })?;
399
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000400 // Actually start the VM.
401 let crosvm_config = CrosvmConfig {
402 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000403 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000404 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000405 kernel,
406 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000407 disks,
408 params: config.params.to_owned(),
409 protected: *is_protected,
410 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
411 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900412 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000413 console_fd,
414 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900415 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000416 indirect_files,
417 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900418 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000419 };
420 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100421 VmInstance::new(
422 crosvm_config,
423 temporary_directory,
424 requester_uid,
425 requester_debug_pid,
426 vm_context,
427 )
428 .map_err(|e| {
429 error!("Failed to create VM with config {:?}: {:?}", config, e);
430 Status::new_service_specific_error_str(
431 -1,
432 Some(format!("Failed to create VM: {:?}", e)),
433 )
434 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000435 );
436 state.add_vm(Arc::downgrade(&instance));
437 Ok(VirtualMachine::create(instance))
438 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900439}
440
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000441fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900442 let file = OpenOptions::new()
443 .create_new(true)
444 .read(true)
445 .write(true)
446 .open(zero_filler_path)
447 .with_context(|| "Failed to create zero.img")?;
448 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000449 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900450}
451
Jiyong Park9dd389e2021-08-23 20:42:59 +0900452fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
453 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
454 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
455 part.flush()
456}
457
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000458fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
459 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
460 part.flush()
461}
462
Jiyong Parke558ab12022-07-07 20:18:55 +0900463fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
Chris Wailes9b866f02022-11-16 15:17:16 -0800464 File::create(ramdump_path).context(format!("Failed to create ramdump file {:?}", &ramdump_path))
Jiyong Parke558ab12022-07-07 20:18:55 +0900465}
466
Alan Stokesff0005f2023-01-30 09:53:00 +0000467fn round_up(input: u64, granularity: u64) -> u64 {
468 if granularity == 0 {
469 return input;
470 }
471 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
472 let result = input.checked_add(granularity - 1).unwrap_or(input);
473 (result / granularity) * granularity
474}
475
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000476/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
477///
478/// This may involve assembling a composite disk from a set of partition images.
479fn assemble_disk_image(
480 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900481 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000482 temporary_directory: &Path,
483 next_temporary_image_id: &mut u64,
484 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000485) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000486 let image = if !disk.partitions.is_empty() {
487 if disk.image.is_some() {
488 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000489 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000490 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000491 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000492 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000493 }
494
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000495 let composite_image_filenames =
496 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
497 let (image, partition_files) = make_composite_image(
498 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900499 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000500 &composite_image_filenames.composite,
501 &composite_image_filenames.header,
502 &composite_image_filenames.footer,
503 )
504 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100505 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000506 Status::new_service_specific_error_str(
507 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100508 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000509 )
510 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000511
512 // Pass the file descriptors for the various partition files to crosvm when it
513 // is run.
514 indirect_files.extend(partition_files);
515
516 image
517 } else if let Some(image) = &disk.image {
518 clone_file(image)?
519 } else {
520 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000521 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000522 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000523 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000524 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000525 };
526
527 Ok(DiskFile { image, writable: disk.writable })
528}
529
Jooyung Han21e9b922021-06-26 04:14:16 +0900530fn load_app_config(
531 config: &VirtualMachineAppConfig,
532 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900533) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000534 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
535 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900536 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900537
Shikha Panwar22e70452022-10-10 18:32:55 +0000538 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
539 Some(clone_file(file)?)
540 } else {
541 None
542 };
543
Alan Stokes0d1ef782022-09-27 13:46:35 +0100544 let vm_payload_config = match &config.payload {
545 Payload::ConfigPath(config_path) => {
546 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
547 .with_context(|| format!("Couldn't read config from {}", config_path))?
548 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000549 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100550 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900551
Alan Stokes0d1ef782022-09-27 13:46:35 +0100552 // For now, the only supported OS is Microdroid
553 let os_name = vm_payload_config.os.name.as_str();
554 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000555 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900556 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000557
558 // It is safe to construct a filename based on the os_name because we've already checked that it
559 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900560 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
561 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000562 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900563
Andrew Walbrancc045902021-07-27 16:06:17 +0000564 if config.memoryMib > 0 {
565 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000566 }
567
Seungjae Yoo62085c02022-08-12 04:44:52 +0000568 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000569 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900570 vm_config.numCpus = config.numCpus;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900571 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900572
Shikha Panwar22e70452022-10-10 18:32:55 +0000573 // Microdroid takes additional init ramdisk & (optionally) storage image
574 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
575
576 // Include Microdroid payload disk (contains apks, idsigs) in vm config
577 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100578 config,
579 temporary_directory,
580 apk_file,
581 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100582 &vm_payload_config,
583 &mut vm_config,
584 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900585
Andrew Walbrancc0db522021-07-12 17:03:42 +0000586 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900587}
588
Alan Stokes0d1ef782022-09-27 13:46:35 +0100589fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
590 let mut apk_zip = ZipArchive::new(apk_file)?;
591 let config_file = apk_zip.by_name(config_path)?;
592 Ok(serde_json::from_reader(config_file)?)
593}
594
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000595fn create_vm_payload_config(
596 payload_config: &VirtualMachinePayloadConfig,
597) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100598 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
599 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
600 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000601
602 let payload_binary_name = &payload_config.payloadBinaryName;
603 if payload_binary_name.contains('/') {
604 bail!("Payload binary name must not specify a path: {payload_binary_name}");
605 }
606
607 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
608 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100609 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
610 task: Some(task),
611 apexes: vec![],
612 extra_apks: vec![],
613 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900614 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100615 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000616 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100617}
618
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000619/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000620fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000621 temporary_directory: &Path,
622 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000623) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000624 let id = *next_temporary_image_id;
625 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000626 CompositeImageFilenames {
627 composite: temporary_directory.join(format!("composite-{}.img", id)),
628 header: temporary_directory.join(format!("composite-{}-header.img", id)),
629 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
630 }
631}
632
633/// Filenames for a composite disk image, including header and footer partitions.
634#[derive(Clone, Debug, Eq, PartialEq)]
635struct CompositeImageFilenames {
636 /// The composite disk image itself.
637 composite: PathBuf,
638 /// The header partition image.
639 header: PathBuf,
640 /// The footer partition image.
641 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000642}
643
Jiyong Park753553b2021-07-12 21:21:09 +0900644/// Checks whether the caller has a specific permission
645fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100646 let calling_pid = get_calling_pid();
647 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900648 // Root can do anything
649 if calling_uid == 0 {
650 return Ok(());
651 }
652 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
653 binder::get_interface("permission")?;
654 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000655 Ok(())
656 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000657 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900658 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000659 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900660 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000661 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000662}
663
Jiyong Park753553b2021-07-12 21:21:09 +0900664/// Check whether the caller of the current Binder method is allowed to manage VMs
665fn check_manage_access() -> binder::Result<()> {
666 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
667}
668
Inseob Kim1119d702022-05-02 18:01:58 +0900669/// Check whether the caller of the current Binder method is allowed to create custom VMs
670fn check_use_custom_virtual_machine() -> binder::Result<()> {
671 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
672}
673
Alan Stokes185fe112023-01-10 16:20:55 +0000674/// Return whether a partition is exempt from selinux label checks, because we know that it does
675/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100676fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000677 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100678 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000679 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100680 || label == "microdroid-apk-idsig"
681 || label == "payload-metadata"
682 || label.starts_with("extra-idsig-")
683}
684
Alan Stokes185fe112023-01-10 16:20:55 +0000685/// Check that a file SELinux label is acceptable.
686///
687/// We only want to allow code in a VM to be sourced from places that apps, and the
688/// system, do not have write access to.
689///
690/// Note that sepolicy must also grant read access for these types to both virtualization
691/// service and crosvm.
692///
693/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
694/// user devices (W^X).
695fn check_label_is_allowed(context: &SeContext) -> Result<()> {
696 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100697 | "system_file" // immutable dm-verity protected partition
698 | "apk_data_file" // APKs of an installed app
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000699 | "staging_data_file" // updated/staged APEX images
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100700 | "shell_data_file" // test files created via adb shell
701 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000702 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900703 }
704}
705
Alan Stokes185fe112023-01-10 16:20:55 +0000706fn check_label_for_partition(partition: &Partition) -> Result<()> {
707 let file = partition.image.as_ref().unwrap().as_ref();
708 check_label_is_allowed(&getfilecon(file)?)
709 .with_context(|| format!("Partition {} invalid", &partition.label))
710}
711
712fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
713 if let Some(f) = kernel {
714 check_label_for_file(f, "kernel")?;
715 }
716 if let Some(f) = initrd {
717 check_label_for_file(f, "initrd")?;
718 }
719 Ok(())
720}
721fn check_label_for_file(file: &File, name: &str) -> Result<()> {
722 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
723}
724
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000725/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
726#[derive(Debug)]
727struct VirtualMachine {
728 instance: Arc<VmInstance>,
729}
730
731impl VirtualMachine {
732 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000733 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000734 }
735}
736
737impl Interface for VirtualMachine {}
738
739impl IVirtualMachine for VirtualMachine {
740 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900741 // Don't check permission. The owner of the VM might have passed this binder object to
742 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000743 Ok(self.instance.cid as i32)
744 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000745
Andrew Walbran6b650662021-09-07 13:13:23 +0000746 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900747 // Don't check permission. The owner of the VM might have passed this binder object to
748 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000749 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000750 }
751
752 fn registerCallback(
753 &self,
754 callback: &Strong<dyn IVirtualMachineCallback>,
755 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900756 // Don't check permission. The owner of the VM might have passed this binder object to
757 // others.
758 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000759 // TODO: Should this give an error if the VM is already dead?
760 self.instance.callbacks.add(callback.clone());
761 Ok(())
762 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000763
Andrew Walbranf8d94112021-09-07 11:45:36 +0000764 fn start(&self) -> binder::Result<()> {
765 self.instance.start().map_err(|e| {
766 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000767 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000768 })
769 }
770
Inseob Kima446f802022-07-11 19:46:37 +0900771 fn stop(&self) -> binder::Result<()> {
772 self.instance.kill().map_err(|e| {
773 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000774 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900775 })
776 }
777
Keir Frasercdd4b112022-11-24 14:02:25 +0000778 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
779 self.instance.trim_memory(level).map_err(|e| {
780 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
781 Status::new_service_specific_error_str(-1, Some(e.to_string()))
782 })
783 }
784
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000785 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000786 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000787 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000788 }
Alan Stokes10c47672022-12-13 17:17:08 +0000789 let port = port as u32;
790 if port < 1024 {
791 return Err(Status::new_service_specific_error_str(
792 -1,
793 Some(format!("Can't connect to privileged port {port}")),
794 ));
795 }
796 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
797 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
798 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000799 Ok(vsock_stream_to_pfd(stream))
800 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000801}
802
803impl Drop for VirtualMachine {
804 fn drop(&mut self) {
805 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900806 if let Err(e) = self.instance.kill() {
807 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
808 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000809 }
810}
811
812/// A set of Binders to be called back in response to various events on the VM, such as when it
813/// dies.
814#[derive(Debug, Default)]
815pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
816
817impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900818 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100819 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900820 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900821 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100822 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100823 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900824 }
825 }
826 }
827
Inseob Kim14cb8692021-08-31 21:50:39 +0900828 /// Call all registered callbacks to notify that the payload is ready to serve.
829 pub fn notify_payload_ready(&self, cid: Cid) {
830 let callbacks = &*self.0.lock().unwrap();
831 for callback in callbacks {
832 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100833 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900834 }
835 }
836 }
837
Inseob Kim2444af92021-08-31 01:22:50 +0900838 /// Call all registered callbacks to notify that the payload has finished.
839 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
840 let callbacks = &*self.0.lock().unwrap();
841 for callback in callbacks {
842 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100843 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900844 }
845 }
846 }
847
Jooyung Handd0a1732021-11-23 15:26:20 +0900848 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100849 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900850 let callbacks = &*self.0.lock().unwrap();
851 for callback in callbacks {
852 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100853 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900854 }
855 }
856 }
857
Andrew Walbrandae07162021-03-12 17:05:20 +0000858 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000859 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000860 let callbacks = &*self.0.lock().unwrap();
861 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000862 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100863 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000864 }
865 }
866 }
867
868 /// Add a new callback to the set.
869 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
870 self.0.lock().unwrap().push(callback);
871 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000872}
873
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000874/// The mutable state of the VirtualizationService. There should only be one instance of this
875/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800876#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000877struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000878 /// The VMs which have been started. When VMs are started a weak reference is added to this list
879 /// while a strong reference is returned to the caller over Binder. Once all copies of the
880 /// Binder client are dropped the weak reference here will become invalid, and will be removed
881 /// from the list opportunistically the next time `add_vm` is called.
882 vms: Vec<Weak<VmInstance>>,
883}
884
885impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000886 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000887 fn vms(&self) -> Vec<Arc<VmInstance>> {
888 // Attempt to upgrade the weak pointers to strong pointers.
889 self.vms.iter().filter_map(Weak::upgrade).collect()
890 }
891
892 /// Add a new VM to the list.
893 fn add_vm(&mut self, vm: Weak<VmInstance>) {
894 // Garbage collect any entries from the stored list which no longer exist.
895 self.vms.retain(|vm| vm.strong_count() > 0);
896
897 // Actually add the new VM.
898 self.vms.push(vm);
899 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000900
Jiyong Park8611a6c2021-07-09 18:17:44 +0900901 /// Get a VM that corresponds to the given cid
902 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
903 self.vms().into_iter().find(|vm| vm.cid == cid)
904 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900905}
906
Andrew Walbran6b650662021-09-07 13:13:23 +0000907/// Gets the `VirtualMachineState` of the given `VmInstance`.
908fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000909 match &*instance.vm_state.lock().unwrap() {
910 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
911 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000912 PayloadState::Starting => VirtualMachineState::STARTING,
913 PayloadState::Started => VirtualMachineState::STARTED,
914 PayloadState::Ready => VirtualMachineState::READY,
915 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900916 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000917 },
918 VmState::Dead => VirtualMachineState::DEAD,
919 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000920 }
921}
922
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000923/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000924pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000925 file.as_ref().try_clone().map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000926 Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000927 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100928 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
Andrew Walbran806f1542021-06-10 14:07:12 +0000929 )
930 })
931}
932
Andrew Walbrand3a84182021-09-07 14:48:52 +0000933/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
934fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
935 file.as_ref().map(clone_file).transpose()
936}
937
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000938/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
939fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
940 // SAFETY: ownership is transferred from stream to f
941 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
942 ParcelFileDescriptor::new(f)
943}
944
Jiyong Parkdcf17412022-02-08 15:07:23 +0900945/// Parses the platform version requirement string.
946fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
947 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000948 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +0900949 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100950 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +0900951 )
952 })
953}
954
Inseob Kim0168b462022-12-27 14:54:35 +0900955fn is_debuggable(config: &VirtualMachineConfig) -> bool {
956 match config {
957 VirtualMachineConfig::AppConfig(config) => config.debugLevel != DebugLevel::NONE,
958 _ => false,
959 }
960}
961
962fn clone_or_prepare_logger_fd(
963 config: &VirtualMachineConfig,
964 fd: Option<&ParcelFileDescriptor>,
965 tag: String,
966) -> Result<Option<File>, Status> {
967 if let Some(fd) = fd {
968 return Ok(Some(clone_file(fd)?));
969 }
970
971 if !is_debuggable(config) {
972 return Ok(None);
973 }
974
975 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
976 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
977 })?;
978
979 // SAFETY: We are the sole owners of these fds as they were just created.
980 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
981 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
982
983 std::thread::spawn(move || loop {
984 let mut buf = vec![];
985 match reader.read_until(b'\n', &mut buf) {
986 Ok(0) => {
987 // EOF
988 return;
989 }
990 Ok(size) => {
991 if buf[size - 1] == b'\n' {
992 buf.pop();
993 }
994 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
995 }
996 Err(e) => {
997 error!("Could not read console pipe: {:?}", e);
998 return;
999 }
1000 };
1001 });
1002
1003 Ok(Some(write_fd))
1004}
1005
Jooyung Han35edb8f2021-07-01 16:17:16 +09001006/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1007/// it doesn't require that T implements Clone.
1008enum BorrowedOrOwned<'a, T> {
1009 Borrowed(&'a T),
1010 Owned(T),
1011}
1012
1013impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1014 fn as_ref(&self) -> &T {
1015 match self {
1016 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001017 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001018 }
1019 }
1020}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001021
1022/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1023#[derive(Debug, Default)]
1024struct VirtualMachineService {
1025 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001026 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001027}
1028
1029impl Interface for VirtualMachineService {}
1030
1031impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001032 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1033 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001034 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001035 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001036 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1037 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1038 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001039 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001040
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001041 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1042 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001043 Ok(())
1044 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001045 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001046 Err(Status::new_service_specific_error_str(
1047 -1,
1048 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001049 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001050 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001051 }
Inseob Kim2444af92021-08-31 01:22:50 +09001052
Inseob Kimc7d28c72021-10-25 14:28:10 +00001053 fn notifyPayloadReady(&self) -> binder::Result<()> {
1054 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001055 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001056 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001057 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1058 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1059 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001060 vm.callbacks.notify_payload_ready(cid);
1061 Ok(())
1062 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001063 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001064 Err(Status::new_service_specific_error_str(
1065 -1,
1066 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001067 ))
1068 }
1069 }
1070
Inseob Kimc7d28c72021-10-25 14:28:10 +00001071 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1072 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001073 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001074 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001075 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1076 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1077 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001078 vm.callbacks.notify_payload_finished(cid, exit_code);
1079 Ok(())
1080 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001081 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001082 Err(Status::new_service_specific_error_str(
1083 -1,
1084 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001085 ))
1086 }
1087 }
1088
Alan Stokes2bead0d2022-09-05 16:58:34 +01001089 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001090 let cid = self.cid;
1091 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001092 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001093 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1094 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1095 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001096 vm.callbacks.notify_error(cid, error_code, message);
1097 Ok(())
1098 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001099 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001100 Err(Status::new_service_specific_error_str(
1101 -1,
1102 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001103 ))
1104 }
1105 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001106}
1107
1108impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001109 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001110 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001111 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001112 BinderFeatures::default(),
1113 )
1114 }
1115}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001116
1117#[cfg(test)]
1118mod tests {
1119 use super::*;
1120
1121 #[test]
1122 fn test_is_allowed_label_for_partition() -> Result<()> {
1123 let expected_results = vec![
1124 ("u:object_r:system_file:s0", true),
1125 ("u:object_r:apk_data_file:s0", true),
1126 ("u:object_r:app_data_file:s0", false),
1127 ("u:object_r:app_data_file:s0:c512,c768", false),
1128 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1129 ("invalid", false),
1130 ("user:role:apk_data_file:severity:categories", true),
1131 ("user:role:apk_data_file:severity:categories:extraneous", false),
1132 ];
1133
1134 for (label, expected_valid) in expected_results {
1135 let context = SeContext::new(label)?;
1136 let result = check_label_is_allowed(&context);
1137 if expected_valid {
1138 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1139 } else if result.is_ok() {
1140 bail!("Expected label {} to be disallowed", label);
1141 }
1142 }
1143 Ok(())
1144 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001145
1146 #[test]
1147 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1148 let apk = tempfile::tempfile().unwrap();
1149 let idsig = tempfile::tempfile().unwrap();
1150
1151 let ret = create_or_update_idsig_file(
1152 &ParcelFileDescriptor::new(apk),
1153 &ParcelFileDescriptor::new(idsig),
1154 );
1155 assert!(ret.is_err(), "should fail");
1156 Ok(())
1157 }
1158
1159 #[test]
1160 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1161 let tmp_dir = tempfile::TempDir::new().unwrap();
1162 let apk = File::open(tmp_dir.path()).unwrap();
1163 let idsig = tempfile::tempfile().unwrap();
1164
1165 let ret = create_or_update_idsig_file(
1166 &ParcelFileDescriptor::new(apk),
1167 &ParcelFileDescriptor::new(idsig),
1168 );
1169 assert!(ret.is_err(), "should fail");
1170 Ok(())
1171 }
1172
1173 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1174 /// on ext4 filesystem is passed.
1175 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1176 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1177 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1178 #[test]
1179 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1180 // APEXes are backed by the ext4.
1181 let apk = File::open("/apex/com.android.virt/").unwrap();
1182 let idsig = tempfile::tempfile().unwrap();
1183
1184 let ret = create_or_update_idsig_file(
1185 &ParcelFileDescriptor::new(apk),
1186 &ParcelFileDescriptor::new(idsig),
1187 );
1188 assert!(ret.is_err(), "should fail");
1189 Ok(())
1190 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001191}