blob: 9cd70e6f061d398c734ffbcced623e9eb1f389dc [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)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900119
120 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
121 // if the idsig file already has the same APK digest.
122 if output.metadata()?.len() > 0 {
123 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
124 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
125 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
126 return Ok(());
127 }
128 }
129 // if we fail to read v4signature from output, that's fine. User can pass a random file.
130 // We will anyway overwrite the file to the v4signature generated from input_fd.
131 }
132
Nikita Ioffec09b0492022-12-14 20:18:33 +0000133 output.set_len(0).context("failed to set_len on the idsig output")?;
134 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000135 Ok(())
136}
137
Alan Stokes25f69362023-03-06 16:51:54 +0000138fn get_current_sdk() -> Result<u32> {
139 let current_sdk = system_properties::read("ro.build.version.sdk")?;
140 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
141 current_sdk.parse().context("Malformed SDK version")
142}
143
David Brazdil4b4c5102022-12-19 22:56:20 +0000144pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
145 for dir_entry in read_dir(path)? {
146 remove_file(dir_entry?.path())?;
147 }
148 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100149}
150
David Brazdil528e0472022-10-10 15:06:02 +0100151/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000152#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000153pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900154 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000155}
156
Shikha Panward8e35422021-10-11 13:51:27 +0000157impl Interface for VirtualizationService {
158 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
159 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
160 let state = &mut *self.state.lock().unwrap();
161 let vms = state.vms();
162 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
163 for vm in vms {
164 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
165 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
166 .or(Err(StatusCode::UNKNOWN_ERROR))?;
167 writeln!(file, "\tPayload state {:?}", vm.payload_state())
168 .or(Err(StatusCode::UNKNOWN_ERROR))?;
169 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
170 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
171 .or(Err(StatusCode::UNKNOWN_ERROR))?;
172 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
173 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000174 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
175 .or(Err(StatusCode::UNKNOWN_ERROR))?;
176 }
177 Ok(())
178 }
179}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000180
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000181impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000182 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
183 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000184 ///
185 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000186 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000187 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000188 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900189 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000190 log_fd: Option<&ParcelFileDescriptor>,
191 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000192 let mut is_protected = false;
193 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000194 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000195 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000196 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000197
Andrew Walbrandff3b942021-06-09 15:20:36 +0000198 /// Initialise an empty partition image of the given size to be used as a writable partition.
199 fn initializeWritablePartition(
200 &self,
201 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000202 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900203 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000204 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900205 check_manage_access()?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000206 let size_bytes = size_bytes.try_into().map_err(|e| {
207 Status::new_exception_str(
208 ExceptionCode::ILLEGAL_ARGUMENT,
209 Some(format!("Invalid size {}: {:?}", size_bytes, e)),
210 )
211 })?;
212 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
213 let image = clone_file(image_fd)?;
214 // initialize the file. Any data in the file will be erased.
215 image.set_len(0).map_err(|e| {
216 Status::new_service_specific_error_str(
217 -1,
218 Some(format!("Failed to reset a file: {:?}", e)),
219 )
220 })?;
221 let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
222 Status::new_service_specific_error_str(
223 -1,
224 Some(format!("Failed to create QCOW2 image: {:?}", e)),
225 )
226 })?;
227
228 match partition_type {
229 PartitionType::RAW => Ok(()),
230 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
231 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
232 _ => Err(Error::new(
233 ErrorKind::Unsupported,
234 format!("Unsupported partition type {:?}", partition_type),
235 )),
236 }
237 .map_err(|e| {
238 Status::new_service_specific_error_str(
239 -1,
240 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
241 )
242 })?;
243
244 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000245 }
246
Jiyong Park0a248432021-08-20 23:32:39 +0900247 /// Creates or update the idsig file by digesting the input APK file.
248 fn createOrUpdateIdsigFile(
249 &self,
250 input_fd: &ParcelFileDescriptor,
251 idsig_fd: &ParcelFileDescriptor,
252 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900253 check_manage_access()?;
254
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000255 create_or_update_idsig_file(input_fd, idsig_fd)
256 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900257 Ok(())
258 }
259
Andrew Walbran320b5602021-03-04 16:11:12 +0000260 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
261 /// and as such is only permitted from the shell user.
262 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000263 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000264 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000265 }
266}
267
Jiyong Park8611a6c2021-07-09 18:17:44 +0900268impl VirtualizationService {
269 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000270 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900271 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000272
David Brazdil209074a2023-01-12 16:44:51 +0000273 fn create_vm_context(
274 &self,
275 requester_debug_pid: pid_t,
276 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000277 const NUM_ATTEMPTS: usize = 5;
278
279 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000280 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000281 let cid = vm_context.getCid()? as Cid;
282 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000283 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
284
285 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000286 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000287 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000288 Ok(vm_server) => {
289 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000290 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000291 }
292 Err(err) => {
293 warn!("Could not start RpcServer on port {}: {}", port, err);
294 }
295 }
296 }
David Brazdil209074a2023-01-12 16:44:51 +0000297 Err(Status::new_service_specific_error_str(
298 -1,
299 Some("Too many attempts to create VM context failed."),
300 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000301 }
302
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000303 fn create_vm_internal(
304 &self,
305 config: &VirtualMachineConfig,
306 console_fd: Option<&ParcelFileDescriptor>,
307 log_fd: Option<&ParcelFileDescriptor>,
308 is_protected: &mut bool,
309 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000310 let requester_uid = get_calling_uid();
311 let requester_debug_pid = get_calling_pid();
312
313 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
314 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900315
Alan Stokes7bc146c2022-10-20 17:10:32 +0100316 let is_custom = match config {
317 VirtualMachineConfig::RawConfig(_) => true,
318 VirtualMachineConfig::AppConfig(config) => {
319 // Some features are reserved for platform apps only, even when using
320 // VirtualMachineAppConfig:
321 // - controlling CPUs;
Nikita Ioffe5776f082023-02-10 21:38:26 +0000322 // - specifying a config file in the APK;
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100323 // - gdbPort is set, meaning that crosvm will start a gdb server;
324 // - using anything other than the default kernel.
Nikita Ioffe5776f082023-02-10 21:38:26 +0000325 !config.taskProfiles.is_empty()
326 || matches!(config.payload, Payload::ConfigPath(_))
327 || config.gdbPort > 0
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100328 || config.customKernelImage.as_ref().is_some()
Inseob Kim1119d702022-05-02 18:01:58 +0900329 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100330 };
331 if is_custom {
332 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900333 }
334
Nikita Ioffe5776f082023-02-10 21:38:26 +0000335 let gdb_port = extract_gdb_port(config);
336
337 // Additional permission checks if caller request gdb.
338 if gdb_port.is_some() {
339 check_gdb_allowed(config)?;
340 }
341
Jaewan Kim61f86142023-03-28 15:12:52 +0900342 let debug_level = match config {
343 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
344 _ => DebugLevel::NONE,
345 };
346 let debug_config = DebugConfig::new(debug_level);
347
348 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900349 Some(prepare_ramdump_file(&temporary_directory)?)
350 } else {
351 None
352 };
353
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000354 let state = &mut *self.state.lock().unwrap();
Inseob Kim0168b462022-12-27 14:54:35 +0900355 let console_fd =
Jaewan Kim61f86142023-03-28 15:12:52 +0900356 clone_or_prepare_logger_fd(&debug_config, console_fd, format!("Console({})", cid))?;
357 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000358
359 // Counter to generate unique IDs for temporary image files.
360 let mut next_temporary_image_id = 0;
361 // Files which are referred to from composite images. These must be mapped to the crosvm
362 // child process, and not closed before it is started.
363 let mut indirect_files = vec![];
364
Alan Stokes7bc146c2022-10-20 17:10:32 +0100365 let (is_app_config, config) = match config {
366 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
367 VirtualMachineConfig::AppConfig(config) => {
Jaewan Kim61f86142023-03-28 15:12:52 +0900368 let config =
369 load_app_config(config, &debug_config, &temporary_directory).map_err(|e| {
370 *is_protected = config.protectedVm;
371 let message = format!("Failed to load app config: {:?}", e);
372 error!("{}", message);
373 Status::new_service_specific_error_str(-1, Some(message))
374 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100375 (true, BorrowedOrOwned::Owned(config))
376 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000377 };
378 let config = config.as_ref();
379 *is_protected = config.protectedVm;
380
381 // Check if partition images are labeled incorrectly. This is to prevent random images
382 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100383 // being loaded in a pVM. This applies to everything in the raw config, and everything but
384 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000385 config
386 .disks
387 .iter()
388 .flat_map(|disk| disk.partitions.iter())
389 .filter(|partition| {
390 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100391 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000392 } else {
393 true // all partitions are checked
394 }
395 })
396 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100397 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000398
Alan Stokes185fe112023-01-10 16:20:55 +0000399 let kernel = maybe_clone_file(&config.kernel)?;
400 let initrd = maybe_clone_file(&config.initrd)?;
401
402 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
403 if config.protectedVm {
404 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
405 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
406 })?;
407 }
408
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000409 let zero_filler_path = temporary_directory.join("zero.img");
410 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100411 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000412 Status::new_service_specific_error_str(
413 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100414 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000415 )
416 })?;
417
418 // Assemble disk images if needed.
419 let disks = config
420 .disks
421 .iter()
422 .map(|disk| {
423 assemble_disk_image(
424 disk,
425 &zero_filler_path,
426 &temporary_directory,
427 &mut next_temporary_image_id,
428 &mut indirect_files,
429 )
430 })
431 .collect::<Result<Vec<DiskFile>, _>>()?;
432
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000433 let (cpus, host_cpu_topology) = match config.cpuTopology {
434 CpuTopology::MATCH_HOST => (None, true),
435 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
436 val => {
437 error!("Unexpected value of CPU topology: {:?}", val);
438 return Err(Status::new_service_specific_error_str(
439 -1,
440 Some(format!("Failed to parse CPU topology value: {:?}", val)),
441 ));
442 }
443 };
444
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000445 // Actually start the VM.
446 let crosvm_config = CrosvmConfig {
447 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000448 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000449 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000450 kernel,
451 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000452 disks,
453 params: config.params.to_owned(),
454 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900455 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000456 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000457 cpus,
458 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900459 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000460 console_fd,
461 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900462 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000463 indirect_files,
464 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900465 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000466 gdb_port,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000467 };
468 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100469 VmInstance::new(
470 crosvm_config,
471 temporary_directory,
472 requester_uid,
473 requester_debug_pid,
474 vm_context,
475 )
476 .map_err(|e| {
477 error!("Failed to create VM with config {:?}: {:?}", config, e);
478 Status::new_service_specific_error_str(
479 -1,
480 Some(format!("Failed to create VM: {:?}", e)),
481 )
482 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000483 );
484 state.add_vm(Arc::downgrade(&instance));
485 Ok(VirtualMachine::create(instance))
486 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900487}
488
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000489fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900490 let file = OpenOptions::new()
491 .create_new(true)
492 .read(true)
493 .write(true)
494 .open(zero_filler_path)
495 .with_context(|| "Failed to create zero.img")?;
496 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000497 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900498}
499
David Brazdilf50c7a62023-04-19 14:22:42 +0000500fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
501 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
502 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
503 part.flush()
504}
505
506fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
507 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
508 part.flush()
509}
510
511fn round_up(input: u64, granularity: u64) -> u64 {
512 if granularity == 0 {
513 return input;
514 }
515 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
516 let result = input.checked_add(granularity - 1).unwrap_or(input);
517 (result / granularity) * granularity
518}
519
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000520/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
521///
522/// This may involve assembling a composite disk from a set of partition images.
523fn assemble_disk_image(
524 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900525 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000526 temporary_directory: &Path,
527 next_temporary_image_id: &mut u64,
528 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000529) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000530 let image = if !disk.partitions.is_empty() {
531 if disk.image.is_some() {
532 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000533 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000534 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000535 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000536 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000537 }
538
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000539 let composite_image_filenames =
540 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
541 let (image, partition_files) = make_composite_image(
542 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900543 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000544 &composite_image_filenames.composite,
545 &composite_image_filenames.header,
546 &composite_image_filenames.footer,
547 )
548 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100549 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000550 Status::new_service_specific_error_str(
551 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100552 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000553 )
554 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000555
556 // Pass the file descriptors for the various partition files to crosvm when it
557 // is run.
558 indirect_files.extend(partition_files);
559
560 image
561 } else if let Some(image) = &disk.image {
562 clone_file(image)?
563 } else {
564 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000565 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000566 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000567 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000568 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000569 };
570
571 Ok(DiskFile { image, writable: disk.writable })
572}
573
Jooyung Han21e9b922021-06-26 04:14:16 +0900574fn load_app_config(
575 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900576 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900577 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900578) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000579 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
580 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900581 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900582
Shikha Panwar22e70452022-10-10 18:32:55 +0000583 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
584 Some(clone_file(file)?)
585 } else {
586 None
587 };
588
Alan Stokes0d1ef782022-09-27 13:46:35 +0100589 let vm_payload_config = match &config.payload {
590 Payload::ConfigPath(config_path) => {
591 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
592 .with_context(|| format!("Couldn't read config from {}", config_path))?
593 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000594 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100595 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900596
Alan Stokes0d1ef782022-09-27 13:46:35 +0100597 // For now, the only supported OS is Microdroid
598 let os_name = vm_payload_config.os.name.as_str();
599 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000600 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900601 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000602
603 // It is safe to construct a filename based on the os_name because we've already checked that it
604 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900605 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
606 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000607 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900608
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100609 if let Some(file) = config.customKernelImage.as_ref() {
610 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
611 }
612
Andrew Walbrancc045902021-07-27 16:06:17 +0000613 if config.memoryMib > 0 {
614 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000615 }
616
Seungjae Yoo62085c02022-08-12 04:44:52 +0000617 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000618 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000619 vm_config.cpuTopology = config.cpuTopology;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900620 vm_config.taskProfiles = config.taskProfiles.clone();
Nikita Ioffe5776f082023-02-10 21:38:26 +0000621 vm_config.gdbPort = config.gdbPort;
Jiyong Park032615f2022-01-10 13:55:34 +0900622
Shikha Panwar22e70452022-10-10 18:32:55 +0000623 // Microdroid takes additional init ramdisk & (optionally) storage image
624 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
625
626 // Include Microdroid payload disk (contains apks, idsigs) in vm config
627 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100628 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900629 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100630 temporary_directory,
631 apk_file,
632 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100633 &vm_payload_config,
634 &mut vm_config,
635 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900636
Andrew Walbrancc0db522021-07-12 17:03:42 +0000637 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900638}
639
Alan Stokes0d1ef782022-09-27 13:46:35 +0100640fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
641 let mut apk_zip = ZipArchive::new(apk_file)?;
642 let config_file = apk_zip.by_name(config_path)?;
643 Ok(serde_json::from_reader(config_file)?)
644}
645
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000646fn create_vm_payload_config(
647 payload_config: &VirtualMachinePayloadConfig,
648) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100649 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
650 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
651 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000652
653 let payload_binary_name = &payload_config.payloadBinaryName;
654 if payload_binary_name.contains('/') {
655 bail!("Payload binary name must not specify a path: {payload_binary_name}");
656 }
657
658 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
659 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100660 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
661 task: Some(task),
662 apexes: vec![],
663 extra_apks: vec![],
664 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900665 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100666 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000667 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100668}
669
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000670/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000671fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000672 temporary_directory: &Path,
673 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000674) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000675 let id = *next_temporary_image_id;
676 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000677 CompositeImageFilenames {
678 composite: temporary_directory.join(format!("composite-{}.img", id)),
679 header: temporary_directory.join(format!("composite-{}-header.img", id)),
680 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
681 }
682}
683
684/// Filenames for a composite disk image, including header and footer partitions.
685#[derive(Clone, Debug, Eq, PartialEq)]
686struct CompositeImageFilenames {
687 /// The composite disk image itself.
688 composite: PathBuf,
689 /// The header partition image.
690 header: PathBuf,
691 /// The footer partition image.
692 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000693}
694
Jiyong Park753553b2021-07-12 21:21:09 +0900695/// Checks whether the caller has a specific permission
696fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100697 let calling_pid = get_calling_pid();
698 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900699 // Root can do anything
700 if calling_uid == 0 {
701 return Ok(());
702 }
703 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
704 binder::get_interface("permission")?;
705 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000706 Ok(())
707 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000708 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900709 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000710 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900711 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000712 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000713}
714
Jiyong Park753553b2021-07-12 21:21:09 +0900715/// Check whether the caller of the current Binder method is allowed to manage VMs
716fn check_manage_access() -> binder::Result<()> {
717 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
718}
719
Inseob Kim1119d702022-05-02 18:01:58 +0900720/// Check whether the caller of the current Binder method is allowed to create custom VMs
721fn check_use_custom_virtual_machine() -> binder::Result<()> {
722 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
723}
724
Alan Stokes185fe112023-01-10 16:20:55 +0000725/// Return whether a partition is exempt from selinux label checks, because we know that it does
726/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100727fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000728 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100729 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000730 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100731 || label == "microdroid-apk-idsig"
732 || label == "payload-metadata"
733 || label.starts_with("extra-idsig-")
734}
735
Alan Stokes185fe112023-01-10 16:20:55 +0000736/// Check that a file SELinux label is acceptable.
737///
738/// We only want to allow code in a VM to be sourced from places that apps, and the
739/// system, do not have write access to.
740///
741/// Note that sepolicy must also grant read access for these types to both virtualization
742/// service and crosvm.
743///
744/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
745/// user devices (W^X).
746fn check_label_is_allowed(context: &SeContext) -> Result<()> {
747 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100748 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100749 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000750 | "staging_data_file" // updated/staged APEX images
751 | "system_file" // immutable dm-verity protected partition
752 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100753 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000754 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900755 }
756}
757
Alan Stokes185fe112023-01-10 16:20:55 +0000758fn check_label_for_partition(partition: &Partition) -> Result<()> {
759 let file = partition.image.as_ref().unwrap().as_ref();
760 check_label_is_allowed(&getfilecon(file)?)
761 .with_context(|| format!("Partition {} invalid", &partition.label))
762}
763
764fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
765 if let Some(f) = kernel {
766 check_label_for_file(f, "kernel")?;
767 }
768 if let Some(f) = initrd {
769 check_label_for_file(f, "initrd")?;
770 }
771 Ok(())
772}
773fn check_label_for_file(file: &File, name: &str) -> Result<()> {
774 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
775}
776
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000777/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
778#[derive(Debug)]
779struct VirtualMachine {
780 instance: Arc<VmInstance>,
781}
782
783impl VirtualMachine {
784 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000785 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000786 }
787}
788
789impl Interface for VirtualMachine {}
790
791impl IVirtualMachine for VirtualMachine {
792 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900793 // Don't check permission. The owner of the VM might have passed this binder object to
794 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000795 Ok(self.instance.cid as i32)
796 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000797
Andrew Walbran6b650662021-09-07 13:13:23 +0000798 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900799 // Don't check permission. The owner of the VM might have passed this binder object to
800 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000801 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000802 }
803
804 fn registerCallback(
805 &self,
806 callback: &Strong<dyn IVirtualMachineCallback>,
807 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900808 // Don't check permission. The owner of the VM might have passed this binder object to
809 // others.
810 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000811 // TODO: Should this give an error if the VM is already dead?
812 self.instance.callbacks.add(callback.clone());
813 Ok(())
814 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000815
Andrew Walbranf8d94112021-09-07 11:45:36 +0000816 fn start(&self) -> binder::Result<()> {
817 self.instance.start().map_err(|e| {
818 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000819 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000820 })
821 }
822
Inseob Kima446f802022-07-11 19:46:37 +0900823 fn stop(&self) -> binder::Result<()> {
824 self.instance.kill().map_err(|e| {
825 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000826 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900827 })
828 }
829
Keir Frasercdd4b112022-11-24 14:02:25 +0000830 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
831 self.instance.trim_memory(level).map_err(|e| {
832 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
833 Status::new_service_specific_error_str(-1, Some(e.to_string()))
834 })
835 }
836
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000837 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000838 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000839 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000840 }
Alan Stokes10c47672022-12-13 17:17:08 +0000841 let port = port as u32;
842 if port < 1024 {
843 return Err(Status::new_service_specific_error_str(
844 -1,
845 Some(format!("Can't connect to privileged port {port}")),
846 ));
847 }
848 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
849 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
850 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000851 Ok(vsock_stream_to_pfd(stream))
852 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000853}
854
855impl Drop for VirtualMachine {
856 fn drop(&mut self) {
857 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900858 if let Err(e) = self.instance.kill() {
859 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
860 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000861 }
862}
863
864/// A set of Binders to be called back in response to various events on the VM, such as when it
865/// dies.
866#[derive(Debug, Default)]
867pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
868
869impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900870 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100871 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900872 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900873 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100874 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100875 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900876 }
877 }
878 }
879
Inseob Kim14cb8692021-08-31 21:50:39 +0900880 /// Call all registered callbacks to notify that the payload is ready to serve.
881 pub fn notify_payload_ready(&self, cid: Cid) {
882 let callbacks = &*self.0.lock().unwrap();
883 for callback in callbacks {
884 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100885 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900886 }
887 }
888 }
889
Inseob Kim2444af92021-08-31 01:22:50 +0900890 /// Call all registered callbacks to notify that the payload has finished.
891 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
892 let callbacks = &*self.0.lock().unwrap();
893 for callback in callbacks {
894 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100895 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900896 }
897 }
898 }
899
Jooyung Handd0a1732021-11-23 15:26:20 +0900900 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100901 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900902 let callbacks = &*self.0.lock().unwrap();
903 for callback in callbacks {
904 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100905 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900906 }
907 }
908 }
909
Andrew Walbrandae07162021-03-12 17:05:20 +0000910 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000911 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000912 let callbacks = &*self.0.lock().unwrap();
913 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000914 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100915 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000916 }
917 }
918 }
919
920 /// Add a new callback to the set.
921 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
922 self.0.lock().unwrap().push(callback);
923 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000924}
925
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000926/// The mutable state of the VirtualizationService. There should only be one instance of this
927/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800928#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000929struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000930 /// The VMs which have been started. When VMs are started a weak reference is added to this list
931 /// while a strong reference is returned to the caller over Binder. Once all copies of the
932 /// Binder client are dropped the weak reference here will become invalid, and will be removed
933 /// from the list opportunistically the next time `add_vm` is called.
934 vms: Vec<Weak<VmInstance>>,
935}
936
937impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000938 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000939 fn vms(&self) -> Vec<Arc<VmInstance>> {
940 // Attempt to upgrade the weak pointers to strong pointers.
941 self.vms.iter().filter_map(Weak::upgrade).collect()
942 }
943
944 /// Add a new VM to the list.
945 fn add_vm(&mut self, vm: Weak<VmInstance>) {
946 // Garbage collect any entries from the stored list which no longer exist.
947 self.vms.retain(|vm| vm.strong_count() > 0);
948
949 // Actually add the new VM.
950 self.vms.push(vm);
951 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000952
Jiyong Park8611a6c2021-07-09 18:17:44 +0900953 /// Get a VM that corresponds to the given cid
954 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
955 self.vms().into_iter().find(|vm| vm.cid == cid)
956 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900957}
958
Andrew Walbran6b650662021-09-07 13:13:23 +0000959/// Gets the `VirtualMachineState` of the given `VmInstance`.
960fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000961 match &*instance.vm_state.lock().unwrap() {
962 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
963 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000964 PayloadState::Starting => VirtualMachineState::STARTING,
965 PayloadState::Started => VirtualMachineState::STARTED,
966 PayloadState::Ready => VirtualMachineState::READY,
967 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900968 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000969 },
970 VmState::Dead => VirtualMachineState::DEAD,
971 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000972 }
973}
974
David Brazdilf50c7a62023-04-19 14:22:42 +0000975/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
976pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
977 file.as_ref().try_clone().map_err(|e| {
978 Status::new_exception_str(
979 ExceptionCode::BAD_PARCELABLE,
980 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
981 )
982 })
983}
984
Andrew Walbrand3a84182021-09-07 14:48:52 +0000985/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
986fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
987 file.as_ref().map(clone_file).transpose()
988}
989
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000990/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
991fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
992 // SAFETY: ownership is transferred from stream to f
993 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
994 ParcelFileDescriptor::new(f)
995}
996
Jiyong Parkdcf17412022-02-08 15:07:23 +0900997/// Parses the platform version requirement string.
998fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
999 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001000 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001001 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001002 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001003 )
1004 })
1005}
1006
Jiyong Parked180932023-02-24 19:55:41 +09001007/// Create the empty ramdump file
1008fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1009 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1010 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1011 // owner) for readout.
1012 let ramdump_path = temporary_directory.join("ramdump");
1013 let ramdump = File::create(ramdump_path).map_err(|e| {
1014 error!("Failed to prepare ramdump file: {:?}", e);
1015 Status::new_service_specific_error_str(
1016 -1,
1017 Some(format!("Failed to prepare ramdump file: {:?}", e)),
1018 )
1019 })?;
1020 Ok(ramdump)
1021}
1022
Nikita Ioffe5776f082023-02-10 21:38:26 +00001023fn is_protected(config: &VirtualMachineConfig) -> bool {
1024 match config {
1025 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1026 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1027 }
1028}
1029
1030fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1031 if is_protected(config) {
1032 return Err(Status::new_exception_str(
1033 ExceptionCode::SECURITY,
1034 Some("can't use gdb with protected VMs"),
1035 ));
1036 }
1037
1038 match config {
1039 VirtualMachineConfig::RawConfig(_) => Ok(()),
1040 VirtualMachineConfig::AppConfig(config) => {
1041 if config.debugLevel != DebugLevel::FULL {
1042 Err(Status::new_exception_str(
1043 ExceptionCode::SECURITY,
1044 Some("can't use gdb with non-debuggable VMs"),
1045 ))
1046 } else {
1047 Ok(())
1048 }
1049 }
1050 }
1051}
1052
1053fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1054 match config {
1055 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1056 VirtualMachineConfig::AppConfig(config) => NonZeroU16::new(config.gdbPort as u16),
1057 }
1058}
1059
Inseob Kim0168b462022-12-27 14:54:35 +09001060fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001061 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001062 fd: Option<&ParcelFileDescriptor>,
1063 tag: String,
1064) -> Result<Option<File>, Status> {
1065 if let Some(fd) = fd {
1066 return Ok(Some(clone_file(fd)?));
1067 }
1068
Jaewan Kim61f86142023-03-28 15:12:52 +09001069 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001070 return Ok(None);
1071 };
Inseob Kim0168b462022-12-27 14:54:35 +09001072
1073 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
1074 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
1075 })?;
1076
1077 // SAFETY: We are the sole owners of these fds as they were just created.
1078 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
1079 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1080
1081 std::thread::spawn(move || loop {
1082 let mut buf = vec![];
1083 match reader.read_until(b'\n', &mut buf) {
1084 Ok(0) => {
1085 // EOF
1086 return;
1087 }
1088 Ok(size) => {
1089 if buf[size - 1] == b'\n' {
1090 buf.pop();
1091 }
1092 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1093 }
1094 Err(e) => {
1095 error!("Could not read console pipe: {:?}", e);
1096 return;
1097 }
1098 };
1099 });
1100
1101 Ok(Some(write_fd))
1102}
1103
Jooyung Han35edb8f2021-07-01 16:17:16 +09001104/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1105/// it doesn't require that T implements Clone.
1106enum BorrowedOrOwned<'a, T> {
1107 Borrowed(&'a T),
1108 Owned(T),
1109}
1110
1111impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1112 fn as_ref(&self) -> &T {
1113 match self {
1114 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001115 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001116 }
1117 }
1118}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001119
1120/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1121#[derive(Debug, Default)]
1122struct VirtualMachineService {
1123 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001124 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001125}
1126
1127impl Interface for VirtualMachineService {}
1128
1129impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001130 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1131 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001132 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001133 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001134 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1135 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1136 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001137 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001138
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001139 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1140 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001141 Ok(())
1142 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001143 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001144 Err(Status::new_service_specific_error_str(
1145 -1,
1146 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001147 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001148 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001149 }
Inseob Kim2444af92021-08-31 01:22:50 +09001150
Inseob Kimc7d28c72021-10-25 14:28:10 +00001151 fn notifyPayloadReady(&self) -> binder::Result<()> {
1152 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001153 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001154 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001155 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1156 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1157 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001158 vm.callbacks.notify_payload_ready(cid);
1159 Ok(())
1160 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001161 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001162 Err(Status::new_service_specific_error_str(
1163 -1,
1164 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001165 ))
1166 }
1167 }
1168
Inseob Kimc7d28c72021-10-25 14:28:10 +00001169 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1170 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001171 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001172 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001173 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1174 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1175 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001176 vm.callbacks.notify_payload_finished(cid, exit_code);
1177 Ok(())
1178 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001179 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001180 Err(Status::new_service_specific_error_str(
1181 -1,
1182 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001183 ))
1184 }
1185 }
1186
Alan Stokes2bead0d2022-09-05 16:58:34 +01001187 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001188 let cid = self.cid;
1189 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001190 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001191 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1192 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1193 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001194 vm.callbacks.notify_error(cid, error_code, message);
1195 Ok(())
1196 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001197 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001198 Err(Status::new_service_specific_error_str(
1199 -1,
1200 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001201 ))
1202 }
1203 }
Alice Wangc2fec932023-02-23 16:24:02 +00001204
1205 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
1206 let cid = self.cid;
1207 let Some(vm) = self.state.lock().unwrap().get_vm(cid) else {
1208 error!("requestCertificate is called from an unknown CID {cid}");
1209 return Err(Status::new_service_specific_error_str(
1210 -1,
1211 Some(format!("cannot find a VM with CID {}", cid)),
1212 ))
1213 };
1214 let instance_img_path = vm.temporary_directory.join("rkpvm_instance.img");
1215 let instance_img = OpenOptions::new()
1216 .create(true)
1217 .read(true)
1218 .write(true)
1219 .open(instance_img_path)
1220 .map_err(|e| {
1221 error!("Failed to create rkpvm_instance.img file: {:?}", e);
1222 Status::new_service_specific_error_str(
1223 -1,
1224 Some(format!("Failed to create rkpvm_instance.img file: {:?}", e)),
1225 )
1226 })?;
1227 GLOBAL_SERVICE.requestCertificate(csr, &ParcelFileDescriptor::new(instance_img))
1228 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001229}
1230
1231impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001232 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001233 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001234 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001235 BinderFeatures::default(),
1236 )
1237 }
1238}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001239
1240#[cfg(test)]
1241mod tests {
1242 use super::*;
1243
1244 #[test]
1245 fn test_is_allowed_label_for_partition() -> Result<()> {
1246 let expected_results = vec![
1247 ("u:object_r:system_file:s0", true),
1248 ("u:object_r:apk_data_file:s0", true),
1249 ("u:object_r:app_data_file:s0", false),
1250 ("u:object_r:app_data_file:s0:c512,c768", false),
1251 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1252 ("invalid", false),
1253 ("user:role:apk_data_file:severity:categories", true),
1254 ("user:role:apk_data_file:severity:categories:extraneous", false),
1255 ];
1256
1257 for (label, expected_valid) in expected_results {
1258 let context = SeContext::new(label)?;
1259 let result = check_label_is_allowed(&context);
1260 if expected_valid {
1261 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1262 } else if result.is_ok() {
1263 bail!("Expected label {} to be disallowed", label);
1264 }
1265 }
1266 Ok(())
1267 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001268
1269 #[test]
1270 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1271 let apk = tempfile::tempfile().unwrap();
1272 let idsig = tempfile::tempfile().unwrap();
1273
1274 let ret = create_or_update_idsig_file(
1275 &ParcelFileDescriptor::new(apk),
1276 &ParcelFileDescriptor::new(idsig),
1277 );
1278 assert!(ret.is_err(), "should fail");
1279 Ok(())
1280 }
1281
1282 #[test]
1283 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1284 let tmp_dir = tempfile::TempDir::new().unwrap();
1285 let apk = File::open(tmp_dir.path()).unwrap();
1286 let idsig = tempfile::tempfile().unwrap();
1287
1288 let ret = create_or_update_idsig_file(
1289 &ParcelFileDescriptor::new(apk),
1290 &ParcelFileDescriptor::new(idsig),
1291 );
1292 assert!(ret.is_err(), "should fail");
1293 Ok(())
1294 }
1295
1296 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1297 /// on ext4 filesystem is passed.
1298 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1299 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1300 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1301 #[test]
1302 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1303 // APEXes are backed by the ext4.
1304 let apk = File::open("/apex/com.android.virt/").unwrap();
1305 let idsig = tempfile::tempfile().unwrap();
1306
1307 let ret = create_or_update_idsig_file(
1308 &ParcelFileDescriptor::new(apk),
1309 &ParcelFileDescriptor::new(idsig),
1310 );
1311 assert!(ret.is_err(), "should fail");
1312 Ok(())
1313 }
Jiyong Park8d192952023-06-26 14:29:51 +09001314
1315 #[test]
1316 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1317 use std::io::Seek;
1318
1319 // Pick any APK
1320 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1321 let mut idsig = tempfile::tempfile().unwrap();
1322
1323 create_or_update_idsig_file(
1324 &ParcelFileDescriptor::new(apk.try_clone()?),
1325 &ParcelFileDescriptor::new(idsig.try_clone()?),
1326 )?;
1327 let modified_orig = idsig.metadata()?.modified()?;
1328 apk.rewind()?;
1329 idsig.rewind()?;
1330
1331 // Call the function again
1332 create_or_update_idsig_file(
1333 &ParcelFileDescriptor::new(apk.try_clone()?),
1334 &ParcelFileDescriptor::new(idsig.try_clone()?),
1335 )?;
1336 let modified_new = idsig.metadata()?.modified()?;
1337 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1338 Ok(())
1339 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001340}