blob: 06274c879cd651e8bb5415bf4e5ca127333556d8 [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 Brazdilf50c7a62023-04-19 14:22:42 +000056use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000057use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000058use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090059use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090060use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000061use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000062use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090063use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000064use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000065use std::ffi::CStr;
David Brazdilafc9a9e2023-01-12 16:08:10 +000066use std::fs::{read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000067use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000068use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000069use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000070use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000071use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000072use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000073use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000074use vsock::VsockStream;
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
David Brazdilf50c7a62023-04-19 14:22:42 +000086/// Magic string for the instance image
87const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
88
89/// Version of the instance image format
90const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
91
Alan Stokes0d1ef782022-09-27 13:46:35 +010092const MICRODROID_OS_NAME: &str = "microdroid";
93
David Brazdilf50c7a62023-04-19 14:22:42 +000094const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
95
96/// crosvm requires all partitions to be a multiple of 4KiB.
97const PARTITION_GRANULARITY_BYTES: u64 = 4096;
98
David Brazdil49f96f52022-12-16 21:29:13 +000099lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000100 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
101 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
102 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000103}
104
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000105fn create_or_update_idsig_file(
106 input_fd: &ParcelFileDescriptor,
107 idsig_fd: &ParcelFileDescriptor,
108) -> Result<()> {
109 let mut input = clone_file(input_fd)?;
110 let metadata = input.metadata().context("failed to get input metadata")?;
111 if !metadata.is_file() {
112 bail!("input is not a regular file");
113 }
Alan Stokes25f69362023-03-06 16:51:54 +0000114 let mut sig =
115 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
116 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000117
118 let mut output = clone_file(idsig_fd)?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000119 output.set_len(0).context("failed to set_len on the idsig output")?;
120 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000121 Ok(())
122}
123
Alan Stokes25f69362023-03-06 16:51:54 +0000124fn get_current_sdk() -> Result<u32> {
125 let current_sdk = system_properties::read("ro.build.version.sdk")?;
126 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
127 current_sdk.parse().context("Malformed SDK version")
128}
129
David Brazdil4b4c5102022-12-19 22:56:20 +0000130pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
131 for dir_entry in read_dir(path)? {
132 remove_file(dir_entry?.path())?;
133 }
134 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100135}
136
David Brazdil528e0472022-10-10 15:06:02 +0100137/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000138#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000139pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900140 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000141}
142
Shikha Panward8e35422021-10-11 13:51:27 +0000143impl Interface for VirtualizationService {
144 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
145 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
146 let state = &mut *self.state.lock().unwrap();
147 let vms = state.vms();
148 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
149 for vm in vms {
150 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
151 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
152 .or(Err(StatusCode::UNKNOWN_ERROR))?;
153 writeln!(file, "\tPayload state {:?}", vm.payload_state())
154 .or(Err(StatusCode::UNKNOWN_ERROR))?;
155 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
156 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
157 .or(Err(StatusCode::UNKNOWN_ERROR))?;
158 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
159 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000160 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
161 .or(Err(StatusCode::UNKNOWN_ERROR))?;
162 }
163 Ok(())
164 }
165}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000166
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000167impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000168 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
169 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000170 ///
171 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000172 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000173 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000174 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900175 console_out_fd: Option<&ParcelFileDescriptor>,
176 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000177 log_fd: Option<&ParcelFileDescriptor>,
178 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000179 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900180 let ret = self.create_vm_internal(
181 config,
182 console_out_fd,
183 console_in_fd,
184 log_fd,
185 &mut is_protected,
186 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000187 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000188 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000189 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000190
Andrew Walbrandff3b942021-06-09 15:20:36 +0000191 /// Initialise an empty partition image of the given size to be used as a writable partition.
192 fn initializeWritablePartition(
193 &self,
194 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000195 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900196 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000197 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900198 check_manage_access()?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000199 let size_bytes = size_bytes.try_into().map_err(|e| {
200 Status::new_exception_str(
201 ExceptionCode::ILLEGAL_ARGUMENT,
202 Some(format!("Invalid size {}: {:?}", size_bytes, e)),
203 )
204 })?;
205 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
206 let image = clone_file(image_fd)?;
207 // initialize the file. Any data in the file will be erased.
208 image.set_len(0).map_err(|e| {
209 Status::new_service_specific_error_str(
210 -1,
211 Some(format!("Failed to reset a file: {:?}", e)),
212 )
213 })?;
214 let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
215 Status::new_service_specific_error_str(
216 -1,
217 Some(format!("Failed to create QCOW2 image: {:?}", e)),
218 )
219 })?;
220
221 match partition_type {
222 PartitionType::RAW => Ok(()),
223 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
224 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
225 _ => Err(Error::new(
226 ErrorKind::Unsupported,
227 format!("Unsupported partition type {:?}", partition_type),
228 )),
229 }
230 .map_err(|e| {
231 Status::new_service_specific_error_str(
232 -1,
233 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
234 )
235 })?;
236
237 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000238 }
239
Jiyong Park0a248432021-08-20 23:32:39 +0900240 /// Creates or update the idsig file by digesting the input APK file.
241 fn createOrUpdateIdsigFile(
242 &self,
243 input_fd: &ParcelFileDescriptor,
244 idsig_fd: &ParcelFileDescriptor,
245 ) -> binder::Result<()> {
246 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
247 // idsig_fd is different from APK digest in input_fd
248
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900249 check_manage_access()?;
250
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000251 create_or_update_idsig_file(input_fd, idsig_fd)
252 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900253 Ok(())
254 }
255
Andrew Walbran320b5602021-03-04 16:11:12 +0000256 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
257 /// and as such is only permitted from the shell user.
258 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000259 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000260 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000261 }
262}
263
Jiyong Park8611a6c2021-07-09 18:17:44 +0900264impl VirtualizationService {
265 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000266 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900267 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000268
David Brazdil209074a2023-01-12 16:44:51 +0000269 fn create_vm_context(
270 &self,
271 requester_debug_pid: pid_t,
272 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000273 const NUM_ATTEMPTS: usize = 5;
274
275 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000276 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000277 let cid = vm_context.getCid()? as Cid;
278 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000279 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
280
281 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000282 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000283 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000284 Ok(vm_server) => {
285 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000286 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000287 }
288 Err(err) => {
289 warn!("Could not start RpcServer on port {}: {}", port, err);
290 }
291 }
292 }
David Brazdil209074a2023-01-12 16:44:51 +0000293 Err(Status::new_service_specific_error_str(
294 -1,
295 Some("Too many attempts to create VM context failed."),
296 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000297 }
298
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000299 fn create_vm_internal(
300 &self,
301 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900302 console_out_fd: Option<&ParcelFileDescriptor>,
303 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000304 log_fd: Option<&ParcelFileDescriptor>,
305 is_protected: &mut bool,
306 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000307 let requester_uid = get_calling_uid();
308 let requester_debug_pid = get_calling_pid();
309
310 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
311 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900312
Alan Stokes7bc146c2022-10-20 17:10:32 +0100313 let is_custom = match config {
314 VirtualMachineConfig::RawConfig(_) => true,
315 VirtualMachineConfig::AppConfig(config) => {
316 // Some features are reserved for platform apps only, even when using
317 // VirtualMachineAppConfig:
318 // - controlling CPUs;
Nikita Ioffe5776f082023-02-10 21:38:26 +0000319 // - specifying a config file in the APK;
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100320 // - gdbPort is set, meaning that crosvm will start a gdb server;
321 // - using anything other than the default kernel.
Nikita Ioffe5776f082023-02-10 21:38:26 +0000322 !config.taskProfiles.is_empty()
323 || matches!(config.payload, Payload::ConfigPath(_))
324 || config.gdbPort > 0
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100325 || config.customKernelImage.as_ref().is_some()
Inseob Kim1119d702022-05-02 18:01:58 +0900326 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100327 };
328 if is_custom {
329 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900330 }
331
Nikita Ioffe5776f082023-02-10 21:38:26 +0000332 let gdb_port = extract_gdb_port(config);
333
334 // Additional permission checks if caller request gdb.
335 if gdb_port.is_some() {
336 check_gdb_allowed(config)?;
337 }
338
Jaewan Kim61f86142023-03-28 15:12:52 +0900339 let debug_level = match config {
340 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
341 _ => DebugLevel::NONE,
342 };
343 let debug_config = DebugConfig::new(debug_level);
344
345 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900346 Some(prepare_ramdump_file(&temporary_directory)?)
347 } else {
348 None
349 };
350
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000351 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900352 let console_out_fd =
353 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
354 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900355 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000356
357 // Counter to generate unique IDs for temporary image files.
358 let mut next_temporary_image_id = 0;
359 // Files which are referred to from composite images. These must be mapped to the crosvm
360 // child process, and not closed before it is started.
361 let mut indirect_files = vec![];
362
Alan Stokes7bc146c2022-10-20 17:10:32 +0100363 let (is_app_config, config) = match config {
364 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
365 VirtualMachineConfig::AppConfig(config) => {
Jaewan Kim61f86142023-03-28 15:12:52 +0900366 let config =
367 load_app_config(config, &debug_config, &temporary_directory).map_err(|e| {
368 *is_protected = config.protectedVm;
369 let message = format!("Failed to load app config: {:?}", e);
370 error!("{}", message);
371 Status::new_service_specific_error_str(-1, Some(message))
372 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100373 (true, BorrowedOrOwned::Owned(config))
374 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000375 };
376 let config = config.as_ref();
377 *is_protected = config.protectedVm;
378
379 // Check if partition images are labeled incorrectly. This is to prevent random images
380 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100381 // being loaded in a pVM. This applies to everything in the raw config, and everything but
382 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000383 config
384 .disks
385 .iter()
386 .flat_map(|disk| disk.partitions.iter())
387 .filter(|partition| {
388 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100389 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000390 } else {
391 true // all partitions are checked
392 }
393 })
394 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100395 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000396
Alan Stokes185fe112023-01-10 16:20:55 +0000397 let kernel = maybe_clone_file(&config.kernel)?;
398 let initrd = maybe_clone_file(&config.initrd)?;
399
400 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
401 if config.protectedVm {
402 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
403 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
404 })?;
405 }
406
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000407 let zero_filler_path = temporary_directory.join("zero.img");
408 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100409 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000410 Status::new_service_specific_error_str(
411 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100412 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000413 )
414 })?;
415
416 // Assemble disk images if needed.
417 let disks = config
418 .disks
419 .iter()
420 .map(|disk| {
421 assemble_disk_image(
422 disk,
423 &zero_filler_path,
424 &temporary_directory,
425 &mut next_temporary_image_id,
426 &mut indirect_files,
427 )
428 })
429 .collect::<Result<Vec<DiskFile>, _>>()?;
430
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000431 let (cpus, host_cpu_topology) = match config.cpuTopology {
432 CpuTopology::MATCH_HOST => (None, true),
433 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
434 val => {
435 error!("Unexpected value of CPU topology: {:?}", val);
436 return Err(Status::new_service_specific_error_str(
437 -1,
438 Some(format!("Failed to parse CPU topology value: {:?}", val)),
439 ));
440 }
441 };
442
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000443 // Actually start the VM.
444 let crosvm_config = CrosvmConfig {
445 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000446 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000447 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000448 kernel,
449 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000450 disks,
451 params: config.params.to_owned(),
452 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900453 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000454 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000455 cpus,
456 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900457 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900458 console_out_fd,
459 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000460 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900461 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000462 indirect_files,
463 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900464 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000465 gdb_port,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000466 };
467 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100468 VmInstance::new(
469 crosvm_config,
470 temporary_directory,
471 requester_uid,
472 requester_debug_pid,
473 vm_context,
474 )
475 .map_err(|e| {
476 error!("Failed to create VM with config {:?}: {:?}", config, e);
477 Status::new_service_specific_error_str(
478 -1,
479 Some(format!("Failed to create VM: {:?}", e)),
480 )
481 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000482 );
483 state.add_vm(Arc::downgrade(&instance));
484 Ok(VirtualMachine::create(instance))
485 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900486}
487
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000488fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900489 let file = OpenOptions::new()
490 .create_new(true)
491 .read(true)
492 .write(true)
493 .open(zero_filler_path)
494 .with_context(|| "Failed to create zero.img")?;
495 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000496 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900497}
498
David Brazdilf50c7a62023-04-19 14:22:42 +0000499fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
500 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
501 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
502 part.flush()
503}
504
505fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
506 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
507 part.flush()
508}
509
510fn round_up(input: u64, granularity: u64) -> u64 {
511 if granularity == 0 {
512 return input;
513 }
514 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
515 let result = input.checked_add(granularity - 1).unwrap_or(input);
516 (result / granularity) * granularity
517}
518
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000519/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
520///
521/// This may involve assembling a composite disk from a set of partition images.
522fn assemble_disk_image(
523 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900524 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000525 temporary_directory: &Path,
526 next_temporary_image_id: &mut u64,
527 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000528) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000529 let image = if !disk.partitions.is_empty() {
530 if disk.image.is_some() {
531 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000532 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000533 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000534 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000535 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000536 }
537
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000538 let composite_image_filenames =
539 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
540 let (image, partition_files) = make_composite_image(
541 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900542 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000543 &composite_image_filenames.composite,
544 &composite_image_filenames.header,
545 &composite_image_filenames.footer,
546 )
547 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100548 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000549 Status::new_service_specific_error_str(
550 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100551 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000552 )
553 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000554
555 // Pass the file descriptors for the various partition files to crosvm when it
556 // is run.
557 indirect_files.extend(partition_files);
558
559 image
560 } else if let Some(image) = &disk.image {
561 clone_file(image)?
562 } else {
563 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000564 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000565 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000566 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000567 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000568 };
569
570 Ok(DiskFile { image, writable: disk.writable })
571}
572
Jooyung Han21e9b922021-06-26 04:14:16 +0900573fn load_app_config(
574 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900575 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900576 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900577) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000578 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
579 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900580 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900581
Shikha Panwar22e70452022-10-10 18:32:55 +0000582 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
583 Some(clone_file(file)?)
584 } else {
585 None
586 };
587
Alan Stokes0d1ef782022-09-27 13:46:35 +0100588 let vm_payload_config = match &config.payload {
589 Payload::ConfigPath(config_path) => {
590 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
591 .with_context(|| format!("Couldn't read config from {}", config_path))?
592 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000593 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100594 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900595
Alan Stokes0d1ef782022-09-27 13:46:35 +0100596 // For now, the only supported OS is Microdroid
597 let os_name = vm_payload_config.os.name.as_str();
598 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000599 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900600 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000601
602 // It is safe to construct a filename based on the os_name because we've already checked that it
603 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900604 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
605 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000606 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900607
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100608 if let Some(file) = config.customKernelImage.as_ref() {
609 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
610 }
611
Andrew Walbrancc045902021-07-27 16:06:17 +0000612 if config.memoryMib > 0 {
613 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000614 }
615
Seungjae Yoo62085c02022-08-12 04:44:52 +0000616 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000617 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000618 vm_config.cpuTopology = config.cpuTopology;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900619 vm_config.taskProfiles = config.taskProfiles.clone();
Nikita Ioffe5776f082023-02-10 21:38:26 +0000620 vm_config.gdbPort = config.gdbPort;
Jiyong Park032615f2022-01-10 13:55:34 +0900621
Shikha Panwar22e70452022-10-10 18:32:55 +0000622 // Microdroid takes additional init ramdisk & (optionally) storage image
623 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
624
625 // Include Microdroid payload disk (contains apks, idsigs) in vm config
626 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100627 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900628 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100629 temporary_directory,
630 apk_file,
631 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100632 &vm_payload_config,
633 &mut vm_config,
634 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900635
Andrew Walbrancc0db522021-07-12 17:03:42 +0000636 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900637}
638
Alan Stokes0d1ef782022-09-27 13:46:35 +0100639fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
640 let mut apk_zip = ZipArchive::new(apk_file)?;
641 let config_file = apk_zip.by_name(config_path)?;
642 Ok(serde_json::from_reader(config_file)?)
643}
644
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000645fn create_vm_payload_config(
646 payload_config: &VirtualMachinePayloadConfig,
647) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100648 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
649 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
650 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000651
652 let payload_binary_name = &payload_config.payloadBinaryName;
653 if payload_binary_name.contains('/') {
654 bail!("Payload binary name must not specify a path: {payload_binary_name}");
655 }
656
657 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
658 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100659 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
660 task: Some(task),
661 apexes: vec![],
662 extra_apks: vec![],
663 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900664 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100665 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000666 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100667}
668
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000669/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000670fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000671 temporary_directory: &Path,
672 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000673) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000674 let id = *next_temporary_image_id;
675 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000676 CompositeImageFilenames {
677 composite: temporary_directory.join(format!("composite-{}.img", id)),
678 header: temporary_directory.join(format!("composite-{}-header.img", id)),
679 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
680 }
681}
682
683/// Filenames for a composite disk image, including header and footer partitions.
684#[derive(Clone, Debug, Eq, PartialEq)]
685struct CompositeImageFilenames {
686 /// The composite disk image itself.
687 composite: PathBuf,
688 /// The header partition image.
689 header: PathBuf,
690 /// The footer partition image.
691 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000692}
693
Jiyong Park753553b2021-07-12 21:21:09 +0900694/// Checks whether the caller has a specific permission
695fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100696 let calling_pid = get_calling_pid();
697 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900698 // Root can do anything
699 if calling_uid == 0 {
700 return Ok(());
701 }
702 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
703 binder::get_interface("permission")?;
704 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000705 Ok(())
706 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000707 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900708 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000709 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900710 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000711 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000712}
713
Jiyong Park753553b2021-07-12 21:21:09 +0900714/// Check whether the caller of the current Binder method is allowed to manage VMs
715fn check_manage_access() -> binder::Result<()> {
716 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
717}
718
Inseob Kim1119d702022-05-02 18:01:58 +0900719/// Check whether the caller of the current Binder method is allowed to create custom VMs
720fn check_use_custom_virtual_machine() -> binder::Result<()> {
721 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
722}
723
Alan Stokes185fe112023-01-10 16:20:55 +0000724/// Return whether a partition is exempt from selinux label checks, because we know that it does
725/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100726fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000727 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100728 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000729 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100730 || label == "microdroid-apk-idsig"
731 || label == "payload-metadata"
732 || label.starts_with("extra-idsig-")
733}
734
Alan Stokes185fe112023-01-10 16:20:55 +0000735/// Check that a file SELinux label is acceptable.
736///
737/// We only want to allow code in a VM to be sourced from places that apps, and the
738/// system, do not have write access to.
739///
740/// Note that sepolicy must also grant read access for these types to both virtualization
741/// service and crosvm.
742///
743/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
744/// user devices (W^X).
745fn check_label_is_allowed(context: &SeContext) -> Result<()> {
746 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100747 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100748 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000749 | "staging_data_file" // updated/staged APEX images
750 | "system_file" // immutable dm-verity protected partition
751 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100752 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000753 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900754 }
755}
756
Alan Stokes185fe112023-01-10 16:20:55 +0000757fn check_label_for_partition(partition: &Partition) -> Result<()> {
758 let file = partition.image.as_ref().unwrap().as_ref();
759 check_label_is_allowed(&getfilecon(file)?)
760 .with_context(|| format!("Partition {} invalid", &partition.label))
761}
762
763fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
764 if let Some(f) = kernel {
765 check_label_for_file(f, "kernel")?;
766 }
767 if let Some(f) = initrd {
768 check_label_for_file(f, "initrd")?;
769 }
770 Ok(())
771}
772fn check_label_for_file(file: &File, name: &str) -> Result<()> {
773 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
774}
775
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000776/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
777#[derive(Debug)]
778struct VirtualMachine {
779 instance: Arc<VmInstance>,
780}
781
782impl VirtualMachine {
783 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000784 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000785 }
786}
787
788impl Interface for VirtualMachine {}
789
790impl IVirtualMachine for VirtualMachine {
791 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900792 // Don't check permission. The owner of the VM might have passed this binder object to
793 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000794 Ok(self.instance.cid as i32)
795 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000796
Andrew Walbran6b650662021-09-07 13:13:23 +0000797 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900798 // Don't check permission. The owner of the VM might have passed this binder object to
799 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000800 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000801 }
802
803 fn registerCallback(
804 &self,
805 callback: &Strong<dyn IVirtualMachineCallback>,
806 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900807 // Don't check permission. The owner of the VM might have passed this binder object to
808 // others.
809 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000810 // TODO: Should this give an error if the VM is already dead?
811 self.instance.callbacks.add(callback.clone());
812 Ok(())
813 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000814
Andrew Walbranf8d94112021-09-07 11:45:36 +0000815 fn start(&self) -> binder::Result<()> {
816 self.instance.start().map_err(|e| {
817 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000818 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000819 })
820 }
821
Inseob Kima446f802022-07-11 19:46:37 +0900822 fn stop(&self) -> binder::Result<()> {
823 self.instance.kill().map_err(|e| {
824 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000825 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900826 })
827 }
828
Keir Frasercdd4b112022-11-24 14:02:25 +0000829 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
830 self.instance.trim_memory(level).map_err(|e| {
831 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
832 Status::new_service_specific_error_str(-1, Some(e.to_string()))
833 })
834 }
835
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000836 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000837 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000838 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000839 }
Alan Stokes10c47672022-12-13 17:17:08 +0000840 let port = port as u32;
841 if port < 1024 {
842 return Err(Status::new_service_specific_error_str(
843 -1,
844 Some(format!("Can't connect to privileged port {port}")),
845 ));
846 }
847 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
848 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
849 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000850 Ok(vsock_stream_to_pfd(stream))
851 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000852}
853
854impl Drop for VirtualMachine {
855 fn drop(&mut self) {
856 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900857 if let Err(e) = self.instance.kill() {
858 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
859 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000860 }
861}
862
863/// A set of Binders to be called back in response to various events on the VM, such as when it
864/// dies.
865#[derive(Debug, Default)]
866pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
867
868impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900869 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100870 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900871 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900872 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100873 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100874 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900875 }
876 }
877 }
878
Inseob Kim14cb8692021-08-31 21:50:39 +0900879 /// Call all registered callbacks to notify that the payload is ready to serve.
880 pub fn notify_payload_ready(&self, cid: Cid) {
881 let callbacks = &*self.0.lock().unwrap();
882 for callback in callbacks {
883 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100884 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900885 }
886 }
887 }
888
Inseob Kim2444af92021-08-31 01:22:50 +0900889 /// Call all registered callbacks to notify that the payload has finished.
890 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
891 let callbacks = &*self.0.lock().unwrap();
892 for callback in callbacks {
893 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100894 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900895 }
896 }
897 }
898
Jooyung Handd0a1732021-11-23 15:26:20 +0900899 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100900 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900901 let callbacks = &*self.0.lock().unwrap();
902 for callback in callbacks {
903 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100904 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900905 }
906 }
907 }
908
Andrew Walbrandae07162021-03-12 17:05:20 +0000909 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000910 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000911 let callbacks = &*self.0.lock().unwrap();
912 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000913 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100914 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000915 }
916 }
917 }
918
919 /// Add a new callback to the set.
920 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
921 self.0.lock().unwrap().push(callback);
922 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000923}
924
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000925/// The mutable state of the VirtualizationService. There should only be one instance of this
926/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800927#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000928struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000929 /// The VMs which have been started. When VMs are started a weak reference is added to this list
930 /// while a strong reference is returned to the caller over Binder. Once all copies of the
931 /// Binder client are dropped the weak reference here will become invalid, and will be removed
932 /// from the list opportunistically the next time `add_vm` is called.
933 vms: Vec<Weak<VmInstance>>,
934}
935
936impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000937 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000938 fn vms(&self) -> Vec<Arc<VmInstance>> {
939 // Attempt to upgrade the weak pointers to strong pointers.
940 self.vms.iter().filter_map(Weak::upgrade).collect()
941 }
942
943 /// Add a new VM to the list.
944 fn add_vm(&mut self, vm: Weak<VmInstance>) {
945 // Garbage collect any entries from the stored list which no longer exist.
946 self.vms.retain(|vm| vm.strong_count() > 0);
947
948 // Actually add the new VM.
949 self.vms.push(vm);
950 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000951
Jiyong Park8611a6c2021-07-09 18:17:44 +0900952 /// Get a VM that corresponds to the given cid
953 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
954 self.vms().into_iter().find(|vm| vm.cid == cid)
955 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900956}
957
Andrew Walbran6b650662021-09-07 13:13:23 +0000958/// Gets the `VirtualMachineState` of the given `VmInstance`.
959fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000960 match &*instance.vm_state.lock().unwrap() {
961 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
962 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000963 PayloadState::Starting => VirtualMachineState::STARTING,
964 PayloadState::Started => VirtualMachineState::STARTED,
965 PayloadState::Ready => VirtualMachineState::READY,
966 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900967 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000968 },
969 VmState::Dead => VirtualMachineState::DEAD,
970 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000971 }
972}
973
David Brazdilf50c7a62023-04-19 14:22:42 +0000974/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
975pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
976 file.as_ref().try_clone().map_err(|e| {
977 Status::new_exception_str(
978 ExceptionCode::BAD_PARCELABLE,
979 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
980 )
981 })
982}
983
Andrew Walbrand3a84182021-09-07 14:48:52 +0000984/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
985fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
986 file.as_ref().map(clone_file).transpose()
987}
988
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000989/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
990fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
991 // SAFETY: ownership is transferred from stream to f
992 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
993 ParcelFileDescriptor::new(f)
994}
995
Jiyong Parkdcf17412022-02-08 15:07:23 +0900996/// Parses the platform version requirement string.
997fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
998 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000999 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001000 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001001 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001002 )
1003 })
1004}
1005
Jiyong Parked180932023-02-24 19:55:41 +09001006/// Create the empty ramdump file
1007fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1008 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1009 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1010 // owner) for readout.
1011 let ramdump_path = temporary_directory.join("ramdump");
1012 let ramdump = File::create(ramdump_path).map_err(|e| {
1013 error!("Failed to prepare ramdump file: {:?}", e);
1014 Status::new_service_specific_error_str(
1015 -1,
1016 Some(format!("Failed to prepare ramdump file: {:?}", e)),
1017 )
1018 })?;
1019 Ok(ramdump)
1020}
1021
Nikita Ioffe5776f082023-02-10 21:38:26 +00001022fn is_protected(config: &VirtualMachineConfig) -> bool {
1023 match config {
1024 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1025 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1026 }
1027}
1028
1029fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1030 if is_protected(config) {
1031 return Err(Status::new_exception_str(
1032 ExceptionCode::SECURITY,
1033 Some("can't use gdb with protected VMs"),
1034 ));
1035 }
1036
1037 match config {
1038 VirtualMachineConfig::RawConfig(_) => Ok(()),
1039 VirtualMachineConfig::AppConfig(config) => {
1040 if config.debugLevel != DebugLevel::FULL {
1041 Err(Status::new_exception_str(
1042 ExceptionCode::SECURITY,
1043 Some("can't use gdb with non-debuggable VMs"),
1044 ))
1045 } else {
1046 Ok(())
1047 }
1048 }
1049 }
1050}
1051
1052fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1053 match config {
1054 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1055 VirtualMachineConfig::AppConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1056 }
1057}
1058
Inseob Kim0168b462022-12-27 14:54:35 +09001059fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001060 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001061 fd: Option<&ParcelFileDescriptor>,
1062 tag: String,
1063) -> Result<Option<File>, Status> {
1064 if let Some(fd) = fd {
1065 return Ok(Some(clone_file(fd)?));
1066 }
1067
Jaewan Kim61f86142023-03-28 15:12:52 +09001068 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001069 return Ok(None);
1070 };
Inseob Kim0168b462022-12-27 14:54:35 +09001071
1072 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
1073 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
1074 })?;
1075
1076 // SAFETY: We are the sole owners of these fds as they were just created.
1077 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
1078 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1079
1080 std::thread::spawn(move || loop {
1081 let mut buf = vec![];
1082 match reader.read_until(b'\n', &mut buf) {
1083 Ok(0) => {
1084 // EOF
1085 return;
1086 }
1087 Ok(size) => {
1088 if buf[size - 1] == b'\n' {
1089 buf.pop();
1090 }
1091 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1092 }
1093 Err(e) => {
1094 error!("Could not read console pipe: {:?}", e);
1095 return;
1096 }
1097 };
1098 });
1099
1100 Ok(Some(write_fd))
1101}
1102
Jooyung Han35edb8f2021-07-01 16:17:16 +09001103/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1104/// it doesn't require that T implements Clone.
1105enum BorrowedOrOwned<'a, T> {
1106 Borrowed(&'a T),
1107 Owned(T),
1108}
1109
1110impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1111 fn as_ref(&self) -> &T {
1112 match self {
1113 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001114 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001115 }
1116 }
1117}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001118
1119/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1120#[derive(Debug, Default)]
1121struct VirtualMachineService {
1122 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001123 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001124}
1125
1126impl Interface for VirtualMachineService {}
1127
1128impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001129 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1130 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001131 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001132 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001133 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1134 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1135 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001136 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001137
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001138 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1139 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001140 Ok(())
1141 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001142 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001143 Err(Status::new_service_specific_error_str(
1144 -1,
1145 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001146 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001147 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001148 }
Inseob Kim2444af92021-08-31 01:22:50 +09001149
Inseob Kimc7d28c72021-10-25 14:28:10 +00001150 fn notifyPayloadReady(&self) -> binder::Result<()> {
1151 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001152 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001153 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001154 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1155 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1156 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001157 vm.callbacks.notify_payload_ready(cid);
1158 Ok(())
1159 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001160 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001161 Err(Status::new_service_specific_error_str(
1162 -1,
1163 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001164 ))
1165 }
1166 }
1167
Inseob Kimc7d28c72021-10-25 14:28:10 +00001168 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1169 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001170 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001171 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001172 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1173 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1174 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001175 vm.callbacks.notify_payload_finished(cid, exit_code);
1176 Ok(())
1177 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001178 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001179 Err(Status::new_service_specific_error_str(
1180 -1,
1181 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001182 ))
1183 }
1184 }
1185
Alan Stokes2bead0d2022-09-05 16:58:34 +01001186 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001187 let cid = self.cid;
1188 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001189 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001190 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1191 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1192 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001193 vm.callbacks.notify_error(cid, error_code, message);
1194 Ok(())
1195 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001196 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001197 Err(Status::new_service_specific_error_str(
1198 -1,
1199 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001200 ))
1201 }
1202 }
Alice Wangc2fec932023-02-23 16:24:02 +00001203
1204 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
1205 let cid = self.cid;
1206 let Some(vm) = self.state.lock().unwrap().get_vm(cid) else {
1207 error!("requestCertificate is called from an unknown CID {cid}");
1208 return Err(Status::new_service_specific_error_str(
1209 -1,
1210 Some(format!("cannot find a VM with CID {}", cid)),
1211 ))
1212 };
1213 let instance_img_path = vm.temporary_directory.join("rkpvm_instance.img");
1214 let instance_img = OpenOptions::new()
1215 .create(true)
1216 .read(true)
1217 .write(true)
1218 .open(instance_img_path)
1219 .map_err(|e| {
1220 error!("Failed to create rkpvm_instance.img file: {:?}", e);
1221 Status::new_service_specific_error_str(
1222 -1,
1223 Some(format!("Failed to create rkpvm_instance.img file: {:?}", e)),
1224 )
1225 })?;
1226 GLOBAL_SERVICE.requestCertificate(csr, &ParcelFileDescriptor::new(instance_img))
1227 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001228}
1229
1230impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001231 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001232 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001233 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001234 BinderFeatures::default(),
1235 )
1236 }
1237}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001238
1239#[cfg(test)]
1240mod tests {
1241 use super::*;
1242
1243 #[test]
1244 fn test_is_allowed_label_for_partition() -> Result<()> {
1245 let expected_results = vec![
1246 ("u:object_r:system_file:s0", true),
1247 ("u:object_r:apk_data_file:s0", true),
1248 ("u:object_r:app_data_file:s0", false),
1249 ("u:object_r:app_data_file:s0:c512,c768", false),
1250 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1251 ("invalid", false),
1252 ("user:role:apk_data_file:severity:categories", true),
1253 ("user:role:apk_data_file:severity:categories:extraneous", false),
1254 ];
1255
1256 for (label, expected_valid) in expected_results {
1257 let context = SeContext::new(label)?;
1258 let result = check_label_is_allowed(&context);
1259 if expected_valid {
1260 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1261 } else if result.is_ok() {
1262 bail!("Expected label {} to be disallowed", label);
1263 }
1264 }
1265 Ok(())
1266 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001267
1268 #[test]
1269 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1270 let apk = tempfile::tempfile().unwrap();
1271 let idsig = tempfile::tempfile().unwrap();
1272
1273 let ret = create_or_update_idsig_file(
1274 &ParcelFileDescriptor::new(apk),
1275 &ParcelFileDescriptor::new(idsig),
1276 );
1277 assert!(ret.is_err(), "should fail");
1278 Ok(())
1279 }
1280
1281 #[test]
1282 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1283 let tmp_dir = tempfile::TempDir::new().unwrap();
1284 let apk = File::open(tmp_dir.path()).unwrap();
1285 let idsig = tempfile::tempfile().unwrap();
1286
1287 let ret = create_or_update_idsig_file(
1288 &ParcelFileDescriptor::new(apk),
1289 &ParcelFileDescriptor::new(idsig),
1290 );
1291 assert!(ret.is_err(), "should fail");
1292 Ok(())
1293 }
1294
1295 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1296 /// on ext4 filesystem is passed.
1297 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1298 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1299 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1300 #[test]
1301 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1302 // APEXes are backed by the ext4.
1303 let apk = File::open("/apex/com.android.virt/").unwrap();
1304 let idsig = tempfile::tempfile().unwrap();
1305
1306 let ret = create_or_update_idsig_file(
1307 &ParcelFileDescriptor::new(apk),
1308 &ParcelFileDescriptor::new(idsig),
1309 );
1310 assert!(ret.is_err(), "should fail");
1311 Ok(())
1312 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001313}