blob: ae81a179c7ae706bc332c0a3601f997a2c88f8d9 [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,
Jiyong Park2227eaa2023-08-04 11:59:18 +090056 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000057};
David Brazdilf50c7a62023-04-19 14:22:42 +000058use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000059use lazy_static::lazy_static;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000060use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090061use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090062use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000063use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000064use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090065use semver::VersionReq;
Inseob Kim6ef80972023-07-20 17:23:36 +090066use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000067use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000068use std::ffi::CStr;
Inseob Kim6ef80972023-07-20 17:23:36 +090069use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000070use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000071use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000072use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000073use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000074use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000075use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000076use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000077use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090078use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000079
Jiyong Park2227eaa2023-08-04 11:59:18 +090080/// Convenient trait for logging an error while returning it
81trait LogResult<T, E> {
82 fn with_log(self) -> std::result::Result<T, E>;
83}
84
85impl<T, E: std::fmt::Debug> LogResult<T, E> for std::result::Result<T, E> {
86 fn with_log(self) -> std::result::Result<T, E> {
87 self.map_err(|e| {
88 error!("{e:?}");
89 e
90 })
91 }
92}
93
David Brazdil41d1a872022-10-05 14:44:19 +010094/// The unique ID of a VM used (together with a port number) for vsock communication.
95pub type Cid = u32;
96
David Brazdil4b4c5102022-12-19 22:56:20 +000097pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
98
Jooyung Han95884632021-07-06 22:27:54 +090099/// The size of zero.img.
100/// Gaps in composite disk images are filled with a shared zero.img.
101const ZERO_FILLER_SIZE: u64 = 4096;
102
David Brazdilf50c7a62023-04-19 14:22:42 +0000103/// Magic string for the instance image
104const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
105
106/// Version of the instance image format
107const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
108
Alan Stokes0d1ef782022-09-27 13:46:35 +0100109const MICRODROID_OS_NAME: &str = "microdroid";
110
David Brazdilf50c7a62023-04-19 14:22:42 +0000111const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
112
113/// crosvm requires all partitions to be a multiple of 4KiB.
114const PARTITION_GRANULARITY_BYTES: u64 = 4096;
115
David Brazdil49f96f52022-12-16 21:29:13 +0000116lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000117 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
118 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
119 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000120}
121
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000122fn create_or_update_idsig_file(
123 input_fd: &ParcelFileDescriptor,
124 idsig_fd: &ParcelFileDescriptor,
125) -> Result<()> {
126 let mut input = clone_file(input_fd)?;
127 let metadata = input.metadata().context("failed to get input metadata")?;
128 if !metadata.is_file() {
129 bail!("input is not a regular file");
130 }
Alan Stokes25f69362023-03-06 16:51:54 +0000131 let mut sig =
132 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
133 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000134
135 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900136
137 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
138 // if the idsig file already has the same APK digest.
139 if output.metadata()?.len() > 0 {
140 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
141 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
142 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
143 return Ok(());
144 }
145 }
146 // if we fail to read v4signature from output, that's fine. User can pass a random file.
147 // We will anyway overwrite the file to the v4signature generated from input_fd.
148 }
149
Nikita Ioffec09b0492022-12-14 20:18:33 +0000150 output.set_len(0).context("failed to set_len on the idsig output")?;
151 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000152 Ok(())
153}
154
Alan Stokes25f69362023-03-06 16:51:54 +0000155fn get_current_sdk() -> Result<u32> {
156 let current_sdk = system_properties::read("ro.build.version.sdk")?;
157 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
158 current_sdk.parse().context("Malformed SDK version")
159}
160
David Brazdil4b4c5102022-12-19 22:56:20 +0000161pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
162 for dir_entry in read_dir(path)? {
163 remove_file(dir_entry?.path())?;
164 }
165 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100166}
167
David Brazdil528e0472022-10-10 15:06:02 +0100168/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000169#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000170pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900171 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000172}
173
Shikha Panward8e35422021-10-11 13:51:27 +0000174impl Interface for VirtualizationService {
175 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
176 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
177 let state = &mut *self.state.lock().unwrap();
178 let vms = state.vms();
179 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
180 for vm in vms {
181 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
182 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
183 .or(Err(StatusCode::UNKNOWN_ERROR))?;
184 writeln!(file, "\tPayload state {:?}", vm.payload_state())
185 .or(Err(StatusCode::UNKNOWN_ERROR))?;
186 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
187 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
188 .or(Err(StatusCode::UNKNOWN_ERROR))?;
189 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
190 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000191 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
192 .or(Err(StatusCode::UNKNOWN_ERROR))?;
193 }
194 Ok(())
195 }
196}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000197impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000198 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
199 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000200 ///
201 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000202 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000203 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000204 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900205 console_out_fd: Option<&ParcelFileDescriptor>,
206 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000207 log_fd: Option<&ParcelFileDescriptor>,
208 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000209 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900210 let ret = self.create_vm_internal(
211 config,
212 console_out_fd,
213 console_in_fd,
214 log_fd,
215 &mut is_protected,
216 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000217 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000218 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000219 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000220
Andrew Walbrandff3b942021-06-09 15:20:36 +0000221 /// Initialise an empty partition image of the given size to be used as a writable partition.
222 fn initializeWritablePartition(
223 &self,
224 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000225 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900226 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000227 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900228 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900229 let size_bytes = size_bytes
230 .try_into()
231 .with_context(|| format!("Invalid size: {}", size_bytes))
232 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000233 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
234 let image = clone_file(image_fd)?;
235 // initialize the file. Any data in the file will be erased.
Jiyong Park2227eaa2023-08-04 11:59:18 +0900236 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
237 let mut part = QcowFile::new(image, size_bytes)
238 .context("Failed to create QCOW2 image")
239 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000240
241 match partition_type {
242 PartitionType::RAW => Ok(()),
243 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
244 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
245 _ => Err(Error::new(
246 ErrorKind::Unsupported,
247 format!("Unsupported partition type {:?}", partition_type),
248 )),
249 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900250 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
251 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000252
253 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000254 }
255
Jiyong Park0a248432021-08-20 23:32:39 +0900256 /// Creates or update the idsig file by digesting the input APK file.
257 fn createOrUpdateIdsigFile(
258 &self,
259 input_fd: &ParcelFileDescriptor,
260 idsig_fd: &ParcelFileDescriptor,
261 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900262 check_manage_access()?;
263
Jiyong Park2227eaa2023-08-04 11:59:18 +0900264 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
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 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900311 Err(anyhow!("Too many attempts to create VM context failed"))
312 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000313 }
314
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000315 fn create_vm_internal(
316 &self,
317 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900318 console_out_fd: Option<&ParcelFileDescriptor>,
319 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000320 log_fd: Option<&ParcelFileDescriptor>,
321 is_protected: &mut bool,
322 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000323 let requester_uid = get_calling_uid();
324 let requester_debug_pid = get_calling_pid();
325
326 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
327 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900328
Alan Stokes7bc146c2022-10-20 17:10:32 +0100329 let is_custom = match config {
330 VirtualMachineConfig::RawConfig(_) => true,
331 VirtualMachineConfig::AppConfig(config) => {
332 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100333 // VirtualMachineAppConfig. Almost all of these features are grouped in the
334 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100335 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100336 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100337 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900338 // - using anything other than the default kernel;
339 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100340 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900341 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100342 };
343 if is_custom {
344 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900345 }
346
Nikita Ioffe5776f082023-02-10 21:38:26 +0000347 let gdb_port = extract_gdb_port(config);
348
349 // Additional permission checks if caller request gdb.
350 if gdb_port.is_some() {
351 check_gdb_allowed(config)?;
352 }
353
Jaewan Kim61f86142023-03-28 15:12:52 +0900354 let debug_level = match config {
355 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
356 _ => DebugLevel::NONE,
357 };
358 let debug_config = DebugConfig::new(debug_level);
359
360 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900361 Some(prepare_ramdump_file(&temporary_directory)?)
362 } else {
363 None
364 };
365
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000366 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900367 let console_out_fd =
368 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
369 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900370 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000371
372 // Counter to generate unique IDs for temporary image files.
373 let mut next_temporary_image_id = 0;
374 // Files which are referred to from composite images. These must be mapped to the crosvm
375 // child process, and not closed before it is started.
376 let mut indirect_files = vec![];
377
Alan Stokes7bc146c2022-10-20 17:10:32 +0100378 let (is_app_config, config) = match config {
379 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
380 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900381 let config = load_app_config(config, &debug_config, &temporary_directory)
382 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900383 *is_protected = config.protectedVm;
384 let message = format!("Failed to load app config: {:?}", e);
385 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900386 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900387 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100388 (true, BorrowedOrOwned::Owned(config))
389 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000390 };
391 let config = config.as_ref();
392 *is_protected = config.protectedVm;
393
394 // Check if partition images are labeled incorrectly. This is to prevent random images
395 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100396 // being loaded in a pVM. This applies to everything in the raw config, and everything but
397 // the non-executable, generated partitions in the app config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000398 config
399 .disks
400 .iter()
401 .flat_map(|disk| disk.partitions.iter())
402 .filter(|partition| {
403 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100404 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000405 } else {
406 true // all partitions are checked
407 }
408 })
409 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900410 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000411
Alan Stokes185fe112023-01-10 16:20:55 +0000412 let kernel = maybe_clone_file(&config.kernel)?;
413 let initrd = maybe_clone_file(&config.initrd)?;
414
415 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
416 if config.protectedVm {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900417 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Alan Stokes185fe112023-01-10 16:20:55 +0000418 }
419
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000420 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900421 write_zero_filler(&zero_filler_path)
422 .context("Failed to make composite image")
423 .with_log()
424 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000425
426 // Assemble disk images if needed.
427 let disks = config
428 .disks
429 .iter()
430 .map(|disk| {
431 assemble_disk_image(
432 disk,
433 &zero_filler_path,
434 &temporary_directory,
435 &mut next_temporary_image_id,
436 &mut indirect_files,
437 )
438 })
439 .collect::<Result<Vec<DiskFile>, _>>()?;
440
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000441 let (cpus, host_cpu_topology) = match config.cpuTopology {
442 CpuTopology::MATCH_HOST => (None, true),
443 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
444 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900445 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
446 .with_log()
447 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000448 }
449 };
450
Inseob Kim6ef80972023-07-20 17:23:36 +0900451 let devices_dtbo = if !config.devices.is_empty() {
452 let mut set = HashSet::new();
453 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900454 let path = canonicalize(device)
455 .with_context(|| format!("can't canonicalize {device}"))
456 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900457 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900458 return Err(anyhow!("duplicated device {device}"))
459 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900460 }
461 }
Inseob Kimf36347b2023-08-03 12:52:48 +0900462 let dtbo_path = temporary_directory.join("dtbo");
463 // open a writable file descriptor for vfio_handler
464 let dtbo = File::create(&dtbo_path).map_err(|e| {
465 error!("Failed to create VM DTBO file {dtbo_path:?}: {e:?}");
466 Status::new_service_specific_error_str(
467 -1,
468 Some(format!("Failed to create VM DTBO file {dtbo_path:?}: {e:?}")),
469 )
470 })?;
471 GLOBAL_SERVICE
472 .bindDevicesToVfioDriver(&config.devices, &ParcelFileDescriptor::new(dtbo))?;
473
474 // open (again) a readable file descriptor for crosvm
475 let dtbo = File::open(&dtbo_path).map_err(|e| {
476 error!("Failed to open VM DTBO file {dtbo_path:?}: {e:?}");
477 Status::new_service_specific_error_str(
478 -1,
479 Some(format!("Failed to open VM DTBO file {dtbo_path:?}: {e:?}")),
480 )
481 })?;
482 Some(dtbo)
Inseob Kim6ef80972023-07-20 17:23:36 +0900483 } else {
484 None
485 };
486
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000487 // Actually start the VM.
488 let crosvm_config = CrosvmConfig {
489 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000490 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000491 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000492 kernel,
493 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000494 disks,
495 params: config.params.to_owned(),
496 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900497 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000498 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000499 cpus,
500 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900501 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900502 console_out_fd,
503 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000504 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900505 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000506 indirect_files,
507 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900508 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000509 gdb_port,
Inseob Kim6ef80972023-07-20 17:23:36 +0900510 vfio_devices: config.devices.iter().map(PathBuf::from).collect(),
511 devices_dtbo,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000512 };
513 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100514 VmInstance::new(
515 crosvm_config,
516 temporary_directory,
517 requester_uid,
518 requester_debug_pid,
519 vm_context,
520 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900521 .with_context(|| format!("Failed to create VM with config {:?}", config))
522 .with_log()
523 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000524 );
525 state.add_vm(Arc::downgrade(&instance));
526 Ok(VirtualMachine::create(instance))
527 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900528}
529
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000530fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900531 let file = OpenOptions::new()
532 .create_new(true)
533 .read(true)
534 .write(true)
535 .open(zero_filler_path)
536 .with_context(|| "Failed to create zero.img")?;
537 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000538 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900539}
540
David Brazdilf50c7a62023-04-19 14:22:42 +0000541fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
542 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
543 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
544 part.flush()
545}
546
547fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
548 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
549 part.flush()
550}
551
552fn round_up(input: u64, granularity: u64) -> u64 {
553 if granularity == 0 {
554 return input;
555 }
556 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
557 let result = input.checked_add(granularity - 1).unwrap_or(input);
558 (result / granularity) * granularity
559}
560
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000561/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
562///
563/// This may involve assembling a composite disk from a set of partition images.
564fn assemble_disk_image(
565 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900566 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000567 temporary_directory: &Path,
568 next_temporary_image_id: &mut u64,
569 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000570) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000571 let image = if !disk.partitions.is_empty() {
572 if disk.image.is_some() {
573 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900574 return Err(anyhow!("DiskImage contains both image and partitions"))
575 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000576 }
577
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000578 let composite_image_filenames =
579 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
580 let (image, partition_files) = make_composite_image(
581 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900582 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000583 &composite_image_filenames.composite,
584 &composite_image_filenames.header,
585 &composite_image_filenames.footer,
586 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900587 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
588 .with_log()
589 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000590
591 // Pass the file descriptors for the various partition files to crosvm when it
592 // is run.
593 indirect_files.extend(partition_files);
594
595 image
596 } else if let Some(image) = &disk.image {
597 clone_file(image)?
598 } else {
599 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900600 return Err(anyhow!("DiskImage didn't contain image or partitions."))
601 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000602 };
603
604 Ok(DiskFile { image, writable: disk.writable })
605}
606
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100607fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
608 if let Some(ref mut params) = vm_config.params {
609 params.push(' ');
610 params.push_str(param)
611 } else {
612 vm_config.params = Some(param.to_owned())
613 }
614}
615
Jooyung Han21e9b922021-06-26 04:14:16 +0900616fn load_app_config(
617 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900618 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900619 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900620) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000621 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
622 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900623 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900624
Shikha Panwar22e70452022-10-10 18:32:55 +0000625 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
626 Some(clone_file(file)?)
627 } else {
628 None
629 };
630
Alan Stokes0d1ef782022-09-27 13:46:35 +0100631 let vm_payload_config = match &config.payload {
632 Payload::ConfigPath(config_path) => {
633 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
634 .with_context(|| format!("Couldn't read config from {}", config_path))?
635 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000636 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100637 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900638
Alan Stokes0d1ef782022-09-27 13:46:35 +0100639 // For now, the only supported OS is Microdroid
640 let os_name = vm_payload_config.os.name.as_str();
641 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000642 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900643 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000644
645 // It is safe to construct a filename based on the os_name because we've already checked that it
646 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900647 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
648 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000649 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900650
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100651 if let Some(custom_config) = &config.customConfig {
652 if let Some(file) = custom_config.customKernelImage.as_ref() {
653 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
654 }
655 vm_config.taskProfiles = custom_config.taskProfiles.clone();
656 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100657
658 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100659 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
660 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100661 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900662
663 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100664 }
665
Andrew Walbrancc045902021-07-27 16:06:17 +0000666 if config.memoryMib > 0 {
667 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000668 }
669
Seungjae Yoo62085c02022-08-12 04:44:52 +0000670 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000671 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000672 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900673
Shikha Panwar22e70452022-10-10 18:32:55 +0000674 // Microdroid takes additional init ramdisk & (optionally) storage image
675 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
676
677 // Include Microdroid payload disk (contains apks, idsigs) in vm config
678 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100679 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900680 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100681 temporary_directory,
682 apk_file,
683 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100684 &vm_payload_config,
685 &mut vm_config,
686 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900687
Andrew Walbrancc0db522021-07-12 17:03:42 +0000688 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900689}
690
Alan Stokes0d1ef782022-09-27 13:46:35 +0100691fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
692 let mut apk_zip = ZipArchive::new(apk_file)?;
693 let config_file = apk_zip.by_name(config_path)?;
694 Ok(serde_json::from_reader(config_file)?)
695}
696
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000697fn create_vm_payload_config(
698 payload_config: &VirtualMachinePayloadConfig,
699) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100700 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
701 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
702 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000703
704 let payload_binary_name = &payload_config.payloadBinaryName;
705 if payload_binary_name.contains('/') {
706 bail!("Payload binary name must not specify a path: {payload_binary_name}");
707 }
708
709 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
710 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100711 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
712 task: Some(task),
713 apexes: vec![],
714 extra_apks: vec![],
715 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900716 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100717 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000718 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100719}
720
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000721/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000722fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000723 temporary_directory: &Path,
724 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000725) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000726 let id = *next_temporary_image_id;
727 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000728 CompositeImageFilenames {
729 composite: temporary_directory.join(format!("composite-{}.img", id)),
730 header: temporary_directory.join(format!("composite-{}-header.img", id)),
731 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
732 }
733}
734
735/// Filenames for a composite disk image, including header and footer partitions.
736#[derive(Clone, Debug, Eq, PartialEq)]
737struct CompositeImageFilenames {
738 /// The composite disk image itself.
739 composite: PathBuf,
740 /// The header partition image.
741 header: PathBuf,
742 /// The footer partition image.
743 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000744}
745
Jiyong Park753553b2021-07-12 21:21:09 +0900746/// Checks whether the caller has a specific permission
747fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100748 let calling_pid = get_calling_pid();
749 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900750 // Root can do anything
751 if calling_uid == 0 {
752 return Ok(());
753 }
754 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
755 binder::get_interface("permission")?;
756 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000757 Ok(())
758 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900759 Err(anyhow!("does not have the {} permission", perm))
760 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000761 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000762}
763
Jiyong Park753553b2021-07-12 21:21:09 +0900764/// Check whether the caller of the current Binder method is allowed to manage VMs
765fn check_manage_access() -> binder::Result<()> {
766 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
767}
768
Inseob Kim1119d702022-05-02 18:01:58 +0900769/// Check whether the caller of the current Binder method is allowed to create custom VMs
770fn check_use_custom_virtual_machine() -> binder::Result<()> {
771 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
772}
773
Alan Stokes185fe112023-01-10 16:20:55 +0000774/// Return whether a partition is exempt from selinux label checks, because we know that it does
775/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100776fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000777 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100778 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000779 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100780 || label == "microdroid-apk-idsig"
781 || label == "payload-metadata"
782 || label.starts_with("extra-idsig-")
783}
784
Alan Stokes185fe112023-01-10 16:20:55 +0000785/// Check that a file SELinux label is acceptable.
786///
787/// We only want to allow code in a VM to be sourced from places that apps, and the
788/// system, do not have write access to.
789///
790/// Note that sepolicy must also grant read access for these types to both virtualization
791/// service and crosvm.
792///
793/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
794/// user devices (W^X).
795fn check_label_is_allowed(context: &SeContext) -> Result<()> {
796 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100797 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100798 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000799 | "staging_data_file" // updated/staged APEX images
800 | "system_file" // immutable dm-verity protected partition
801 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100802 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000803 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900804 }
805}
806
Alan Stokes185fe112023-01-10 16:20:55 +0000807fn check_label_for_partition(partition: &Partition) -> Result<()> {
808 let file = partition.image.as_ref().unwrap().as_ref();
809 check_label_is_allowed(&getfilecon(file)?)
810 .with_context(|| format!("Partition {} invalid", &partition.label))
811}
812
813fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
814 if let Some(f) = kernel {
815 check_label_for_file(f, "kernel")?;
816 }
817 if let Some(f) = initrd {
818 check_label_for_file(f, "initrd")?;
819 }
820 Ok(())
821}
822fn check_label_for_file(file: &File, name: &str) -> Result<()> {
823 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
824}
825
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000826/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
827#[derive(Debug)]
828struct VirtualMachine {
829 instance: Arc<VmInstance>,
830}
831
832impl VirtualMachine {
833 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000834 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000835 }
836}
837
838impl Interface for VirtualMachine {}
839
840impl IVirtualMachine for VirtualMachine {
841 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900842 // Don't check permission. The owner of the VM might have passed this binder object to
843 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000844 Ok(self.instance.cid as i32)
845 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000846
Andrew Walbran6b650662021-09-07 13:13:23 +0000847 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900848 // Don't check permission. The owner of the VM might have passed this binder object to
849 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000850 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000851 }
852
853 fn registerCallback(
854 &self,
855 callback: &Strong<dyn IVirtualMachineCallback>,
856 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900857 // Don't check permission. The owner of the VM might have passed this binder object to
858 // others.
859 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000860 // TODO: Should this give an error if the VM is already dead?
861 self.instance.callbacks.add(callback.clone());
862 Ok(())
863 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000864
Andrew Walbranf8d94112021-09-07 11:45:36 +0000865 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900866 self.instance
867 .start()
868 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
869 .with_log()
870 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000871 }
872
Inseob Kima446f802022-07-11 19:46:37 +0900873 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900874 self.instance
875 .kill()
876 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
877 .with_log()
878 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +0900879 }
880
Keir Frasercdd4b112022-11-24 14:02:25 +0000881 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900882 self.instance
883 .trim_memory(level)
884 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
885 .with_log()
886 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +0000887 }
888
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000889 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000890 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900891 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000892 }
Alan Stokes10c47672022-12-13 17:17:08 +0000893 let port = port as u32;
894 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900895 return Err(anyhow!("Can't connect to privileged port {port}"))
896 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +0000897 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900898 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
899 .context("Failed to connect")
900 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000901 Ok(vsock_stream_to_pfd(stream))
902 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000903}
904
905impl Drop for VirtualMachine {
906 fn drop(&mut self) {
907 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900908 if let Err(e) = self.instance.kill() {
909 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
910 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000911 }
912}
913
914/// A set of Binders to be called back in response to various events on the VM, such as when it
915/// dies.
916#[derive(Debug, Default)]
917pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
918
919impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900920 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +0100921 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900922 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900923 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +0100924 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100925 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900926 }
927 }
928 }
929
Inseob Kim14cb8692021-08-31 21:50:39 +0900930 /// Call all registered callbacks to notify that the payload is ready to serve.
931 pub fn notify_payload_ready(&self, cid: Cid) {
932 let callbacks = &*self.0.lock().unwrap();
933 for callback in callbacks {
934 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100935 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900936 }
937 }
938 }
939
Inseob Kim2444af92021-08-31 01:22:50 +0900940 /// Call all registered callbacks to notify that the payload has finished.
941 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
942 let callbacks = &*self.0.lock().unwrap();
943 for callback in callbacks {
944 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100945 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900946 }
947 }
948 }
949
Jooyung Handd0a1732021-11-23 15:26:20 +0900950 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100951 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900952 let callbacks = &*self.0.lock().unwrap();
953 for callback in callbacks {
954 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100955 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900956 }
957 }
958 }
959
Andrew Walbrandae07162021-03-12 17:05:20 +0000960 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000961 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000962 let callbacks = &*self.0.lock().unwrap();
963 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000964 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100965 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000966 }
967 }
968 }
969
970 /// Add a new callback to the set.
971 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
972 self.0.lock().unwrap().push(callback);
973 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000974}
975
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000976/// The mutable state of the VirtualizationService. There should only be one instance of this
977/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800978#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000979struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000980 /// The VMs which have been started. When VMs are started a weak reference is added to this list
981 /// while a strong reference is returned to the caller over Binder. Once all copies of the
982 /// Binder client are dropped the weak reference here will become invalid, and will be removed
983 /// from the list opportunistically the next time `add_vm` is called.
984 vms: Vec<Weak<VmInstance>>,
985}
986
987impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000988 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000989 fn vms(&self) -> Vec<Arc<VmInstance>> {
990 // Attempt to upgrade the weak pointers to strong pointers.
991 self.vms.iter().filter_map(Weak::upgrade).collect()
992 }
993
994 /// Add a new VM to the list.
995 fn add_vm(&mut self, vm: Weak<VmInstance>) {
996 // Garbage collect any entries from the stored list which no longer exist.
997 self.vms.retain(|vm| vm.strong_count() > 0);
998
999 // Actually add the new VM.
1000 self.vms.push(vm);
1001 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001002
Jiyong Park8611a6c2021-07-09 18:17:44 +09001003 /// Get a VM that corresponds to the given cid
1004 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1005 self.vms().into_iter().find(|vm| vm.cid == cid)
1006 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001007}
1008
Andrew Walbran6b650662021-09-07 13:13:23 +00001009/// Gets the `VirtualMachineState` of the given `VmInstance`.
1010fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001011 match &*instance.vm_state.lock().unwrap() {
1012 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1013 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001014 PayloadState::Starting => VirtualMachineState::STARTING,
1015 PayloadState::Started => VirtualMachineState::STARTED,
1016 PayloadState::Ready => VirtualMachineState::READY,
1017 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001018 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001019 },
1020 VmState::Dead => VirtualMachineState::DEAD,
1021 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001022 }
1023}
1024
David Brazdilf50c7a62023-04-19 14:22:42 +00001025/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001026pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1027 file.as_ref()
1028 .try_clone()
1029 .context("Failed to clone File from ParcelFileDescriptor")
1030 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
David Brazdilf50c7a62023-04-19 14:22:42 +00001031}
1032
Andrew Walbrand3a84182021-09-07 14:48:52 +00001033/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001034fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001035 file.as_ref().map(clone_file).transpose()
1036}
1037
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001038/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1039fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1040 // SAFETY: ownership is transferred from stream to f
1041 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1042 ParcelFileDescriptor::new(f)
1043}
1044
Jiyong Parkdcf17412022-02-08 15:07:23 +09001045/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001046fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1047 VersionReq::parse(s)
1048 .with_context(|| format!("Invalid platform version requirement {}", s))
1049 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001050}
1051
Jiyong Parked180932023-02-24 19:55:41 +09001052/// Create the empty ramdump file
1053fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1054 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1055 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1056 // owner) for readout.
1057 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001058 let ramdump = File::create(ramdump_path)
1059 .context("Failed to prepare ramdump file")
1060 .with_log()
1061 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001062 Ok(ramdump)
1063}
1064
Nikita Ioffe5776f082023-02-10 21:38:26 +00001065fn is_protected(config: &VirtualMachineConfig) -> bool {
1066 match config {
1067 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1068 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1069 }
1070}
1071
1072fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1073 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001074 return Err(anyhow!("Can't use gdb with protected VMs"))
1075 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001076 }
1077
1078 match config {
1079 VirtualMachineConfig::RawConfig(_) => Ok(()),
1080 VirtualMachineConfig::AppConfig(config) => {
1081 if config.debugLevel != DebugLevel::FULL {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001082 Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1083 .or_binder_exception(ExceptionCode::SECURITY)
Nikita Ioffe5776f082023-02-10 21:38:26 +00001084 } else {
1085 Ok(())
1086 }
1087 }
1088 }
1089}
1090
1091fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1092 match config {
1093 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001094 VirtualMachineConfig::AppConfig(config) => {
1095 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1096 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001097 }
1098}
1099
Inseob Kim0168b462022-12-27 14:54:35 +09001100fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001101 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001102 fd: Option<&ParcelFileDescriptor>,
1103 tag: String,
1104) -> Result<Option<File>, Status> {
1105 if let Some(fd) = fd {
1106 return Ok(Some(clone_file(fd)?));
1107 }
1108
Jaewan Kim61f86142023-03-28 15:12:52 +09001109 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001110 return Ok(None);
1111 };
Inseob Kim0168b462022-12-27 14:54:35 +09001112
Jiyong Park2227eaa2023-08-04 11:59:18 +09001113 let (raw_read_fd, raw_write_fd) =
1114 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001115
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001116 // 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 +09001117 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001118 // 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 +09001119 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1120
1121 std::thread::spawn(move || loop {
1122 let mut buf = vec![];
1123 match reader.read_until(b'\n', &mut buf) {
1124 Ok(0) => {
1125 // EOF
1126 return;
1127 }
1128 Ok(size) => {
1129 if buf[size - 1] == b'\n' {
1130 buf.pop();
1131 }
1132 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1133 }
1134 Err(e) => {
1135 error!("Could not read console pipe: {:?}", e);
1136 return;
1137 }
1138 };
1139 });
1140
1141 Ok(Some(write_fd))
1142}
1143
Jooyung Han35edb8f2021-07-01 16:17:16 +09001144/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1145/// it doesn't require that T implements Clone.
1146enum BorrowedOrOwned<'a, T> {
1147 Borrowed(&'a T),
1148 Owned(T),
1149}
1150
1151impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1152 fn as_ref(&self) -> &T {
1153 match self {
1154 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001155 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001156 }
1157 }
1158}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001159
1160/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1161#[derive(Debug, Default)]
1162struct VirtualMachineService {
1163 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001164 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001165}
1166
1167impl Interface for VirtualMachineService {}
1168
1169impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001170 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1171 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001172 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001173 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001174 vm.update_payload_state(PayloadState::Started)
1175 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001176 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001177
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001178 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1179 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001180 Ok(())
1181 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001182 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001183 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001184 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001185 }
Inseob Kim2444af92021-08-31 01:22:50 +09001186
Inseob Kimc7d28c72021-10-25 14:28:10 +00001187 fn notifyPayloadReady(&self) -> binder::Result<()> {
1188 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001189 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001190 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001191 vm.update_payload_state(PayloadState::Ready)
1192 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001193 vm.callbacks.notify_payload_ready(cid);
1194 Ok(())
1195 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001196 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001197 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001198 }
1199 }
1200
Inseob Kimc7d28c72021-10-25 14:28:10 +00001201 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1202 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001203 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001204 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001205 vm.update_payload_state(PayloadState::Finished)
1206 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001207 vm.callbacks.notify_payload_finished(cid, exit_code);
1208 Ok(())
1209 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001210 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001211 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001212 }
1213 }
1214
Alan Stokes2bead0d2022-09-05 16:58:34 +01001215 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001216 let cid = self.cid;
1217 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001218 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001219 vm.update_payload_state(PayloadState::Finished)
1220 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001221 vm.callbacks.notify_error(cid, error_code, message);
1222 Ok(())
1223 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001224 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001225 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001226 }
1227 }
Alice Wangc2fec932023-02-23 16:24:02 +00001228
1229 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
1230 let cid = self.cid;
1231 let Some(vm) = self.state.lock().unwrap().get_vm(cid) else {
1232 error!("requestCertificate is called from an unknown CID {cid}");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001233 return Err(anyhow!("cannot find a VM with CID {}", cid))
1234 .or_service_specific_exception(-1);
Alice Wangc2fec932023-02-23 16:24:02 +00001235 };
1236 let instance_img_path = vm.temporary_directory.join("rkpvm_instance.img");
1237 let instance_img = OpenOptions::new()
1238 .create(true)
1239 .read(true)
1240 .write(true)
1241 .open(instance_img_path)
Jiyong Park2227eaa2023-08-04 11:59:18 +09001242 .context("Failed to create rkpvm_instance.img file")
1243 .with_log()
1244 .or_service_specific_exception(-1)?;
Alice Wangc2fec932023-02-23 16:24:02 +00001245 GLOBAL_SERVICE.requestCertificate(csr, &ParcelFileDescriptor::new(instance_img))
1246 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001247}
1248
1249impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001250 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001251 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001252 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001253 BinderFeatures::default(),
1254 )
1255 }
1256}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001257
1258#[cfg(test)]
1259mod tests {
1260 use super::*;
1261
1262 #[test]
1263 fn test_is_allowed_label_for_partition() -> Result<()> {
1264 let expected_results = vec![
1265 ("u:object_r:system_file:s0", true),
1266 ("u:object_r:apk_data_file:s0", true),
1267 ("u:object_r:app_data_file:s0", false),
1268 ("u:object_r:app_data_file:s0:c512,c768", false),
1269 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1270 ("invalid", false),
1271 ("user:role:apk_data_file:severity:categories", true),
1272 ("user:role:apk_data_file:severity:categories:extraneous", false),
1273 ];
1274
1275 for (label, expected_valid) in expected_results {
1276 let context = SeContext::new(label)?;
1277 let result = check_label_is_allowed(&context);
1278 if expected_valid {
1279 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1280 } else if result.is_ok() {
1281 bail!("Expected label {} to be disallowed", label);
1282 }
1283 }
1284 Ok(())
1285 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001286
1287 #[test]
1288 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1289 let apk = tempfile::tempfile().unwrap();
1290 let idsig = tempfile::tempfile().unwrap();
1291
1292 let ret = create_or_update_idsig_file(
1293 &ParcelFileDescriptor::new(apk),
1294 &ParcelFileDescriptor::new(idsig),
1295 );
1296 assert!(ret.is_err(), "should fail");
1297 Ok(())
1298 }
1299
1300 #[test]
1301 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1302 let tmp_dir = tempfile::TempDir::new().unwrap();
1303 let apk = File::open(tmp_dir.path()).unwrap();
1304 let idsig = tempfile::tempfile().unwrap();
1305
1306 let ret = create_or_update_idsig_file(
1307 &ParcelFileDescriptor::new(apk),
1308 &ParcelFileDescriptor::new(idsig),
1309 );
1310 assert!(ret.is_err(), "should fail");
1311 Ok(())
1312 }
1313
1314 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1315 /// on ext4 filesystem is passed.
1316 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1317 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1318 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1319 #[test]
1320 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1321 // APEXes are backed by the ext4.
1322 let apk = File::open("/apex/com.android.virt/").unwrap();
1323 let idsig = tempfile::tempfile().unwrap();
1324
1325 let ret = create_or_update_idsig_file(
1326 &ParcelFileDescriptor::new(apk),
1327 &ParcelFileDescriptor::new(idsig),
1328 );
1329 assert!(ret.is_err(), "should fail");
1330 Ok(())
1331 }
Jiyong Park8d192952023-06-26 14:29:51 +09001332
1333 #[test]
1334 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1335 use std::io::Seek;
1336
1337 // Pick any APK
1338 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1339 let mut idsig = tempfile::tempfile().unwrap();
1340
1341 create_or_update_idsig_file(
1342 &ParcelFileDescriptor::new(apk.try_clone()?),
1343 &ParcelFileDescriptor::new(idsig.try_clone()?),
1344 )?;
1345 let modified_orig = idsig.metadata()?.modified()?;
1346 apk.rewind()?;
1347 idsig.rewind()?;
1348
1349 // Call the function again
1350 create_or_update_idsig_file(
1351 &ParcelFileDescriptor::new(apk.try_clone()?),
1352 &ParcelFileDescriptor::new(idsig.try_clone()?),
1353 )?;
1354 let modified_new = idsig.metadata()?.modified()?;
1355 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1356 Ok(())
1357 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001358
1359 #[test]
1360 fn test_append_kernel_param_first_param() {
1361 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1362 append_kernel_param("foo=1", &mut vm_config);
1363 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1364 }
1365
1366 #[test]
1367 fn test_append_kernel_param() {
1368 let mut vm_config =
1369 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1370 append_kernel_param("bar=42", &mut vm_config);
1371 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1372 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001373}