blob: d0a8e85e9243ed1e08b8c1de2dca9ff6d68a2e3f [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::{
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 Parke6fb1672023-06-26 16:45:55 +0900189 console_out_fd: Option<&ParcelFileDescriptor>,
190 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000191 log_fd: Option<&ParcelFileDescriptor>,
192 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000193 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900194 let ret = self.create_vm_internal(
195 config,
196 console_out_fd,
197 console_in_fd,
198 log_fd,
199 &mut is_protected,
200 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000201 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000202 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000203 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000204
Andrew Walbrandff3b942021-06-09 15:20:36 +0000205 /// Initialise an empty partition image of the given size to be used as a writable partition.
206 fn initializeWritablePartition(
207 &self,
208 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000209 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900210 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000211 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900212 check_manage_access()?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000213 let size_bytes = size_bytes.try_into().map_err(|e| {
214 Status::new_exception_str(
215 ExceptionCode::ILLEGAL_ARGUMENT,
216 Some(format!("Invalid size {}: {:?}", size_bytes, e)),
217 )
218 })?;
219 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
220 let image = clone_file(image_fd)?;
221 // initialize the file. Any data in the file will be erased.
222 image.set_len(0).map_err(|e| {
223 Status::new_service_specific_error_str(
224 -1,
225 Some(format!("Failed to reset a file: {:?}", e)),
226 )
227 })?;
228 let mut part = QcowFile::new(image, size_bytes).map_err(|e| {
229 Status::new_service_specific_error_str(
230 -1,
231 Some(format!("Failed to create QCOW2 image: {:?}", e)),
232 )
233 })?;
234
235 match partition_type {
236 PartitionType::RAW => Ok(()),
237 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
238 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
239 _ => Err(Error::new(
240 ErrorKind::Unsupported,
241 format!("Unsupported partition type {:?}", partition_type),
242 )),
243 }
244 .map_err(|e| {
245 Status::new_service_specific_error_str(
246 -1,
247 Some(format!("Failed to initialize partition as {:?}: {:?}", partition_type, e)),
248 )
249 })?;
250
251 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000252 }
253
Jiyong Park0a248432021-08-20 23:32:39 +0900254 /// Creates or update the idsig file by digesting the input APK file.
255 fn createOrUpdateIdsigFile(
256 &self,
257 input_fd: &ParcelFileDescriptor,
258 idsig_fd: &ParcelFileDescriptor,
259 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900260 check_manage_access()?;
261
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000262 create_or_update_idsig_file(input_fd, idsig_fd)
263 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Jiyong Park0a248432021-08-20 23:32:39 +0900264 Ok(())
265 }
266
Andrew Walbran320b5602021-03-04 16:11:12 +0000267 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
268 /// and as such is only permitted from the shell user.
269 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000270 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000271 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000272 }
273}
274
Jiyong Park8611a6c2021-07-09 18:17:44 +0900275impl VirtualizationService {
276 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000277 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900278 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000279
David Brazdil209074a2023-01-12 16:44:51 +0000280 fn create_vm_context(
281 &self,
282 requester_debug_pid: pid_t,
283 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000284 const NUM_ATTEMPTS: usize = 5;
285
286 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000287 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000288 let cid = vm_context.getCid()? as Cid;
289 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000290 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
291
292 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000293 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000294 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000295 Ok(vm_server) => {
296 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000297 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000298 }
299 Err(err) => {
300 warn!("Could not start RpcServer on port {}: {}", port, err);
301 }
302 }
303 }
David Brazdil209074a2023-01-12 16:44:51 +0000304 Err(Status::new_service_specific_error_str(
305 -1,
306 Some("Too many attempts to create VM context failed."),
307 ))
David Brazdil8cf8f482022-11-23 14:21:26 +0000308 }
309
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000310 fn create_vm_internal(
311 &self,
312 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900313 console_out_fd: Option<&ParcelFileDescriptor>,
314 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000315 log_fd: Option<&ParcelFileDescriptor>,
316 is_protected: &mut bool,
317 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000318 let requester_uid = get_calling_uid();
319 let requester_debug_pid = get_calling_pid();
320
321 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
322 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900323
Alan Stokes7bc146c2022-10-20 17:10:32 +0100324 let is_custom = match config {
325 VirtualMachineConfig::RawConfig(_) => true,
326 VirtualMachineConfig::AppConfig(config) => {
327 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100328 // VirtualMachineAppConfig. Almost all of these features are grouped in the
329 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100330 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100331 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100332 // - gdbPort is set, meaning that crosvm will start a gdb server;
333 // - using anything other than the default kernel.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100334 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900335 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100336 };
337 if is_custom {
338 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900339 }
340
Nikita Ioffe5776f082023-02-10 21:38:26 +0000341 let gdb_port = extract_gdb_port(config);
342
343 // Additional permission checks if caller request gdb.
344 if gdb_port.is_some() {
345 check_gdb_allowed(config)?;
346 }
347
Jaewan Kim61f86142023-03-28 15:12:52 +0900348 let debug_level = match config {
349 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
350 _ => DebugLevel::NONE,
351 };
352 let debug_config = DebugConfig::new(debug_level);
353
354 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900355 Some(prepare_ramdump_file(&temporary_directory)?)
356 } else {
357 None
358 };
359
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000360 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900361 let console_out_fd =
362 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
363 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900364 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000365
366 // Counter to generate unique IDs for temporary image files.
367 let mut next_temporary_image_id = 0;
368 // Files which are referred to from composite images. These must be mapped to the crosvm
369 // child process, and not closed before it is started.
370 let mut indirect_files = vec![];
371
Alan Stokes7bc146c2022-10-20 17:10:32 +0100372 let (is_app_config, config) = match config {
373 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
374 VirtualMachineConfig::AppConfig(config) => {
Jaewan Kim61f86142023-03-28 15:12:52 +0900375 let config =
376 load_app_config(config, &debug_config, &temporary_directory).map_err(|e| {
377 *is_protected = config.protectedVm;
378 let message = format!("Failed to load app config: {:?}", e);
379 error!("{}", message);
380 Status::new_service_specific_error_str(-1, Some(message))
381 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100382 (true, BorrowedOrOwned::Owned(config))
383 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000384 };
385 let config = config.as_ref();
386 *is_protected = config.protectedVm;
387
388 // Check if partition images are labeled incorrectly. This is to prevent random images
389 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100390 // being loaded in a pVM. This applies to everything in the raw config, and everything but
391 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000392 config
393 .disks
394 .iter()
395 .flat_map(|disk| disk.partitions.iter())
396 .filter(|partition| {
397 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100398 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000399 } else {
400 true // all partitions are checked
401 }
402 })
403 .try_for_each(check_label_for_partition)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100404 .map_err(|e| Status::new_service_specific_error_str(-1, Some(format!("{:?}", e))))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000405
Alan Stokes185fe112023-01-10 16:20:55 +0000406 let kernel = maybe_clone_file(&config.kernel)?;
407 let initrd = maybe_clone_file(&config.initrd)?;
408
409 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
410 if config.protectedVm {
411 check_label_for_kernel_files(&kernel, &initrd).map_err(|e| {
412 Status::new_service_specific_error_str(-1, Some(format!("{:?}", e)))
413 })?;
414 }
415
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000416 let zero_filler_path = temporary_directory.join("zero.img");
417 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100418 error!("Failed to make composite image: {:?}", e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000419 Status::new_service_specific_error_str(
420 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100421 Some(format!("Failed to make composite image: {:?}", e)),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000422 )
423 })?;
424
425 // Assemble disk images if needed.
426 let disks = config
427 .disks
428 .iter()
429 .map(|disk| {
430 assemble_disk_image(
431 disk,
432 &zero_filler_path,
433 &temporary_directory,
434 &mut next_temporary_image_id,
435 &mut indirect_files,
436 )
437 })
438 .collect::<Result<Vec<DiskFile>, _>>()?;
439
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000440 let (cpus, host_cpu_topology) = match config.cpuTopology {
441 CpuTopology::MATCH_HOST => (None, true),
442 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
443 val => {
444 error!("Unexpected value of CPU topology: {:?}", val);
445 return Err(Status::new_service_specific_error_str(
446 -1,
447 Some(format!("Failed to parse CPU topology value: {:?}", val)),
448 ));
449 }
450 };
451
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000452 // Actually start the VM.
453 let crosvm_config = CrosvmConfig {
454 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000455 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000456 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000457 kernel,
458 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000459 disks,
460 params: config.params.to_owned(),
461 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900462 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000463 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000464 cpus,
465 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900466 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900467 console_out_fd,
468 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000469 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900470 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000471 indirect_files,
472 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900473 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000474 gdb_port,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000475 };
476 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100477 VmInstance::new(
478 crosvm_config,
479 temporary_directory,
480 requester_uid,
481 requester_debug_pid,
482 vm_context,
483 )
484 .map_err(|e| {
485 error!("Failed to create VM with config {:?}: {:?}", config, e);
486 Status::new_service_specific_error_str(
487 -1,
488 Some(format!("Failed to create VM: {:?}", e)),
489 )
490 })?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000491 );
492 state.add_vm(Arc::downgrade(&instance));
493 Ok(VirtualMachine::create(instance))
494 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900495}
496
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000497fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900498 let file = OpenOptions::new()
499 .create_new(true)
500 .read(true)
501 .write(true)
502 .open(zero_filler_path)
503 .with_context(|| "Failed to create zero.img")?;
504 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000505 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900506}
507
David Brazdilf50c7a62023-04-19 14:22:42 +0000508fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
509 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
510 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
511 part.flush()
512}
513
514fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
515 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
516 part.flush()
517}
518
519fn round_up(input: u64, granularity: u64) -> u64 {
520 if granularity == 0 {
521 return input;
522 }
523 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
524 let result = input.checked_add(granularity - 1).unwrap_or(input);
525 (result / granularity) * granularity
526}
527
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000528/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
529///
530/// This may involve assembling a composite disk from a set of partition images.
531fn assemble_disk_image(
532 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900533 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000534 temporary_directory: &Path,
535 next_temporary_image_id: &mut u64,
536 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000537) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000538 let image = if !disk.partitions.is_empty() {
539 if disk.image.is_some() {
540 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000541 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000542 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000543 Some("DiskImage contains both image and partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000544 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000545 }
546
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000547 let composite_image_filenames =
548 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
549 let (image, partition_files) = make_composite_image(
550 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900551 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000552 &composite_image_filenames.composite,
553 &composite_image_filenames.header,
554 &composite_image_filenames.footer,
555 )
556 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100557 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000558 Status::new_service_specific_error_str(
559 -1,
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100560 Some(format!("Failed to make composite image: {:?}", e)),
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000561 )
562 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000563
564 // Pass the file descriptors for the various partition files to crosvm when it
565 // is run.
566 indirect_files.extend(partition_files);
567
568 image
569 } else if let Some(image) = &disk.image {
570 clone_file(image)?
571 } else {
572 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000573 return Err(Status::new_exception_str(
Andrew Walbran806f1542021-06-10 14:07:12 +0000574 ExceptionCode::ILLEGAL_ARGUMENT,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000575 Some("DiskImage didn't contain image or partitions."),
Andrew Walbran806f1542021-06-10 14:07:12 +0000576 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000577 };
578
579 Ok(DiskFile { image, writable: disk.writable })
580}
581
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100582fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
583 if let Some(ref mut params) = vm_config.params {
584 params.push(' ');
585 params.push_str(param)
586 } else {
587 vm_config.params = Some(param.to_owned())
588 }
589}
590
Jooyung Han21e9b922021-06-26 04:14:16 +0900591fn load_app_config(
592 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900593 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900594 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900595) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000596 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
597 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900598 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900599
Shikha Panwar22e70452022-10-10 18:32:55 +0000600 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
601 Some(clone_file(file)?)
602 } else {
603 None
604 };
605
Alan Stokes0d1ef782022-09-27 13:46:35 +0100606 let vm_payload_config = match &config.payload {
607 Payload::ConfigPath(config_path) => {
608 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
609 .with_context(|| format!("Couldn't read config from {}", config_path))?
610 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000611 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100612 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900613
Alan Stokes0d1ef782022-09-27 13:46:35 +0100614 // For now, the only supported OS is Microdroid
615 let os_name = vm_payload_config.os.name.as_str();
616 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000617 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900618 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000619
620 // It is safe to construct a filename based on the os_name because we've already checked that it
621 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900622 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
623 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000624 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900625
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100626 if let Some(custom_config) = &config.customConfig {
627 if let Some(file) = custom_config.customKernelImage.as_ref() {
628 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
629 }
630 vm_config.taskProfiles = custom_config.taskProfiles.clone();
631 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100632
633 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100634 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
635 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100636 }
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100637 }
638
Andrew Walbrancc045902021-07-27 16:06:17 +0000639 if config.memoryMib > 0 {
640 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000641 }
642
Seungjae Yoo62085c02022-08-12 04:44:52 +0000643 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000644 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000645 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900646
Shikha Panwar22e70452022-10-10 18:32:55 +0000647 // Microdroid takes additional init ramdisk & (optionally) storage image
648 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
649
650 // Include Microdroid payload disk (contains apks, idsigs) in vm config
651 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100652 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900653 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100654 temporary_directory,
655 apk_file,
656 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100657 &vm_payload_config,
658 &mut vm_config,
659 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900660
Andrew Walbrancc0db522021-07-12 17:03:42 +0000661 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900662}
663
Alan Stokes0d1ef782022-09-27 13:46:35 +0100664fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
665 let mut apk_zip = ZipArchive::new(apk_file)?;
666 let config_file = apk_zip.by_name(config_path)?;
667 Ok(serde_json::from_reader(config_file)?)
668}
669
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000670fn create_vm_payload_config(
671 payload_config: &VirtualMachinePayloadConfig,
672) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100673 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
674 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
675 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000676
677 let payload_binary_name = &payload_config.payloadBinaryName;
678 if payload_binary_name.contains('/') {
679 bail!("Payload binary name must not specify a path: {payload_binary_name}");
680 }
681
682 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
683 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100684 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
685 task: Some(task),
686 apexes: vec![],
687 extra_apks: vec![],
688 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900689 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100690 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000691 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100692}
693
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000694/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000695fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000696 temporary_directory: &Path,
697 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000698) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000699 let id = *next_temporary_image_id;
700 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000701 CompositeImageFilenames {
702 composite: temporary_directory.join(format!("composite-{}.img", id)),
703 header: temporary_directory.join(format!("composite-{}-header.img", id)),
704 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
705 }
706}
707
708/// Filenames for a composite disk image, including header and footer partitions.
709#[derive(Clone, Debug, Eq, PartialEq)]
710struct CompositeImageFilenames {
711 /// The composite disk image itself.
712 composite: PathBuf,
713 /// The header partition image.
714 header: PathBuf,
715 /// The footer partition image.
716 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000717}
718
Jiyong Park753553b2021-07-12 21:21:09 +0900719/// Checks whether the caller has a specific permission
720fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100721 let calling_pid = get_calling_pid();
722 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900723 // Root can do anything
724 if calling_uid == 0 {
725 return Ok(());
726 }
727 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
728 binder::get_interface("permission")?;
729 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000730 Ok(())
731 } else {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000732 Err(Status::new_exception_str(
Jiyong Park753553b2021-07-12 21:21:09 +0900733 ExceptionCode::SECURITY,
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000734 Some(format!("does not have the {} permission", perm)),
Jiyong Park753553b2021-07-12 21:21:09 +0900735 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000736 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000737}
738
Jiyong Park753553b2021-07-12 21:21:09 +0900739/// Check whether the caller of the current Binder method is allowed to manage VMs
740fn check_manage_access() -> binder::Result<()> {
741 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
742}
743
Inseob Kim1119d702022-05-02 18:01:58 +0900744/// Check whether the caller of the current Binder method is allowed to create custom VMs
745fn check_use_custom_virtual_machine() -> binder::Result<()> {
746 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
747}
748
Alan Stokes185fe112023-01-10 16:20:55 +0000749/// Return whether a partition is exempt from selinux label checks, because we know that it does
750/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100751fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000752 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100753 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000754 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100755 || label == "microdroid-apk-idsig"
756 || label == "payload-metadata"
757 || label.starts_with("extra-idsig-")
758}
759
Alan Stokes185fe112023-01-10 16:20:55 +0000760/// Check that a file SELinux label is acceptable.
761///
762/// We only want to allow code in a VM to be sourced from places that apps, and the
763/// system, do not have write access to.
764///
765/// Note that sepolicy must also grant read access for these types to both virtualization
766/// service and crosvm.
767///
768/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
769/// user devices (W^X).
770fn check_label_is_allowed(context: &SeContext) -> Result<()> {
771 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100772 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100773 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000774 | "staging_data_file" // updated/staged APEX images
775 | "system_file" // immutable dm-verity protected partition
776 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100777 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000778 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900779 }
780}
781
Alan Stokes185fe112023-01-10 16:20:55 +0000782fn check_label_for_partition(partition: &Partition) -> Result<()> {
783 let file = partition.image.as_ref().unwrap().as_ref();
784 check_label_is_allowed(&getfilecon(file)?)
785 .with_context(|| format!("Partition {} invalid", &partition.label))
786}
787
788fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
789 if let Some(f) = kernel {
790 check_label_for_file(f, "kernel")?;
791 }
792 if let Some(f) = initrd {
793 check_label_for_file(f, "initrd")?;
794 }
795 Ok(())
796}
797fn check_label_for_file(file: &File, name: &str) -> Result<()> {
798 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
799}
800
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000801/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
802#[derive(Debug)]
803struct VirtualMachine {
804 instance: Arc<VmInstance>,
805}
806
807impl VirtualMachine {
808 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000809 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000810 }
811}
812
813impl Interface for VirtualMachine {}
814
815impl IVirtualMachine for VirtualMachine {
816 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900817 // Don't check permission. The owner of the VM might have passed this binder object to
818 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000819 Ok(self.instance.cid as i32)
820 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000821
Andrew Walbran6b650662021-09-07 13:13:23 +0000822 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900823 // Don't check permission. The owner of the VM might have passed this binder object to
824 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000825 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000826 }
827
828 fn registerCallback(
829 &self,
830 callback: &Strong<dyn IVirtualMachineCallback>,
831 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900832 // Don't check permission. The owner of the VM might have passed this binder object to
833 // others.
834 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000835 // TODO: Should this give an error if the VM is already dead?
836 self.instance.callbacks.add(callback.clone());
837 Ok(())
838 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000839
Andrew Walbranf8d94112021-09-07 11:45:36 +0000840 fn start(&self) -> binder::Result<()> {
841 self.instance.start().map_err(|e| {
842 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000843 Status::new_service_specific_error_str(-1, Some(e.to_string()))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000844 })
845 }
846
Inseob Kima446f802022-07-11 19:46:37 +0900847 fn stop(&self) -> binder::Result<()> {
848 self.instance.kill().map_err(|e| {
849 error!("Error stopping 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()))
Inseob Kima446f802022-07-11 19:46:37 +0900851 })
852 }
853
Keir Frasercdd4b112022-11-24 14:02:25 +0000854 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
855 self.instance.trim_memory(level).map_err(|e| {
856 error!("Error trimming VM with CID {}: {:?}", self.instance.cid, e);
857 Status::new_service_specific_error_str(-1, Some(e.to_string()))
858 })
859 }
860
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000861 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000862 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Andrew Walbrandcf9d582022-08-03 11:25:24 +0000863 return Err(Status::new_service_specific_error_str(-1, Some("VM is not running")));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000864 }
Alan Stokes10c47672022-12-13 17:17:08 +0000865 let port = port as u32;
866 if port < 1024 {
867 return Err(Status::new_service_specific_error_str(
868 -1,
869 Some(format!("Can't connect to privileged port {port}")),
870 ));
871 }
872 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port).map_err(|e| {
873 Status::new_service_specific_error_str(-1, Some(format!("Failed to connect: {:?}", e)))
874 })?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000875 Ok(vsock_stream_to_pfd(stream))
876 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000877}
878
879impl Drop for VirtualMachine {
880 fn drop(&mut self) {
881 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900882 if let Err(e) = self.instance.kill() {
883 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
884 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000885 }
886}
887
888/// A set of Binders to be called back in response to various events on the VM, such as when it
889/// dies.
890#[derive(Debug, Default)]
891pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
892
893impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900894 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100895 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900896 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900897 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100898 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100899 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900900 }
901 }
902 }
903
Inseob Kim14cb8692021-08-31 21:50:39 +0900904 /// Call all registered callbacks to notify that the payload is ready to serve.
905 pub fn notify_payload_ready(&self, cid: Cid) {
906 let callbacks = &*self.0.lock().unwrap();
907 for callback in callbacks {
908 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100909 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900910 }
911 }
912 }
913
Inseob Kim2444af92021-08-31 01:22:50 +0900914 /// Call all registered callbacks to notify that the payload has finished.
915 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
916 let callbacks = &*self.0.lock().unwrap();
917 for callback in callbacks {
918 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100919 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900920 }
921 }
922 }
923
Jooyung Handd0a1732021-11-23 15:26:20 +0900924 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100925 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900926 let callbacks = &*self.0.lock().unwrap();
927 for callback in callbacks {
928 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100929 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900930 }
931 }
932 }
933
Andrew Walbrandae07162021-03-12 17:05:20 +0000934 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000935 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000936 let callbacks = &*self.0.lock().unwrap();
937 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000938 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100939 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000940 }
941 }
942 }
943
944 /// Add a new callback to the set.
945 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
946 self.0.lock().unwrap().push(callback);
947 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000948}
949
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000950/// The mutable state of the VirtualizationService. There should only be one instance of this
951/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800952#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000953struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000954 /// The VMs which have been started. When VMs are started a weak reference is added to this list
955 /// while a strong reference is returned to the caller over Binder. Once all copies of the
956 /// Binder client are dropped the weak reference here will become invalid, and will be removed
957 /// from the list opportunistically the next time `add_vm` is called.
958 vms: Vec<Weak<VmInstance>>,
959}
960
961impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000962 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000963 fn vms(&self) -> Vec<Arc<VmInstance>> {
964 // Attempt to upgrade the weak pointers to strong pointers.
965 self.vms.iter().filter_map(Weak::upgrade).collect()
966 }
967
968 /// Add a new VM to the list.
969 fn add_vm(&mut self, vm: Weak<VmInstance>) {
970 // Garbage collect any entries from the stored list which no longer exist.
971 self.vms.retain(|vm| vm.strong_count() > 0);
972
973 // Actually add the new VM.
974 self.vms.push(vm);
975 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000976
Jiyong Park8611a6c2021-07-09 18:17:44 +0900977 /// Get a VM that corresponds to the given cid
978 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
979 self.vms().into_iter().find(|vm| vm.cid == cid)
980 }
Jiyong Parkd50a0242021-09-16 21:00:14 +0900981}
982
Andrew Walbran6b650662021-09-07 13:13:23 +0000983/// Gets the `VirtualMachineState` of the given `VmInstance`.
984fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000985 match &*instance.vm_state.lock().unwrap() {
986 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
987 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000988 PayloadState::Starting => VirtualMachineState::STARTING,
989 PayloadState::Started => VirtualMachineState::STARTED,
990 PayloadState::Ready => VirtualMachineState::READY,
991 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900992 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000993 },
994 VmState::Dead => VirtualMachineState::DEAD,
995 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000996 }
997}
998
David Brazdilf50c7a62023-04-19 14:22:42 +0000999/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
1000pub fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
1001 file.as_ref().try_clone().map_err(|e| {
1002 Status::new_exception_str(
1003 ExceptionCode::BAD_PARCELABLE,
1004 Some(format!("Failed to clone File from ParcelFileDescriptor: {:?}", e)),
1005 )
1006 })
1007}
1008
Andrew Walbrand3a84182021-09-07 14:48:52 +00001009/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1010fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1011 file.as_ref().map(clone_file).transpose()
1012}
1013
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001014/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1015fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1016 // SAFETY: ownership is transferred from stream to f
1017 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1018 ParcelFileDescriptor::new(f)
1019}
1020
Jiyong Parkdcf17412022-02-08 15:07:23 +09001021/// Parses the platform version requirement string.
1022fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1023 VersionReq::parse(s).map_err(|e| {
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001024 Status::new_exception_str(
Jiyong Parkdcf17412022-02-08 15:07:23 +09001025 ExceptionCode::BAD_PARCELABLE,
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001026 Some(format!("Invalid platform version requirement {}: {:?}", s, e)),
Jiyong Parkdcf17412022-02-08 15:07:23 +09001027 )
1028 })
1029}
1030
Jiyong Parked180932023-02-24 19:55:41 +09001031/// Create the empty ramdump file
1032fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1033 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1034 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1035 // owner) for readout.
1036 let ramdump_path = temporary_directory.join("ramdump");
1037 let ramdump = File::create(ramdump_path).map_err(|e| {
1038 error!("Failed to prepare ramdump file: {:?}", e);
1039 Status::new_service_specific_error_str(
1040 -1,
1041 Some(format!("Failed to prepare ramdump file: {:?}", e)),
1042 )
1043 })?;
1044 Ok(ramdump)
1045}
1046
Nikita Ioffe5776f082023-02-10 21:38:26 +00001047fn is_protected(config: &VirtualMachineConfig) -> bool {
1048 match config {
1049 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1050 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1051 }
1052}
1053
1054fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1055 if is_protected(config) {
1056 return Err(Status::new_exception_str(
1057 ExceptionCode::SECURITY,
1058 Some("can't use gdb with protected VMs"),
1059 ));
1060 }
1061
1062 match config {
1063 VirtualMachineConfig::RawConfig(_) => Ok(()),
1064 VirtualMachineConfig::AppConfig(config) => {
1065 if config.debugLevel != DebugLevel::FULL {
1066 Err(Status::new_exception_str(
1067 ExceptionCode::SECURITY,
1068 Some("can't use gdb with non-debuggable VMs"),
1069 ))
1070 } else {
1071 Ok(())
1072 }
1073 }
1074 }
1075}
1076
1077fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1078 match config {
1079 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001080 VirtualMachineConfig::AppConfig(config) => {
1081 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1082 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001083 }
1084}
1085
Inseob Kim0168b462022-12-27 14:54:35 +09001086fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001087 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001088 fd: Option<&ParcelFileDescriptor>,
1089 tag: String,
1090) -> Result<Option<File>, Status> {
1091 if let Some(fd) = fd {
1092 return Ok(Some(clone_file(fd)?));
1093 }
1094
Jaewan Kim61f86142023-03-28 15:12:52 +09001095 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001096 return Ok(None);
1097 };
Inseob Kim0168b462022-12-27 14:54:35 +09001098
1099 let (raw_read_fd, raw_write_fd) = pipe().map_err(|e| {
1100 Status::new_service_specific_error_str(-1, Some(format!("Failed to create pipe: {:?}", e)))
1101 })?;
1102
1103 // SAFETY: We are the sole owners of these fds as they were just created.
1104 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
1105 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1106
1107 std::thread::spawn(move || loop {
1108 let mut buf = vec![];
1109 match reader.read_until(b'\n', &mut buf) {
1110 Ok(0) => {
1111 // EOF
1112 return;
1113 }
1114 Ok(size) => {
1115 if buf[size - 1] == b'\n' {
1116 buf.pop();
1117 }
1118 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1119 }
1120 Err(e) => {
1121 error!("Could not read console pipe: {:?}", e);
1122 return;
1123 }
1124 };
1125 });
1126
1127 Ok(Some(write_fd))
1128}
1129
Jooyung Han35edb8f2021-07-01 16:17:16 +09001130/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1131/// it doesn't require that T implements Clone.
1132enum BorrowedOrOwned<'a, T> {
1133 Borrowed(&'a T),
1134 Owned(T),
1135}
1136
1137impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1138 fn as_ref(&self) -> &T {
1139 match self {
1140 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001141 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001142 }
1143 }
1144}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001145
1146/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1147#[derive(Debug, Default)]
1148struct VirtualMachineService {
1149 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001150 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001151}
1152
1153impl Interface for VirtualMachineService {}
1154
1155impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001156 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1157 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001158 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001159 info!("VM with CID {} started payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001160 vm.update_payload_state(PayloadState::Started).map_err(|e| {
1161 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1162 })?;
David Brazdil451cc962022-10-14 14:08:12 +01001163 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001164
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001165 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1166 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001167 Ok(())
1168 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001169 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001170 Err(Status::new_service_specific_error_str(
1171 -1,
1172 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001173 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001174 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001175 }
Inseob Kim2444af92021-08-31 01:22:50 +09001176
Inseob Kimc7d28c72021-10-25 14:28:10 +00001177 fn notifyPayloadReady(&self) -> binder::Result<()> {
1178 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001179 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001180 info!("VM with CID {} reported payload is ready", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001181 vm.update_payload_state(PayloadState::Ready).map_err(|e| {
1182 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1183 })?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001184 vm.callbacks.notify_payload_ready(cid);
1185 Ok(())
1186 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001187 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001188 Err(Status::new_service_specific_error_str(
1189 -1,
1190 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim14cb8692021-08-31 21:50:39 +09001191 ))
1192 }
1193 }
1194
Inseob Kimc7d28c72021-10-25 14:28:10 +00001195 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1196 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001197 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001198 info!("VM with CID {} finished payload", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001199 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1200 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1201 })?;
Inseob Kim2444af92021-08-31 01:22:50 +09001202 vm.callbacks.notify_payload_finished(cid, exit_code);
1203 Ok(())
1204 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001205 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001206 Err(Status::new_service_specific_error_str(
1207 -1,
1208 Some(format!("cannot find a VM with CID {}", cid)),
Jooyung Handd0a1732021-11-23 15:26:20 +09001209 ))
1210 }
1211 }
1212
Alan Stokes2bead0d2022-09-05 16:58:34 +01001213 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001214 let cid = self.cid;
1215 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001216 info!("VM with CID {} encountered an error", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001217 vm.update_payload_state(PayloadState::Finished).map_err(|e| {
1218 Status::new_exception_str(ExceptionCode::ILLEGAL_STATE, Some(e.to_string()))
1219 })?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001220 vm.callbacks.notify_error(cid, error_code, message);
1221 Ok(())
1222 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001223 error!("notifyError is called from an unknown CID {}", cid);
Andrew Walbrandcf9d582022-08-03 11:25:24 +00001224 Err(Status::new_service_specific_error_str(
1225 -1,
1226 Some(format!("cannot find a VM with CID {}", cid)),
Inseob Kim2444af92021-08-31 01:22:50 +09001227 ))
1228 }
1229 }
Alice Wangc2fec932023-02-23 16:24:02 +00001230
1231 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
1232 let cid = self.cid;
1233 let Some(vm) = self.state.lock().unwrap().get_vm(cid) else {
1234 error!("requestCertificate is called from an unknown CID {cid}");
1235 return Err(Status::new_service_specific_error_str(
1236 -1,
1237 Some(format!("cannot find a VM with CID {}", cid)),
1238 ))
1239 };
1240 let instance_img_path = vm.temporary_directory.join("rkpvm_instance.img");
1241 let instance_img = OpenOptions::new()
1242 .create(true)
1243 .read(true)
1244 .write(true)
1245 .open(instance_img_path)
1246 .map_err(|e| {
1247 error!("Failed to create rkpvm_instance.img file: {:?}", e);
1248 Status::new_service_specific_error_str(
1249 -1,
1250 Some(format!("Failed to create rkpvm_instance.img file: {:?}", e)),
1251 )
1252 })?;
1253 GLOBAL_SERVICE.requestCertificate(csr, &ParcelFileDescriptor::new(instance_img))
1254 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001255}
1256
1257impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001258 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001259 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001260 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001261 BinderFeatures::default(),
1262 )
1263 }
1264}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001265
1266#[cfg(test)]
1267mod tests {
1268 use super::*;
1269
1270 #[test]
1271 fn test_is_allowed_label_for_partition() -> Result<()> {
1272 let expected_results = vec![
1273 ("u:object_r:system_file:s0", true),
1274 ("u:object_r:apk_data_file:s0", true),
1275 ("u:object_r:app_data_file:s0", false),
1276 ("u:object_r:app_data_file:s0:c512,c768", false),
1277 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1278 ("invalid", false),
1279 ("user:role:apk_data_file:severity:categories", true),
1280 ("user:role:apk_data_file:severity:categories:extraneous", false),
1281 ];
1282
1283 for (label, expected_valid) in expected_results {
1284 let context = SeContext::new(label)?;
1285 let result = check_label_is_allowed(&context);
1286 if expected_valid {
1287 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1288 } else if result.is_ok() {
1289 bail!("Expected label {} to be disallowed", label);
1290 }
1291 }
1292 Ok(())
1293 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001294
1295 #[test]
1296 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1297 let apk = tempfile::tempfile().unwrap();
1298 let idsig = tempfile::tempfile().unwrap();
1299
1300 let ret = create_or_update_idsig_file(
1301 &ParcelFileDescriptor::new(apk),
1302 &ParcelFileDescriptor::new(idsig),
1303 );
1304 assert!(ret.is_err(), "should fail");
1305 Ok(())
1306 }
1307
1308 #[test]
1309 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1310 let tmp_dir = tempfile::TempDir::new().unwrap();
1311 let apk = File::open(tmp_dir.path()).unwrap();
1312 let idsig = tempfile::tempfile().unwrap();
1313
1314 let ret = create_or_update_idsig_file(
1315 &ParcelFileDescriptor::new(apk),
1316 &ParcelFileDescriptor::new(idsig),
1317 );
1318 assert!(ret.is_err(), "should fail");
1319 Ok(())
1320 }
1321
1322 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1323 /// on ext4 filesystem is passed.
1324 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1325 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1326 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1327 #[test]
1328 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1329 // APEXes are backed by the ext4.
1330 let apk = File::open("/apex/com.android.virt/").unwrap();
1331 let idsig = tempfile::tempfile().unwrap();
1332
1333 let ret = create_or_update_idsig_file(
1334 &ParcelFileDescriptor::new(apk),
1335 &ParcelFileDescriptor::new(idsig),
1336 );
1337 assert!(ret.is_err(), "should fail");
1338 Ok(())
1339 }
Jiyong Park8d192952023-06-26 14:29:51 +09001340
1341 #[test]
1342 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1343 use std::io::Seek;
1344
1345 // Pick any APK
1346 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1347 let mut idsig = tempfile::tempfile().unwrap();
1348
1349 create_or_update_idsig_file(
1350 &ParcelFileDescriptor::new(apk.try_clone()?),
1351 &ParcelFileDescriptor::new(idsig.try_clone()?),
1352 )?;
1353 let modified_orig = idsig.metadata()?.modified()?;
1354 apk.rewind()?;
1355 idsig.rewind()?;
1356
1357 // Call the function again
1358 create_or_update_idsig_file(
1359 &ParcelFileDescriptor::new(apk.try_clone()?),
1360 &ParcelFileDescriptor::new(idsig.try_clone()?),
1361 )?;
1362 let modified_new = idsig.metadata()?.modified()?;
1363 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1364 Ok(())
1365 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001366
1367 #[test]
1368 fn test_append_kernel_param_first_param() {
1369 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1370 append_kernel_param("foo=1", &mut vm_config);
1371 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1372 }
1373
1374 #[test]
1375 fn test_append_kernel_param() {
1376 let mut vm_config =
1377 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1378 append_kernel_param("bar=42", &mut vm_config);
1379 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1380 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001381}