blob: daee7c5511945782a11413c2e58eaba4d4c2ca11 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
David Brazdil1f530702022-10-03 12:18:10 +010017use crate::{get_calling_pid, get_calling_uid};
David Brazdil49f96f52022-12-16 21:29:13 +000018use crate::atom::{
David Brazdil49f96f52022-12-16 21:29:13 +000019 write_vm_booted_stats, write_vm_creation_stats};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000020use crate::composite::make_composite_image;
David Brazdil8cf8f482022-11-23 14:21:26 +000021use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmContext, VmInstance, VmState};
Jaewan Kim61f86142023-03-28 15:12:52 +090022use crate::debug_config::DebugConfig;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +010023use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090024use crate::selinux::{getfilecon, SeContext};
Jiyong Park753553b2021-07-12 21:21:09 +090025use android_os_permissions_aidl::aidl::android::os::IPermissionController;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000027 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000028 ErrorCode::ErrorCode,
29};
30use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090031 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000032 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000033 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010034 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000035 IVirtualMachineCallback::IVirtualMachineCallback,
36 IVirtualizationService::IVirtualizationService,
Keir Frasercdd4b112022-11-24 14:02:25 +000037 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090038 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000039 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090040 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090041 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000042 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010043 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090044 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000045 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090046};
David Brazdilafc9a9e2023-01-12 16:08:10 +000047use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090048use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000049 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090050};
Alan Stokes25f69362023-03-06 16:51:54 +000051use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090052use apkverify::{HashAlgorithm, V4Signature};
Alan Stokes0e82b502022-08-08 14:44:48 +010053use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000054 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
55 Status, StatusCode, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000056};
David Brazdilf50c7a62023-04-19 14:22:42 +000057use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000058use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000059use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090060use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090061use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000062use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000063use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090064use semver::VersionReq;
Andrew Walbrandff3b942021-06-09 15:20:36 +000065use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000066use std::ffi::CStr;
David Brazdilafc9a9e2023-01-12 16:08:10 +000067use std::fs::{read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000068use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000069use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000070use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000071use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000072use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000073use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000074use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000075use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090076use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000077
David Brazdil41d1a872022-10-05 14:44:19 +010078/// The unique ID of a VM used (together with a port number) for vsock communication.
79pub type Cid = u32;
80
David Brazdil4b4c5102022-12-19 22:56:20 +000081pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
82
Jooyung Han95884632021-07-06 22:27:54 +090083/// The size of zero.img.
84/// Gaps in composite disk images are filled with a shared zero.img.
85const ZERO_FILLER_SIZE: u64 = 4096;
86
David Brazdilf50c7a62023-04-19 14:22:42 +000087/// Magic string for the instance image
88const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
89
90/// Version of the instance image format
91const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
92
Alan Stokes0d1ef782022-09-27 13:46:35 +010093const MICRODROID_OS_NAME: &str = "microdroid";
94
David Brazdilf50c7a62023-04-19 14:22:42 +000095const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
96
97/// crosvm requires all partitions to be a multiple of 4KiB.
98const PARTITION_GRANULARITY_BYTES: u64 = 4096;
99
David Brazdil49f96f52022-12-16 21:29:13 +0000100lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000101 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
102 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
103 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000104}
105
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000106fn create_or_update_idsig_file(
107 input_fd: &ParcelFileDescriptor,
108 idsig_fd: &ParcelFileDescriptor,
109) -> Result<()> {
110 let mut input = clone_file(input_fd)?;
111 let metadata = input.metadata().context("failed to get input metadata")?;
112 if !metadata.is_file() {
113 bail!("input is not a regular file");
114 }
Alan Stokes25f69362023-03-06 16:51:54 +0000115 let mut sig =
116 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
117 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000118
119 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900120
121 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
122 // if the idsig file already has the same APK digest.
123 if output.metadata()?.len() > 0 {
124 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
125 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
126 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
127 return Ok(());
128 }
129 }
130 // if we fail to read v4signature from output, that's fine. User can pass a random file.
131 // We will anyway overwrite the file to the v4signature generated from input_fd.
132 }
133
Nikita Ioffec09b0492022-12-14 20:18:33 +0000134 output.set_len(0).context("failed to set_len on the idsig output")?;
135 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000136 Ok(())
137}
138
Alan Stokes25f69362023-03-06 16:51:54 +0000139fn get_current_sdk() -> Result<u32> {
140 let current_sdk = system_properties::read("ro.build.version.sdk")?;
141 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
142 current_sdk.parse().context("Malformed SDK version")
143}
144
David Brazdil4b4c5102022-12-19 22:56:20 +0000145pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
146 for dir_entry in read_dir(path)? {
147 remove_file(dir_entry?.path())?;
148 }
149 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100150}
151
David Brazdil528e0472022-10-10 15:06:02 +0100152/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000153#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000154pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900155 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000156}
157
Shikha Panward8e35422021-10-11 13:51:27 +0000158impl Interface for VirtualizationService {
159 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
160 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
161 let state = &mut *self.state.lock().unwrap();
162 let vms = state.vms();
163 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
164 for vm in vms {
165 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
166 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
167 .or(Err(StatusCode::UNKNOWN_ERROR))?;
168 writeln!(file, "\tPayload state {:?}", vm.payload_state())
169 .or(Err(StatusCode::UNKNOWN_ERROR))?;
170 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
171 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
172 .or(Err(StatusCode::UNKNOWN_ERROR))?;
173 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
174 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000175 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
176 .or(Err(StatusCode::UNKNOWN_ERROR))?;
177 }
178 Ok(())
179 }
180}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000181
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000182impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000183 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
184 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000185 ///
186 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000187 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000188 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000189 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900190 console_out_fd: Option<&ParcelFileDescriptor>,
191 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000192 log_fd: Option<&ParcelFileDescriptor>,
193 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000194 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900195 let ret = self.create_vm_internal(
196 config,
197 console_out_fd,
198 console_in_fd,
199 log_fd,
200 &mut is_protected,
201 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000202 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000203 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000204 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000205
Andrew Walbrandff3b942021-06-09 15:20:36 +0000206 /// Initialise an empty partition image of the given size to be used as a writable partition.
207 fn initializeWritablePartition(
208 &self,
209 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000210 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900211 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000212 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900213 check_manage_access()?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000214 let size_bytes = size_bytes.try_into().map_err(|e| {
215 Status::new_exception_str(
216 ExceptionCode::ILLEGAL_ARGUMENT,
217 Some(format!("Invalid size {}: {:?}", size_bytes, e)),
218 )
219 })?;
220 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
221 let image = clone_file(image_fd)?;
222 // initialize the file. Any data in the file will be erased.
223 image.set_len(0).map_err(|e| {
224 Status::new_service_specific_error_str(
225 -1,
226 Some(format!("Failed to reset a file: {:?}", e)),
227 )
228 })?;
229 let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
230 Status::new_service_specific_error_str(
231 -1,
232 Some(format!("Failed to create QCOW2 image: {:?}", e)),
233 )
234 })?;
235
236 match partition_type {
237 PartitionType::RAW => Ok(()),
238 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
239 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
240 _ => Err(Error::new(
241 ErrorKind::Unsupported,
242 format!("Unsupported partition type {:?}", partition_type),
243 )),
244 }
245 .map_err(|e| {
246 Status::new_service_specific_error_str(
247 -1,
248 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
249 )
250 })?;
251
252 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000253 }
254
Jiyong Park0a248432021-08-20 23:32:39 +0900255 /// Creates or update the idsig file by digesting the input APK file.
256 fn createOrUpdateIdsigFile(
257 &self,
258 input_fd: &ParcelFileDescriptor,
259 idsig_fd: &ParcelFileDescriptor,
260 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900261 check_manage_access()?;
262
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000263 create_or_update_idsig_file(input_fd, idsig_fd)
264 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900265 Ok(())
266 }
267
Andrew Walbran320b5602021-03-04 16:11:12 +0000268 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
269 /// and as such is only permitted from the shell user.
270 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000271 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000272 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000273 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900274
275 /// Get a list of assignable device types.
276 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
277 // Delegate to the global service, including checking the permission.
278 GLOBAL_SERVICE.getAssignableDevices()
279 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000280}
281
Jiyong Park8611a6c2021-07-09 18:17:44 +0900282impl VirtualizationService {
283 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000284 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900285 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000286
David Brazdil209074a2023-01-12 16:44:51 +0000287 fn create_vm_context(
288 &self,
289 requester_debug_pid: pid_t,
290 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000291 const NUM_ATTEMPTS: usize = 5;
292
293 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000294 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000295 let cid = vm_context.getCid()? as Cid;
296 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000297 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
298
299 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000300 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000301 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000302 Ok(vm_server) => {
303 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000304 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000305 }
306 Err(err) => {
307 warn!("Could not start RpcServer on port {}: {}", port, err);
308 }
309 }
310 }
David Brazdil209074a2023-01-12 16:44:51 +0000311 Err(Status::new_service_specific_error_str(
312 -1,
313 Some("Too many attempts to create VM context failed."),
314 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000315 }
316
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000317 fn create_vm_internal(
318 &self,
319 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900320 console_out_fd: Option<&ParcelFileDescriptor>,
321 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000322 log_fd: Option<&ParcelFileDescriptor>,
323 is_protected: &mut bool,
324 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000325 let requester_uid = get_calling_uid();
326 let requester_debug_pid = get_calling_pid();
327
328 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
329 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900330
Alan Stokes7bc146c2022-10-20 17:10:32 +0100331 let is_custom = match config {
332 VirtualMachineConfig::RawConfig(_) => true,
333 VirtualMachineConfig::AppConfig(config) => {
334 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100335 // VirtualMachineAppConfig. Almost all of these features are grouped in the
336 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100337 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100338 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100339 // - gdbPort is set, meaning that crosvm will start a gdb server;
340 // - using anything other than the default kernel.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100341 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900342 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100343 };
344 if is_custom {
345 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900346 }
347
Nikita Ioffe5776f082023-02-10 21:38:26 +0000348 let gdb_port = extract_gdb_port(config);
349
350 // Additional permission checks if caller request gdb.
351 if gdb_port.is_some() {
352 check_gdb_allowed(config)?;
353 }
354
Jaewan Kim61f86142023-03-28 15:12:52 +0900355 let debug_level = match config {
356 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
357 _ => DebugLevel::NONE,
358 };
359 let debug_config = DebugConfig::new(debug_level);
360
361 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900362 Some(prepare_ramdump_file(&temporary_directory)?)
363 } else {
364 None
365 };
366
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000367 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900368 let console_out_fd =
369 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
370 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900371 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000372
373 // Counter to generate unique IDs for temporary image files.
374 let mut next_temporary_image_id = 0;
375 // Files which are referred to from composite images. These must be mapped to the crosvm
376 // child process, and not closed before it is started.
377 let mut indirect_files = vec![];
378
Alan Stokes7bc146c2022-10-20 17:10:32 +0100379 let (is_app_config, config) = match config {
380 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
381 VirtualMachineConfig::AppConfig(config) => {
Jaewan Kim61f86142023-03-28 15:12:52 +0900382 let config =
383 load_app_config(config, &debug_config, &temporary_directory).map_err(|e| {
384 *is_protected = config.protectedVm;
385 let message = format!("Failed to load app config: {:?}", e);
386 error!("{}", message);
387 Status::new_service_specific_error_str(-1, Some(message))
388 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100389 (true, BorrowedOrOwned::Owned(config))
390 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000391 };
392 let config = config.as_ref();
393 *is_protected = config.protectedVm;
394
395 // Check if partition images are labeled incorrectly. This is to prevent random images
396 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100397 // being loaded in a pVM. This applies to everything in the raw config, and everything but
398 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000399 config
400 .disks
401 .iter()
402 .flat_map(|disk| disk.partitions.iter())
403 .filter(|partition| {
404 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100405 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000406 } else {
407 true // all partitions are checked
408 }
409 })
410 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100411 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000412
Alan Stokes185fe112023-01-10 16:20:55 +0000413 let kernel = maybe_clone_file(&config.kernel)?;
414 let initrd = maybe_clone_file(&config.initrd)?;
415
416 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
417 if config.protectedVm {
418 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
419 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
420 })?;
421 }
422
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000423 let zero_filler_path = temporary_directory.join("zero.img");
424 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100425 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000426 Status::new_service_specific_error_str(
427 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100428 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000429 )
430 })?;
431
432 // Assemble disk images if needed.
433 let disks = config
434 .disks
435 .iter()
436 .map(|disk| {
437 assemble_disk_image(
438 disk,
439 &zero_filler_path,
440 &temporary_directory,
441 &mut next_temporary_image_id,
442 &mut indirect_files,
443 )
444 })
445 .collect::<Result<Vec<DiskFile>, _>>()?;
446
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000447 let (cpus, host_cpu_topology) = match config.cpuTopology {
448 CpuTopology::MATCH_HOST => (None, true),
449 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
450 val => {
451 error!("Unexpected value of CPU topology: {:?}", val);
452 return Err(Status::new_service_specific_error_str(
453 -1,
454 Some(format!("Failed to parse CPU topology value: {:?}", val)),
455 ));
456 }
457 };
458
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000459 // Actually start the VM.
460 let crosvm_config = CrosvmConfig {
461 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000462 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000463 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000464 kernel,
465 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000466 disks,
467 params: config.params.to_owned(),
468 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900469 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000470 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000471 cpus,
472 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900473 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900474 console_out_fd,
475 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000476 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900477 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000478 indirect_files,
479 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900480 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000481 gdb_port,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000482 };
483 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100484 VmInstance::new(
485 crosvm_config,
486 temporary_directory,
487 requester_uid,
488 requester_debug_pid,
489 vm_context,
490 )
491 .map_err(|e| {
492 error!("Failed to create VM with config {:?}: {:?}", config, e);
493 Status::new_service_specific_error_str(
494 -1,
495 Some(format!("Failed to create VM: {:?}", e)),
496 )
497 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000498 );
499 state.add_vm(Arc::downgrade(&instance));
500 Ok(VirtualMachine::create(instance))
501 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900502}
503
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000504fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900505 let file = OpenOptions::new()
506 .create_new(true)
507 .read(true)
508 .write(true)
509 .open(zero_filler_path)
510 .with_context(|| "Failed to create zero.img")?;
511 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000512 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900513}
514
David Brazdilf50c7a62023-04-19 14:22:42 +0000515fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
516 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
517 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
518 part.flush()
519}
520
521fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
522 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
523 part.flush()
524}
525
526fn round_up(input: u64, granularity: u64) -> u64 {
527 if granularity == 0 {
528 return input;
529 }
530 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
531 let result = input.checked_add(granularity - 1).unwrap_or(input);
532 (result / granularity) * granularity
533}
534
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000535/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
536///
537/// This may involve assembling a composite disk from a set of partition images.
538fn assemble_disk_image(
539 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900540 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000541 temporary_directory: &Path,
542 next_temporary_image_id: &mut u64,
543 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000544) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000545 let image = if !disk.partitions.is_empty() {
546 if disk.image.is_some() {
547 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000548 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000549 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000550 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000551 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000552 }
553
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000554 let composite_image_filenames =
555 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
556 let (image, partition_files) = make_composite_image(
557 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900558 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000559 &composite_image_filenames.composite,
560 &composite_image_filenames.header,
561 &composite_image_filenames.footer,
562 )
563 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100564 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000565 Status::new_service_specific_error_str(
566 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100567 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000568 )
569 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000570
571 // Pass the file descriptors for the various partition files to crosvm when it
572 // is run.
573 indirect_files.extend(partition_files);
574
575 image
576 } else if let Some(image) = &disk.image {
577 clone_file(image)?
578 } else {
579 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000580 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000581 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000582 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000583 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000584 };
585
586 Ok(DiskFile { image, writable: disk.writable })
587}
588
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100589fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
590 if let Some(ref mut params) = vm_config.params {
591 params.push(' ');
592 params.push_str(param)
593 } else {
594 vm_config.params = Some(param.to_owned())
595 }
596}
597
Jooyung Han21e9b922021-06-26 04:14:16 +0900598fn load_app_config(
599 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900600 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900601 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900602) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000603 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
604 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900605 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900606
Shikha Panwar22e70452022-10-10 18:32:55 +0000607 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
608 Some(clone_file(file)?)
609 } else {
610 None
611 };
612
Alan Stokes0d1ef782022-09-27 13:46:35 +0100613 let vm_payload_config = match &config.payload {
614 Payload::ConfigPath(config_path) => {
615 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
616 .with_context(|| format!("Couldn't read config from {}", config_path))?
617 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000618 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100619 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900620
Alan Stokes0d1ef782022-09-27 13:46:35 +0100621 // For now, the only supported OS is Microdroid
622 let os_name = vm_payload_config.os.name.as_str();
623 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000624 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900625 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000626
627 // It is safe to construct a filename based on the os_name because we've already checked that it
628 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900629 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
630 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000631 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900632
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100633 if let Some(custom_config) = &config.customConfig {
634 if let Some(file) = custom_config.customKernelImage.as_ref() {
635 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
636 }
637 vm_config.taskProfiles = custom_config.taskProfiles.clone();
638 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100639
640 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100641 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
642 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100643 }
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100644 }
645
Andrew Walbrancc045902021-07-27 16:06:17 +0000646 if config.memoryMib > 0 {
647 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000648 }
649
Seungjae Yoo62085c02022-08-12 04:44:52 +0000650 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000651 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000652 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900653
Shikha Panwar22e70452022-10-10 18:32:55 +0000654 // Microdroid takes additional init ramdisk & (optionally) storage image
655 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
656
657 // Include Microdroid payload disk (contains apks, idsigs) in vm config
658 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100659 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900660 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100661 temporary_directory,
662 apk_file,
663 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100664 &vm_payload_config,
665 &mut vm_config,
666 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900667
Andrew Walbrancc0db522021-07-12 17:03:42 +0000668 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900669}
670
Alan Stokes0d1ef782022-09-27 13:46:35 +0100671fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
672 let mut apk_zip = ZipArchive::new(apk_file)?;
673 let config_file = apk_zip.by_name(config_path)?;
674 Ok(serde_json::from_reader(config_file)?)
675}
676
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000677fn create_vm_payload_config(
678 payload_config: &VirtualMachinePayloadConfig,
679) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100680 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
681 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
682 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000683
684 let payload_binary_name = &payload_config.payloadBinaryName;
685 if payload_binary_name.contains('/') {
686 bail!("Payload binary name must not specify a path: {payload_binary_name}");
687 }
688
689 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
690 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100691 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
692 task: Some(task),
693 apexes: vec![],
694 extra_apks: vec![],
695 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900696 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100697 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000698 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100699}
700
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000701/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000702fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000703 temporary_directory: &Path,
704 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000705) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000706 let id = *next_temporary_image_id;
707 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000708 CompositeImageFilenames {
709 composite: temporary_directory.join(format!("composite-{}.img", id)),
710 header: temporary_directory.join(format!("composite-{}-header.img", id)),
711 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
712 }
713}
714
715/// Filenames for a composite disk image, including header and footer partitions.
716#[derive(Clone, Debug, Eq, PartialEq)]
717struct CompositeImageFilenames {
718 /// The composite disk image itself.
719 composite: PathBuf,
720 /// The header partition image.
721 header: PathBuf,
722 /// The footer partition image.
723 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000724}
725
Jiyong Park753553b2021-07-12 21:21:09 +0900726/// Checks whether the caller has a specific permission
727fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100728 let calling_pid = get_calling_pid();
729 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900730 // Root can do anything
731 if calling_uid == 0 {
732 return Ok(());
733 }
734 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
735 binder::get_interface("permission")?;
736 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000737 Ok(())
738 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000739 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900740 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000741 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900742 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000743 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000744}
745
Jiyong Park753553b2021-07-12 21:21:09 +0900746/// Check whether the caller of the current Binder method is allowed to manage VMs
747fn check_manage_access() -> binder::Result<()> {
748 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
749}
750
Inseob Kim1119d702022-05-02 18:01:58 +0900751/// Check whether the caller of the current Binder method is allowed to create custom VMs
752fn check_use_custom_virtual_machine() -> binder::Result<()> {
753 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
754}
755
Alan Stokes185fe112023-01-10 16:20:55 +0000756/// Return whether a partition is exempt from selinux label checks, because we know that it does
757/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100758fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000759 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100760 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000761 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100762 || label == "microdroid-apk-idsig"
763 || label == "payload-metadata"
764 || label.starts_with("extra-idsig-")
765}
766
Alan Stokes185fe112023-01-10 16:20:55 +0000767/// Check that a file SELinux label is acceptable.
768///
769/// We only want to allow code in a VM to be sourced from places that apps, and the
770/// system, do not have write access to.
771///
772/// Note that sepolicy must also grant read access for these types to both virtualization
773/// service and crosvm.
774///
775/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
776/// user devices (W^X).
777fn check_label_is_allowed(context: &SeContext) -> Result<()> {
778 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100779 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100780 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000781 | "staging_data_file" // updated/staged APEX images
782 | "system_file" // immutable dm-verity protected partition
783 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100784 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000785 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900786 }
787}
788
Alan Stokes185fe112023-01-10 16:20:55 +0000789fn check_label_for_partition(partition: &Partition) -> Result<()> {
790 let file = partition.image.as_ref().unwrap().as_ref();
791 check_label_is_allowed(&getfilecon(file)?)
792 .with_context(|| format!("Partition {} invalid", &partition.label))
793}
794
795fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
796 if let Some(f) = kernel {
797 check_label_for_file(f, "kernel")?;
798 }
799 if let Some(f) = initrd {
800 check_label_for_file(f, "initrd")?;
801 }
802 Ok(())
803}
804fn check_label_for_file(file: &File, name: &str) -> Result<()> {
805 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
806}
807
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000808/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
809#[derive(Debug)]
810struct VirtualMachine {
811 instance: Arc<VmInstance>,
812}
813
814impl VirtualMachine {
815 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000816 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000817 }
818}
819
820impl Interface for VirtualMachine {}
821
822impl IVirtualMachine for VirtualMachine {
823 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900824 // Don't check permission. The owner of the VM might have passed this binder object to
825 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000826 Ok(self.instance.cid as i32)
827 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000828
Andrew Walbran6b650662021-09-07 13:13:23 +0000829 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900830 // Don't check permission. The owner of the VM might have passed this binder object to
831 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000832 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000833 }
834
835 fn registerCallback(
836 &self,
837 callback: &Strong<dyn IVirtualMachineCallback>,
838 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900839 // Don't check permission. The owner of the VM might have passed this binder object to
840 // others.
841 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000842 // TODO: Should this give an error if the VM is already dead?
843 self.instance.callbacks.add(callback.clone());
844 Ok(())
845 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000846
Andrew Walbranf8d94112021-09-07 11:45:36 +0000847 fn start(&self) -> binder::Result<()> {
848 self.instance.start().map_err(|e| {
849 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000850 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000851 })
852 }
853
Inseob Kima446f802022-07-11 19:46:37 +0900854 fn stop(&self) -> binder::Result<()> {
855 self.instance.kill().map_err(|e| {
856 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000857 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Inseob Kima446f802022-07-11 19:46:37 +0900858 })
859 }
860
Keir Frasercdd4b112022-11-24 14:02:25 +0000861 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
862 self.instance.trim_memory(level).map_err(|e| {
863 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
864 Status::new_service_specific_error_str(-1, Some(e.to_string()))
865 })
866 }
867
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000868 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000869 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000870 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000871 }
Alan Stokes10c47672022-12-13 17:17:08 +0000872 let port = port as u32;
873 if port < 1024 {
874 return Err(Status::new_service_specific_error_str(
875 -1,
876 Some(format!("Can't connect to privileged port {port}")),
877 ));
878 }
879 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
880 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
881 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000882 Ok(vsock_stream_to_pfd(stream))
883 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000884}
885
886impl Drop for VirtualMachine {
887 fn drop(&mut self) {
888 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900889 if let Err(e) = self.instance.kill() {
890 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
891 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000892 }
893}
894
895/// A set of Binders to be called back in response to various events on the VM, such as when it
896/// dies.
897#[derive(Debug, Default)]
898pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
899
900impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900901 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100902 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900903 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900904 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100905 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100906 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900907 }
908 }
909 }
910
Inseob Kim14cb8692021-08-31 21:50:39 +0900911 /// Call all registered callbacks to notify that the payload is ready to serve.
912 pub fn notify_payload_ready(&self, cid: Cid) {
913 let callbacks = &*self.0.lock().unwrap();
914 for callback in callbacks {
915 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100916 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900917 }
918 }
919 }
920
Inseob Kim2444af92021-08-31 01:22:50 +0900921 /// Call all registered callbacks to notify that the payload has finished.
922 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
923 let callbacks = &*self.0.lock().unwrap();
924 for callback in callbacks {
925 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100926 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900927 }
928 }
929 }
930
Jooyung Handd0a1732021-11-23 15:26:20 +0900931 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100932 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900933 let callbacks = &*self.0.lock().unwrap();
934 for callback in callbacks {
935 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100936 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900937 }
938 }
939 }
940
Andrew Walbrandae07162021-03-12 17:05:20 +0000941 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000942 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000943 let callbacks = &*self.0.lock().unwrap();
944 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000945 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100946 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000947 }
948 }
949 }
950
951 /// Add a new callback to the set.
952 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
953 self.0.lock().unwrap().push(callback);
954 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000955}
956
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000957/// The mutable state of the VirtualizationService. There should only be one instance of this
958/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800959#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000960struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000961 /// The VMs which have been started. When VMs are started a weak reference is added to this list
962 /// while a strong reference is returned to the caller over Binder. Once all copies of the
963 /// Binder client are dropped the weak reference here will become invalid, and will be removed
964 /// from the list opportunistically the next time `add_vm` is called.
965 vms: Vec<Weak<VmInstance>>,
966}
967
968impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000969 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000970 fn vms(&self) -> Vec<Arc<VmInstance>> {
971 // Attempt to upgrade the weak pointers to strong pointers.
972 self.vms.iter().filter_map(Weak::upgrade).collect()
973 }
974
975 /// Add a new VM to the list.
976 fn add_vm(&mut self, vm: Weak<VmInstance>) {
977 // Garbage collect any entries from the stored list which no longer exist.
978 self.vms.retain(|vm| vm.strong_count() > 0);
979
980 // Actually add the new VM.
981 self.vms.push(vm);
982 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000983
Jiyong Park8611a6c2021-07-09 18:17:44 +0900984 /// Get a VM that corresponds to the given cid
985 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
986 self.vms().into_iter().find(|vm| vm.cid == cid)
987 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900988}
989
Andrew Walbran6b650662021-09-07 13:13:23 +0000990/// Gets the `VirtualMachineState` of the given `VmInstance`.
991fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000992 match &*instance.vm_state.lock().unwrap() {
993 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
994 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000995 PayloadState::Starting => VirtualMachineState::STARTING,
996 PayloadState::Started => VirtualMachineState::STARTED,
997 PayloadState::Ready => VirtualMachineState::READY,
998 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900999 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001000 },
1001 VmState::Dead => VirtualMachineState::DEAD,
1002 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001003 }
1004}
1005
David Brazdilf50c7a62023-04-19 14:22:42 +00001006/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
1007pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
1008 file.as_ref().try_clone().map_err(|e| {
1009 Status::new_exception_str(
1010 ExceptionCode::BAD_PARCELABLE,
1011 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
1012 )
1013 })
1014}
1015
Andrew Walbrand3a84182021-09-07 14:48:52 +00001016/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1017fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1018 file.as_ref().map(clone_file).transpose()
1019}
1020
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001021/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1022fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1023 // SAFETY: ownership is transferred from stream to f
1024 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1025 ParcelFileDescriptor::new(f)
1026}
1027
Jiyong Parkdcf17412022-02-08 15:07:23 +09001028/// Parses the platform version requirement string.
1029fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1030 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001031 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001032 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001033 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001034 )
1035 })
1036}
1037
Jiyong Parked180932023-02-24 19:55:41 +09001038/// Create the empty ramdump file
1039fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1040 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1041 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1042 // owner) for readout.
1043 let ramdump_path = temporary_directory.join("ramdump");
1044 let ramdump = File::create(ramdump_path).map_err(|e| {
1045 error!("Failed to prepare ramdump file: {:?}", e);
1046 Status::new_service_specific_error_str(
1047 -1,
1048 Some(format!("Failed to prepare ramdump file: {:?}", e)),
1049 )
1050 })?;
1051 Ok(ramdump)
1052}
1053
Nikita Ioffe5776f082023-02-10 21:38:26 +00001054fn is_protected(config: &VirtualMachineConfig) -> bool {
1055 match config {
1056 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1057 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1058 }
1059}
1060
1061fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1062 if is_protected(config) {
1063 return Err(Status::new_exception_str(
1064 ExceptionCode::SECURITY,
1065 Some("can't use gdb with protected VMs"),
1066 ));
1067 }
1068
1069 match config {
1070 VirtualMachineConfig::RawConfig(_) => Ok(()),
1071 VirtualMachineConfig::AppConfig(config) => {
1072 if config.debugLevel != DebugLevel::FULL {
1073 Err(Status::new_exception_str(
1074 ExceptionCode::SECURITY,
1075 Some("can't use gdb with non-debuggable VMs"),
1076 ))
1077 } else {
1078 Ok(())
1079 }
1080 }
1081 }
1082}
1083
1084fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1085 match config {
1086 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001087 VirtualMachineConfig::AppConfig(config) => {
1088 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1089 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001090 }
1091}
1092
Inseob Kim0168b462022-12-27 14:54:35 +09001093fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001094 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001095 fd: Option<&ParcelFileDescriptor>,
1096 tag: String,
1097) -> Result<Option<File>, Status> {
1098 if let Some(fd) = fd {
1099 return Ok(Some(clone_file(fd)?));
1100 }
1101
Jaewan Kim61f86142023-03-28 15:12:52 +09001102 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001103 return Ok(None);
1104 };
Inseob Kim0168b462022-12-27 14:54:35 +09001105
1106 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
1107 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
1108 })?;
1109
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001110 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Inseob Kim0168b462022-12-27 14:54:35 +09001111 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001112 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Inseob Kim0168b462022-12-27 14:54:35 +09001113 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1114
1115 std::thread::spawn(move || loop {
1116 let mut buf = vec![];
1117 match reader.read_until(b'\n', &mut buf) {
1118 Ok(0) => {
1119 // EOF
1120 return;
1121 }
1122 Ok(size) => {
1123 if buf[size - 1] == b'\n' {
1124 buf.pop();
1125 }
1126 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1127 }
1128 Err(e) => {
1129 error!("Could not read console pipe: {:?}", e);
1130 return;
1131 }
1132 };
1133 });
1134
1135 Ok(Some(write_fd))
1136}
1137
Jooyung Han35edb8f2021-07-01 16:17:16 +09001138/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1139/// it doesn't require that T implements Clone.
1140enum BorrowedOrOwned<'a, T> {
1141 Borrowed(&'a T),
1142 Owned(T),
1143}
1144
1145impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1146 fn as_ref(&self) -> &T {
1147 match self {
1148 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001149 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001150 }
1151 }
1152}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001153
1154/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1155#[derive(Debug, Default)]
1156struct VirtualMachineService {
1157 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001158 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001159}
1160
1161impl Interface for VirtualMachineService {}
1162
1163impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001164 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1165 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001166 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001167 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001168 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1169 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1170 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001171 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001172
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001173 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1174 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001175 Ok(())
1176 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001177 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001178 Err(Status::new_service_specific_error_str(
1179 -1,
1180 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001181 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001182 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001183 }
Inseob Kim2444af92021-08-31 01:22:50 +09001184
Inseob Kimc7d28c72021-10-25 14:28:10 +00001185 fn notifyPayloadReady(&self) -> binder::Result<()> {
1186 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001187 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001188 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001189 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1190 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1191 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001192 vm.callbacks.notify_payload_ready(cid);
1193 Ok(())
1194 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001195 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001196 Err(Status::new_service_specific_error_str(
1197 -1,
1198 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001199 ))
1200 }
1201 }
1202
Inseob Kimc7d28c72021-10-25 14:28:10 +00001203 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1204 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001205 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001206 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001207 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1208 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1209 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001210 vm.callbacks.notify_payload_finished(cid, exit_code);
1211 Ok(())
1212 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001213 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001214 Err(Status::new_service_specific_error_str(
1215 -1,
1216 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001217 ))
1218 }
1219 }
1220
Alan Stokes2bead0d2022-09-05 16:58:34 +01001221 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001222 let cid = self.cid;
1223 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001224 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001225 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1226 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1227 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001228 vm.callbacks.notify_error(cid, error_code, message);
1229 Ok(())
1230 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001231 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001232 Err(Status::new_service_specific_error_str(
1233 -1,
1234 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001235 ))
1236 }
1237 }
Alice Wangc2fec932023-02-23 16:24:02 +00001238
1239 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
1240 let cid = self.cid;
1241 let Some(vm) = self.state.lock().unwrap().get_vm(cid) else {
1242 error!("requestCertificate is called from an unknown CID {cid}");
1243 return Err(Status::new_service_specific_error_str(
1244 -1,
1245 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim53d0b212023-07-20 16:58:37 +09001246 ));
Alice Wangc2fec932023-02-23 16:24:02 +00001247 };
1248 let instance_img_path = vm.temporary_directory.join("rkpvm_instance.img");
1249 let instance_img = OpenOptions::new()
1250 .create(true)
1251 .read(true)
1252 .write(true)
1253 .open(instance_img_path)
1254 .map_err(|e| {
1255 error!("Failed to create rkpvm_instance.img file: {:?}", e);
1256 Status::new_service_specific_error_str(
1257 -1,
1258 Some(format!("Failed to create rkpvm_instance.img file: {:?}", e)),
1259 )
1260 })?;
1261 GLOBAL_SERVICE.requestCertificate(csr, &ParcelFileDescriptor::new(instance_img))
1262 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001263}
1264
1265impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001266 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001267 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001268 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001269 BinderFeatures::default(),
1270 )
1271 }
1272}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001273
1274#[cfg(test)]
1275mod tests {
1276 use super::*;
1277
1278 #[test]
1279 fn test_is_allowed_label_for_partition() -> Result<()> {
1280 let expected_results = vec![
1281 ("u:object_r:system_file:s0", true),
1282 ("u:object_r:apk_data_file:s0", true),
1283 ("u:object_r:app_data_file:s0", false),
1284 ("u:object_r:app_data_file:s0:c512,c768", false),
1285 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1286 ("invalid", false),
1287 ("user:role:apk_data_file:severity:categories", true),
1288 ("user:role:apk_data_file:severity:categories:extraneous", false),
1289 ];
1290
1291 for (label, expected_valid) in expected_results {
1292 let context = SeContext::new(label)?;
1293 let result = check_label_is_allowed(&context);
1294 if expected_valid {
1295 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1296 } else if result.is_ok() {
1297 bail!("Expected label {} to be disallowed", label);
1298 }
1299 }
1300 Ok(())
1301 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001302
1303 #[test]
1304 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1305 let apk = tempfile::tempfile().unwrap();
1306 let idsig = tempfile::tempfile().unwrap();
1307
1308 let ret = create_or_update_idsig_file(
1309 &ParcelFileDescriptor::new(apk),
1310 &ParcelFileDescriptor::new(idsig),
1311 );
1312 assert!(ret.is_err(), "should fail");
1313 Ok(())
1314 }
1315
1316 #[test]
1317 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1318 let tmp_dir = tempfile::TempDir::new().unwrap();
1319 let apk = File::open(tmp_dir.path()).unwrap();
1320 let idsig = tempfile::tempfile().unwrap();
1321
1322 let ret = create_or_update_idsig_file(
1323 &ParcelFileDescriptor::new(apk),
1324 &ParcelFileDescriptor::new(idsig),
1325 );
1326 assert!(ret.is_err(), "should fail");
1327 Ok(())
1328 }
1329
1330 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1331 /// on ext4 filesystem is passed.
1332 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1333 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1334 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1335 #[test]
1336 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1337 // APEXes are backed by the ext4.
1338 let apk = File::open("/apex/com.android.virt/").unwrap();
1339 let idsig = tempfile::tempfile().unwrap();
1340
1341 let ret = create_or_update_idsig_file(
1342 &ParcelFileDescriptor::new(apk),
1343 &ParcelFileDescriptor::new(idsig),
1344 );
1345 assert!(ret.is_err(), "should fail");
1346 Ok(())
1347 }
Jiyong Park8d192952023-06-26 14:29:51 +09001348
1349 #[test]
1350 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1351 use std::io::Seek;
1352
1353 // Pick any APK
1354 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1355 let mut idsig = tempfile::tempfile().unwrap();
1356
1357 create_or_update_idsig_file(
1358 &ParcelFileDescriptor::new(apk.try_clone()?),
1359 &ParcelFileDescriptor::new(idsig.try_clone()?),
1360 )?;
1361 let modified_orig = idsig.metadata()?.modified()?;
1362 apk.rewind()?;
1363 idsig.rewind()?;
1364
1365 // Call the function again
1366 create_or_update_idsig_file(
1367 &ParcelFileDescriptor::new(apk.try_clone()?),
1368 &ParcelFileDescriptor::new(idsig.try_clone()?),
1369 )?;
1370 let modified_new = idsig.metadata()?.modified()?;
1371 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1372 Ok(())
1373 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001374
1375 #[test]
1376 fn test_append_kernel_param_first_param() {
1377 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1378 append_kernel_param("foo=1", &mut vm_config);
1379 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1380 }
1381
1382 #[test]
1383 fn test_append_kernel_param() {
1384 let mut vm_config =
1385 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1386 append_kernel_param("bar=42", &mut vm_config);
1387 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1388 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001389}