blob: 2603e77508fefa776a4453826aa424f4c939267f [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;
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +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::{
Alice Wang4e3015d2023-10-10 09:35:37 +000027 Certificate::Certificate,
Andrew Walbranc92d35f2022-01-12 12:45:19 +000028 DeathReason::DeathReason,
David Brazdil49f96f52022-12-16 21:29:13 +000029 ErrorCode::ErrorCode,
30};
31use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090032 AssignableDevice::AssignableDevice,
David Brazdil7d1e5ec2023-02-06 17:56:29 +000033 CpuTopology::CpuTopology,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010035 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000036 IVirtualMachineCallback::IVirtualMachineCallback,
37 IVirtualizationService::IVirtualizationService,
Alan Stokes27f3ef02023-09-29 15:09:35 +010038 IVirtualizationService::FEATURE_MULTI_TENANT,
Nikita Ioffe631717e2023-09-05 13:38:07 +010039 IVirtualizationService::FEATURE_VENDOR_MODULES,
Alan Stokes7f27c0d2023-09-07 16:22:58 +010040 IVirtualizationService::FEATURE_DICE_CHANGES,
Keir Frasercdd4b112022-11-24 14:02:25 +000041 MemoryTrimLevel::MemoryTrimLevel,
Jiyong Park029977d2021-11-24 21:56:49 +090042 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000043 PartitionType::PartitionType,
Inseob Kim0168b462022-12-27 14:54:35 +090044 VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
Jooyung Han21e9b922021-06-26 04:14:16 +090045 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000046 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Alan Stokes0d1ef782022-09-27 13:46:35 +010047 VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090048 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000049 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090050};
David Brazdilafc9a9e2023-01-12 16:08:10 +000051use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
Seungjae Yoodd91f0f2022-11-09 15:25:21 +090052use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000053 BnVirtualMachineService, IVirtualMachineService,
Seungjae Yoofd9a0622022-10-14 10:01:29 +090054};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000055use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
56use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
57use android_hardware_security_authgraph::aidl::android::hardware::security::authgraph::{
58 Arc::Arc as AuthgraphArc, IAuthGraphKeyExchange::IAuthGraphKeyExchange,
59 IAuthGraphKeyExchange::BnAuthGraphKeyExchange, Identity::Identity, KeInitResult::KeInitResult,
60 Key::Key, PubKey::PubKey, SessionIdSignature::SessionIdSignature, SessionInfo::SessionInfo,
61 SessionInitiationInfo::SessionInitiationInfo,
62};
Alan Stokes25f69362023-03-06 16:51:54 +000063use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090064use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090065use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010066use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000067 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
68 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090069 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000070};
David Brazdilf50c7a62023-04-19 14:22:42 +000071use disk::QcowFile;
Inseob Kim46257382024-01-03 15:41:22 +090072use glob::glob;
David Brazdil49f96f52022-12-16 21:29:13 +000073use lazy_static::lazy_static;
Seungjae Yooec3bc522023-11-09 10:14:30 +090074use libfdt::Fdt;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000075use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090076use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090077use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000078use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000079use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090080use semver::VersionReq;
Inseob Kim6ef80972023-07-20 17:23:36 +090081use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000082use std::convert::TryInto;
Seungjae Yooec3bc522023-11-09 10:14:30 +090083use std::ffi::{CStr, CString};
Inseob Kim6ef80972023-07-20 17:23:36 +090084use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000085use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Inseob Kim46257382024-01-03 15:41:22 +090086use std::iter;
Nikita Ioffe5776f082023-02-10 21:38:26 +000087use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000088use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000089use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000091use std::sync::{Arc, Mutex, Weak};
Seungjae Yooec3bc522023-11-09 10:14:30 +090092use vbmeta::VbMetaImage;
Andrew Walbrancc0db522021-07-12 17:03:42 +000093use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000094use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090095use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096
David Brazdil41d1a872022-10-05 14:44:19 +010097/// The unique ID of a VM used (together with a port number) for vsock communication.
98pub type Cid = u32;
99
David Brazdil4b4c5102022-12-19 22:56:20 +0000100pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
101
Jooyung Han95884632021-07-06 22:27:54 +0900102/// The size of zero.img.
103/// Gaps in composite disk images are filled with a shared zero.img.
104const ZERO_FILLER_SIZE: u64 = 4096;
105
David Brazdilf50c7a62023-04-19 14:22:42 +0000106/// Magic string for the instance image
107const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
108
109/// Version of the instance image format
110const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
111
Alan Stokes0d1ef782022-09-27 13:46:35 +0100112const MICRODROID_OS_NAME: &str = "microdroid";
113
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000114// TODO(b/291213394): Use 'default' instance for secretkeeper instead of 'nonsecure'
115const SECRETKEEPER_IDENTIFIER: &str =
116 "android.hardware.security.secretkeeper.ISecretkeeper/nonsecure";
117
David Brazdilf50c7a62023-04-19 14:22:42 +0000118const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
119
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900120/// Rough size for storing root digest of vendor hash descriptor into DTBO.
Seungjae Yooec3bc522023-11-09 10:14:30 +0900121const EMPTY_VENDOR_DT_OVERLAY_BUF_SIZE: usize = 10000;
122
David Brazdilf50c7a62023-04-19 14:22:42 +0000123/// crosvm requires all partitions to be a multiple of 4KiB.
124const PARTITION_GRANULARITY_BYTES: u64 = 4096;
125
David Brazdil49f96f52022-12-16 21:29:13 +0000126lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000127 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
128 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
129 .expect("Could not connect to VirtualizationServiceInternal");
Inseob Kim46257382024-01-03 15:41:22 +0900130 static ref SUPPORTED_OS_NAMES: HashSet<String> =
131 get_supported_os_names().expect("Failed to get list of supported os names");
David Brazdil49f96f52022-12-16 21:29:13 +0000132}
133
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000134fn create_or_update_idsig_file(
135 input_fd: &ParcelFileDescriptor,
136 idsig_fd: &ParcelFileDescriptor,
137) -> Result<()> {
138 let mut input = clone_file(input_fd)?;
139 let metadata = input.metadata().context("failed to get input metadata")?;
140 if !metadata.is_file() {
141 bail!("input is not a regular file");
142 }
Alan Stokes25f69362023-03-06 16:51:54 +0000143 let mut sig =
144 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
145 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000146
147 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900148
149 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
150 // if the idsig file already has the same APK digest.
151 if output.metadata()?.len() > 0 {
152 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
153 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
154 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
155 return Ok(());
156 }
157 }
158 // if we fail to read v4signature from output, that's fine. User can pass a random file.
159 // We will anyway overwrite the file to the v4signature generated from input_fd.
160 }
161
Nikita Ioffec09b0492022-12-14 20:18:33 +0000162 output.set_len(0).context("failed to set_len on the idsig output")?;
163 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000164 Ok(())
165}
166
Alan Stokes25f69362023-03-06 16:51:54 +0000167fn get_current_sdk() -> Result<u32> {
168 let current_sdk = system_properties::read("ro.build.version.sdk")?;
169 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
170 current_sdk.parse().context("Malformed SDK version")
171}
172
David Brazdil4b4c5102022-12-19 22:56:20 +0000173pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
174 for dir_entry in read_dir(path)? {
175 remove_file(dir_entry?.path())?;
176 }
177 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100178}
179
David Brazdil528e0472022-10-10 15:06:02 +0100180/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000181#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000182pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900183 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000184}
185
Shikha Panward8e35422021-10-11 13:51:27 +0000186impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000187 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000188 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
189 let state = &mut *self.state.lock().unwrap();
190 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000191 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000192 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000193 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
194 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000195 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000196 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000197 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000198 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
199 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000200 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000201 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000202 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000203 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000204 .or(Err(StatusCode::UNKNOWN_ERROR))?;
205 }
206 Ok(())
207 }
208}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000209impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000210 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
211 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000212 ///
213 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000214 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000215 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000216 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900217 console_out_fd: Option<&ParcelFileDescriptor>,
218 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000219 log_fd: Option<&ParcelFileDescriptor>,
220 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000221 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900222 let ret = self.create_vm_internal(
223 config,
224 console_out_fd,
225 console_in_fd,
226 log_fd,
227 &mut is_protected,
228 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000229 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000230 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000231 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000232
Andrew Walbrandff3b942021-06-09 15:20:36 +0000233 /// Initialise an empty partition image of the given size to be used as a writable partition.
234 fn initializeWritablePartition(
235 &self,
236 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000237 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900238 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000239 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900240 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900241 let size_bytes = size_bytes
242 .try_into()
243 .with_context(|| format!("Invalid size: {}", size_bytes))
244 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000245 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
246 let image = clone_file(image_fd)?;
247 // initialize the file. Any data in the file will be erased.
Jiyong Park2227eaa2023-08-04 11:59:18 +0900248 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
249 let mut part = QcowFile::new(image, size_bytes)
250 .context("Failed to create QCOW2 image")
251 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000252
253 match partition_type {
254 PartitionType::RAW => Ok(()),
255 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
256 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
257 _ => Err(Error::new(
258 ErrorKind::Unsupported,
259 format!("Unsupported partition type {:?}", partition_type),
260 )),
261 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900262 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
263 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000264
265 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000266 }
267
Jiyong Park0a248432021-08-20 23:32:39 +0900268 /// Creates or update the idsig file by digesting the input APK file.
269 fn createOrUpdateIdsigFile(
270 &self,
271 input_fd: &ParcelFileDescriptor,
272 idsig_fd: &ParcelFileDescriptor,
273 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900274 check_manage_access()?;
275
Jiyong Park2227eaa2023-08-04 11:59:18 +0900276 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900277 Ok(())
278 }
279
Andrew Walbran320b5602021-03-04 16:11:12 +0000280 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
281 /// and as such is only permitted from the shell user.
282 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000283 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000284 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000285 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900286
287 /// Get a list of assignable device types.
288 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
289 // Delegate to the global service, including checking the permission.
290 GLOBAL_SERVICE.getAssignableDevices()
291 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100292
Inseob Kim46257382024-01-03 15:41:22 +0900293 /// Get a list of supported OSes.
294 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
295 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
296 }
297
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100298 /// Returns whether given feature is enabled
299 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
300 check_manage_access()?;
301
302 // This approach is quite cumbersome, but will do the work for the short term.
303 // TODO(b/298012279): make this scalable.
304 match feature {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100305 FEATURE_DICE_CHANGES => Ok(cfg!(dice_changes)),
Alan Stokes27f3ef02023-09-29 15:09:35 +0100306 FEATURE_MULTI_TENANT => Ok(cfg!(multi_tenant)),
Nikita Ioffe631717e2023-09-05 13:38:07 +0100307 FEATURE_VENDOR_MODULES => Ok(cfg!(vendor_modules)),
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100308 _ => {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100309 warn!("unknown feature {feature}");
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100310 Ok(false)
311 }
312 }
313 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000314}
315
Jiyong Park8611a6c2021-07-09 18:17:44 +0900316impl VirtualizationService {
317 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000318 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900319 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000320
David Brazdil209074a2023-01-12 16:44:51 +0000321 fn create_vm_context(
322 &self,
323 requester_debug_pid: pid_t,
324 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000325 const NUM_ATTEMPTS: usize = 5;
326
327 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000328 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000329 let cid = vm_context.getCid()? as Cid;
330 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000331 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
332
333 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000334 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000335 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000336 Ok(vm_server) => {
337 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000338 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000339 }
340 Err(err) => {
341 warn!("Could not start RpcServer on port {}: {}", port, err);
342 }
343 }
344 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900345 Err(anyhow!("Too many attempts to create VM context failed"))
346 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000347 }
348
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000349 fn create_vm_internal(
350 &self,
351 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900352 console_out_fd: Option<&ParcelFileDescriptor>,
353 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000354 log_fd: Option<&ParcelFileDescriptor>,
355 is_protected: &mut bool,
356 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000357 let requester_uid = get_calling_uid();
358 let requester_debug_pid = get_calling_pid();
359
Nikita Ioffe631717e2023-09-05 13:38:07 +0100360 check_config_features(config)?;
361
David Brazdil209074a2023-01-12 16:44:51 +0000362 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
363 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900364
Alan Stokes7bc146c2022-10-20 17:10:32 +0100365 let is_custom = match config {
366 VirtualMachineConfig::RawConfig(_) => true,
367 VirtualMachineConfig::AppConfig(config) => {
368 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100369 // VirtualMachineAppConfig. Almost all of these features are grouped in the
370 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100371 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100372 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100373 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900374 // - using anything other than the default kernel;
375 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100376 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900377 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100378 };
379 if is_custom {
380 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900381 }
382
Nikita Ioffe5776f082023-02-10 21:38:26 +0000383 let gdb_port = extract_gdb_port(config);
384
385 // Additional permission checks if caller request gdb.
386 if gdb_port.is_some() {
387 check_gdb_allowed(config)?;
388 }
389
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900390 let vendor_hashtree_descriptor_root_digest =
391 extract_vendor_hashtree_descriptor_root_digest(config)
392 .context("Failed to extract root digest of vendor")
393 .or_service_specific_exception(-1)?;
394 let dtbo_vendor = if let Some(vendor_hashtree_descriptor_root_digest) =
395 vendor_hashtree_descriptor_root_digest
396 {
397 let root_digest_hex = hex::encode(vendor_hashtree_descriptor_root_digest);
Seungjae Yooec3bc522023-11-09 10:14:30 +0900398 let dtbo_for_vendor_image = temporary_directory.join("dtbo_vendor");
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900399 create_dtbo_for_vendor_image(root_digest_hex.as_bytes(), &dtbo_for_vendor_image)
400 .context("Failed to write root digest of vendor")
Seungjae Yooec3bc522023-11-09 10:14:30 +0900401 .or_service_specific_exception(-1)?;
402 let file = File::open(dtbo_for_vendor_image)
403 .context("Failed to open dtbo_vendor")
404 .or_service_specific_exception(-1)?;
405 Some(file)
406 } else {
407 None
408 };
409
Jaewan Kim61f86142023-03-28 15:12:52 +0900410 let debug_level = match config {
411 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
412 _ => DebugLevel::NONE,
413 };
414 let debug_config = DebugConfig::new(debug_level);
415
416 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900417 Some(prepare_ramdump_file(&temporary_directory)?)
418 } else {
419 None
420 };
421
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000422 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900423 let console_out_fd =
424 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
425 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900426 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000427
428 // Counter to generate unique IDs for temporary image files.
429 let mut next_temporary_image_id = 0;
430 // Files which are referred to from composite images. These must be mapped to the crosvm
431 // child process, and not closed before it is started.
432 let mut indirect_files = vec![];
433
Alan Stokes7bc146c2022-10-20 17:10:32 +0100434 let (is_app_config, config) = match config {
435 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
436 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900437 let config = load_app_config(config, &debug_config, &temporary_directory)
438 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900439 *is_protected = config.protectedVm;
440 let message = format!("Failed to load app config: {:?}", e);
441 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900442 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900443 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100444 (true, BorrowedOrOwned::Owned(config))
445 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000446 };
447 let config = config.as_ref();
448 *is_protected = config.protectedVm;
449
450 // Check if partition images are labeled incorrectly. This is to prevent random images
451 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100452 // being loaded in a pVM. This applies to everything but the instance image in the raw
453 // config, and everything but the non-executable, generated partitions in the app
454 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000455 config
456 .disks
457 .iter()
458 .flat_map(|disk| disk.partitions.iter())
459 .filter(|partition| {
460 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100461 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000462 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000463 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000464 }
465 })
466 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900467 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000468
Alan Stokes185fe112023-01-10 16:20:55 +0000469 let kernel = maybe_clone_file(&config.kernel)?;
470 let initrd = maybe_clone_file(&config.initrd)?;
471
472 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
473 if config.protectedVm {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900474 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Alan Stokes185fe112023-01-10 16:20:55 +0000475 }
476
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000477 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900478 write_zero_filler(&zero_filler_path)
479 .context("Failed to make composite image")
480 .with_log()
481 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000482
483 // Assemble disk images if needed.
484 let disks = config
485 .disks
486 .iter()
487 .map(|disk| {
488 assemble_disk_image(
489 disk,
490 &zero_filler_path,
491 &temporary_directory,
492 &mut next_temporary_image_id,
493 &mut indirect_files,
494 )
495 })
496 .collect::<Result<Vec<DiskFile>, _>>()?;
497
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000498 let (cpus, host_cpu_topology) = match config.cpuTopology {
499 CpuTopology::MATCH_HOST => (None, true),
500 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
501 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900502 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
503 .with_log()
504 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000505 }
506 };
507
David Brazdil2dfefd12023-11-17 14:07:36 +0000508 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900509 let mut set = HashSet::new();
510 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900511 let path = canonicalize(device)
512 .with_context(|| format!("can't canonicalize {device}"))
513 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900514 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900515 return Err(anyhow!("duplicated device {device}"))
516 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900517 }
518 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000519 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000520 let dtbo_file = File::from(
521 GLOBAL_SERVICE
522 .getDtboFile()?
523 .as_ref()
524 .try_clone()
525 .context("Failed to create File from ParcelFileDescriptor")
526 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
527 );
528 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900529 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000530 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900531 };
Inseob Kim6ef80972023-07-20 17:23:36 +0900532
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000533 // Actually start the VM.
534 let crosvm_config = CrosvmConfig {
535 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000536 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000537 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000538 kernel,
539 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000540 disks,
541 params: config.params.to_owned(),
542 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900543 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000544 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000545 cpus,
546 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900547 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900548 console_out_fd,
549 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000550 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900551 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000552 indirect_files,
553 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900554 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000555 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900556 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000557 dtbo,
Seungjae Yooec3bc522023-11-09 10:14:30 +0900558 dtbo_vendor,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000559 };
560 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100561 VmInstance::new(
562 crosvm_config,
563 temporary_directory,
564 requester_uid,
565 requester_debug_pid,
566 vm_context,
567 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900568 .with_context(|| format!("Failed to create VM with config {:?}", config))
569 .with_log()
570 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000571 );
572 state.add_vm(Arc::downgrade(&instance));
573 Ok(VirtualMachine::create(instance))
574 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900575}
576
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900577fn extract_vendor_hashtree_descriptor_root_digest(
578 config: &VirtualMachineConfig,
579) -> Result<Option<Vec<u8>>> {
Seungjae Yooec3bc522023-11-09 10:14:30 +0900580 let VirtualMachineConfig::AppConfig(config) = config else {
581 return Ok(None);
582 };
583 let Some(custom_config) = &config.customConfig else {
584 return Ok(None);
585 };
586 let Some(file) = custom_config.vendorImage.as_ref() else {
587 return Ok(None);
588 };
589
590 let file = clone_file(file)?;
591 let size = file.metadata().context("Failed to get metadata from microdroid-vendor.img")?.len();
592 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
593 .context("Failed to get vbmeta from microdroid-vendor.img")?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900594
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900595 for descriptor in vbmeta.descriptors()?.iter() {
596 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
597 return Ok(Some(descriptor.to_hashtree()?.root_digest().to_vec()));
598 }
599 }
600 Err(anyhow!("No root digest is extracted from microdroid-vendor.img"))
Seungjae Yooec3bc522023-11-09 10:14:30 +0900601}
602
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900603fn create_dtbo_for_vendor_image(
604 vendor_hashtree_descriptor_root_digest: &[u8],
605 dtbo: &PathBuf,
606) -> Result<()> {
Seungjae Yooec3bc522023-11-09 10:14:30 +0900607 if dtbo.exists() {
608 return Err(anyhow!("DTBO file already exists"));
609 }
610
611 let mut buf = vec![0; EMPTY_VENDOR_DT_OVERLAY_BUF_SIZE];
612 let fdt = Fdt::create_empty_tree(buf.as_mut_slice())
613 .map_err(|e| anyhow!("Failed to create FDT: {:?}", e))?;
614 let mut root = fdt.root_mut().map_err(|e| anyhow!("Failed to get root node: {:?}", e))?;
615
616 let fragment_node_name = CString::new("fragment@0")?;
617 let mut fragment_node = root
618 .add_subnode(fragment_node_name.as_c_str())
619 .map_err(|e| anyhow!("Failed to create fragment node: {:?}", e))?;
620 let target_path_prop_name = CString::new("target-path")?;
621 let target_path = CString::new("/")?;
622 fragment_node
623 .setprop(target_path_prop_name.as_c_str(), target_path.to_bytes_with_nul())
624 .map_err(|e| anyhow!("Failed to set target-path: {:?}", e))?;
625 let overlay_node_name = CString::new("__overlay__")?;
626 let mut overlay_node = fragment_node
627 .add_subnode(overlay_node_name.as_c_str())
628 .map_err(|e| anyhow!("Failed to create overlay node: {:?}", e))?;
629
630 let avf_node_name = CString::new("avf")?;
631 let mut avf_node = overlay_node
632 .add_subnode(avf_node_name.as_c_str())
633 .map_err(|e| anyhow!("Failed to create avf node: {:?}", e))?;
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900634 let vendor_hashtree_descriptor_root_digest_name =
635 CString::new("vendor_hashtree_descriptor_root_digest")?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900636 avf_node
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900637 .setprop(
638 vendor_hashtree_descriptor_root_digest_name.as_c_str(),
639 vendor_hashtree_descriptor_root_digest,
640 )
641 .map_err(|e| {
642 anyhow!("Failed to set avf/vendor_hashtree_descriptor_root_digest: {:?}", e)
643 })?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900644
645 fdt.pack().map_err(|e| anyhow!("Failed to pack fdt: {:?}", e))?;
646 let mut file = File::create(dtbo)?;
647 file.write_all(fdt.as_slice())?;
648 Ok(file.flush()?)
649}
650
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000651fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900652 let file = OpenOptions::new()
653 .create_new(true)
654 .read(true)
655 .write(true)
656 .open(zero_filler_path)
657 .with_context(|| "Failed to create zero.img")?;
658 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000659 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900660}
661
David Brazdilf50c7a62023-04-19 14:22:42 +0000662fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
663 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
664 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
665 part.flush()
666}
667
668fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
669 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
670 part.flush()
671}
672
673fn round_up(input: u64, granularity: u64) -> u64 {
674 if granularity == 0 {
675 return input;
676 }
677 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
678 let result = input.checked_add(granularity - 1).unwrap_or(input);
679 (result / granularity) * granularity
680}
681
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000682/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
683///
684/// This may involve assembling a composite disk from a set of partition images.
685fn assemble_disk_image(
686 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900687 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000688 temporary_directory: &Path,
689 next_temporary_image_id: &mut u64,
690 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000691) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000692 let image = if !disk.partitions.is_empty() {
693 if disk.image.is_some() {
694 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900695 return Err(anyhow!("DiskImage contains both image and partitions"))
696 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000697 }
698
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000699 let composite_image_filenames =
700 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
701 let (image, partition_files) = make_composite_image(
702 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900703 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000704 &composite_image_filenames.composite,
705 &composite_image_filenames.header,
706 &composite_image_filenames.footer,
707 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900708 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
709 .with_log()
710 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000711
712 // Pass the file descriptors for the various partition files to crosvm when it
713 // is run.
714 indirect_files.extend(partition_files);
715
716 image
717 } else if let Some(image) = &disk.image {
718 clone_file(image)?
719 } else {
720 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900721 return Err(anyhow!("DiskImage didn't contain image or partitions."))
722 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000723 };
724
725 Ok(DiskFile { image, writable: disk.writable })
726}
727
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100728fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
729 if let Some(ref mut params) = vm_config.params {
730 params.push(' ');
731 params.push_str(param)
732 } else {
733 vm_config.params = Some(param.to_owned())
734 }
735}
736
Inseob Kim46257382024-01-03 15:41:22 +0900737fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
738 if config.extension()?.to_str()? != "json" {
739 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +0900740 }
Inseob Kim46257382024-01-03 15:41:22 +0900741
742 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
743}
744
745fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
746 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
747 let os_names =
748 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
749
750 Ok(os_names)
751}
752
753fn get_supported_os_names() -> Result<HashSet<String>> {
754 if !cfg!(vendor_modules) {
755 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
756 }
757
758 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
759}
760
761fn is_valid_os(os_name: &str) -> bool {
762 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +0900763}
764
Jooyung Han21e9b922021-06-26 04:14:16 +0900765fn load_app_config(
766 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900767 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900768 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900769) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000770 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
771 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900772 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900773
Shikha Panwar22e70452022-10-10 18:32:55 +0000774 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
775 Some(clone_file(file)?)
776 } else {
777 None
778 };
779
Alan Stokes0d1ef782022-09-27 13:46:35 +0100780 let vm_payload_config = match &config.payload {
781 Payload::ConfigPath(config_path) => {
782 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
783 .with_context(|| format!("Couldn't read config from {}", config_path))?
784 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000785 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100786 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900787
Inseob Kim172f9eb2023-11-06 17:02:08 +0900788 // For now, the only supported OS is Microdroid and Microdroid GKI
Alan Stokes0d1ef782022-09-27 13:46:35 +0100789 let os_name = vm_payload_config.os.name.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +0900790 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000791 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900792 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000793
794 // It is safe to construct a filename based on the os_name because we've already checked that it
795 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900796 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
797 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000798 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900799
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100800 if let Some(custom_config) = &config.customConfig {
801 if let Some(file) = custom_config.customKernelImage.as_ref() {
802 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
803 }
804 vm_config.taskProfiles = custom_config.taskProfiles.clone();
805 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100806
807 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100808 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
809 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100810 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900811
812 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100813 }
814
Andrew Walbrancc045902021-07-27 16:06:17 +0000815 if config.memoryMib > 0 {
816 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000817 }
818
Seungjae Yoo62085c02022-08-12 04:44:52 +0000819 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000820 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000821 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900822
Shikha Panwar22e70452022-10-10 18:32:55 +0000823 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +0900824 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +0000825
826 // Include Microdroid payload disk (contains apks, idsigs) in vm config
827 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100828 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900829 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100830 temporary_directory,
831 apk_file,
832 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100833 &vm_payload_config,
834 &mut vm_config,
835 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900836
Andrew Walbrancc0db522021-07-12 17:03:42 +0000837 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900838}
839
Alan Stokes0d1ef782022-09-27 13:46:35 +0100840fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
841 let mut apk_zip = ZipArchive::new(apk_file)?;
842 let config_file = apk_zip.by_name(config_path)?;
843 Ok(serde_json::from_reader(config_file)?)
844}
845
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000846fn create_vm_payload_config(
847 payload_config: &VirtualMachinePayloadConfig,
848) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100849 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
850 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
851 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000852
853 let payload_binary_name = &payload_config.payloadBinaryName;
854 if payload_binary_name.contains('/') {
855 bail!("Payload binary name must not specify a path: {payload_binary_name}");
856 }
857
858 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Inseob Kim172f9eb2023-11-06 17:02:08 +0900859 let name = payload_config.osName.clone();
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000860 Ok(VmPayloadConfig {
Inseob Kim172f9eb2023-11-06 17:02:08 +0900861 os: OsConfig { name },
Alan Stokes0d1ef782022-09-27 13:46:35 +0100862 task: Some(task),
863 apexes: vec![],
864 extra_apks: vec![],
865 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900866 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100867 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000868 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100869}
870
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000871/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000872fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000873 temporary_directory: &Path,
874 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000875) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000876 let id = *next_temporary_image_id;
877 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000878 CompositeImageFilenames {
879 composite: temporary_directory.join(format!("composite-{}.img", id)),
880 header: temporary_directory.join(format!("composite-{}-header.img", id)),
881 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
882 }
883}
884
885/// Filenames for a composite disk image, including header and footer partitions.
886#[derive(Clone, Debug, Eq, PartialEq)]
887struct CompositeImageFilenames {
888 /// The composite disk image itself.
889 composite: PathBuf,
890 /// The header partition image.
891 header: PathBuf,
892 /// The footer partition image.
893 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000894}
895
Jiyong Park753553b2021-07-12 21:21:09 +0900896/// Checks whether the caller has a specific permission
897fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100898 let calling_pid = get_calling_pid();
899 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900900 // Root can do anything
901 if calling_uid == 0 {
902 return Ok(());
903 }
904 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
905 binder::get_interface("permission")?;
906 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000907 Ok(())
908 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900909 Err(anyhow!("does not have the {} permission", perm))
910 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000911 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000912}
913
Jiyong Park753553b2021-07-12 21:21:09 +0900914/// Check whether the caller of the current Binder method is allowed to manage VMs
915fn check_manage_access() -> binder::Result<()> {
916 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
917}
918
Inseob Kim1119d702022-05-02 18:01:58 +0900919/// Check whether the caller of the current Binder method is allowed to create custom VMs
920fn check_use_custom_virtual_machine() -> binder::Result<()> {
921 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
922}
923
Alan Stokes185fe112023-01-10 16:20:55 +0000924/// Return whether a partition is exempt from selinux label checks, because we know that it does
925/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100926fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000927 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100928 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000929 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100930 || label == "microdroid-apk-idsig"
931 || label == "payload-metadata"
932 || label.starts_with("extra-idsig-")
933}
934
Alice Wangc206b9b2023-08-28 14:13:51 +0000935/// Returns whether a partition with the given label is safe for a raw config VM.
936fn is_safe_raw_partition(label: &str) -> bool {
937 label == "vm-instance"
938}
939
Alan Stokes185fe112023-01-10 16:20:55 +0000940/// Check that a file SELinux label is acceptable.
941///
942/// We only want to allow code in a VM to be sourced from places that apps, and the
Seungjae Yoo2b74c442023-11-15 18:05:07 +0900943/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +0000944///
945/// Note that sepolicy must also grant read access for these types to both virtualization
946/// service and crosvm.
947///
948/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
949/// user devices (W^X).
950fn check_label_is_allowed(context: &SeContext) -> Result<()> {
951 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100952 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100953 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000954 | "staging_data_file" // updated/staged APEX images
955 | "system_file" // immutable dm-verity protected partition
956 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +0900957 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100958 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000959 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900960 }
961}
962
Alan Stokes185fe112023-01-10 16:20:55 +0000963fn check_label_for_partition(partition: &Partition) -> Result<()> {
964 let file = partition.image.as_ref().unwrap().as_ref();
965 check_label_is_allowed(&getfilecon(file)?)
966 .with_context(|| format!("Partition {} invalid", &partition.label))
967}
968
969fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
970 if let Some(f) = kernel {
971 check_label_for_file(f, "kernel")?;
972 }
973 if let Some(f) = initrd {
974 check_label_for_file(f, "initrd")?;
975 }
976 Ok(())
977}
978fn check_label_for_file(file: &File, name: &str) -> Result<()> {
979 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
980}
981
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000982/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
983#[derive(Debug)]
984struct VirtualMachine {
985 instance: Arc<VmInstance>,
986}
987
988impl VirtualMachine {
989 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000990 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000991 }
992}
993
994impl Interface for VirtualMachine {}
995
996impl IVirtualMachine for VirtualMachine {
997 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900998 // Don't check permission. The owner of the VM might have passed this binder object to
999 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001000 Ok(self.instance.cid as i32)
1001 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001002
Andrew Walbran6b650662021-09-07 13:13:23 +00001003 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001004 // Don't check permission. The owner of the VM might have passed this binder object to
1005 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001006 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001007 }
1008
1009 fn registerCallback(
1010 &self,
1011 callback: &Strong<dyn IVirtualMachineCallback>,
1012 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001013 // Don't check permission. The owner of the VM might have passed this binder object to
1014 // others.
1015 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001016 // TODO: Should this give an error if the VM is already dead?
1017 self.instance.callbacks.add(callback.clone());
1018 Ok(())
1019 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001020
Andrew Walbranf8d94112021-09-07 11:45:36 +00001021 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001022 self.instance
1023 .start()
1024 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1025 .with_log()
1026 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001027 }
1028
Inseob Kima446f802022-07-11 19:46:37 +09001029 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001030 self.instance
1031 .kill()
1032 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1033 .with_log()
1034 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001035 }
1036
Keir Frasercdd4b112022-11-24 14:02:25 +00001037 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001038 self.instance
1039 .trim_memory(level)
1040 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
1041 .with_log()
1042 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001043 }
1044
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001045 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001046 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001047 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001048 }
Alan Stokes10c47672022-12-13 17:17:08 +00001049 let port = port as u32;
1050 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001051 return Err(anyhow!("Can't connect to privileged port {port}"))
1052 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +00001053 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001054 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1055 .context("Failed to connect")
1056 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001057 Ok(vsock_stream_to_pfd(stream))
1058 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001059}
1060
1061impl Drop for VirtualMachine {
1062 fn drop(&mut self) {
1063 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001064 if let Err(e) = self.instance.kill() {
1065 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1066 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001067 }
1068}
1069
1070/// A set of Binders to be called back in response to various events on the VM, such as when it
1071/// dies.
1072#[derive(Debug, Default)]
1073pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1074
1075impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001076 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001077 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001078 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001079 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001080 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001081 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001082 }
1083 }
1084 }
1085
Inseob Kim14cb8692021-08-31 21:50:39 +09001086 /// Call all registered callbacks to notify that the payload is ready to serve.
1087 pub fn notify_payload_ready(&self, cid: Cid) {
1088 let callbacks = &*self.0.lock().unwrap();
1089 for callback in callbacks {
1090 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001091 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001092 }
1093 }
1094 }
1095
Inseob Kim2444af92021-08-31 01:22:50 +09001096 /// Call all registered callbacks to notify that the payload has finished.
1097 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1098 let callbacks = &*self.0.lock().unwrap();
1099 for callback in callbacks {
1100 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001101 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001102 }
1103 }
1104 }
1105
Jooyung Handd0a1732021-11-23 15:26:20 +09001106 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001107 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001108 let callbacks = &*self.0.lock().unwrap();
1109 for callback in callbacks {
1110 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001111 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001112 }
1113 }
1114 }
1115
Andrew Walbrandae07162021-03-12 17:05:20 +00001116 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001117 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001118 let callbacks = &*self.0.lock().unwrap();
1119 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001120 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001121 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001122 }
1123 }
1124 }
1125
1126 /// Add a new callback to the set.
1127 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1128 self.0.lock().unwrap().push(callback);
1129 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001130}
1131
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001132/// The mutable state of the VirtualizationService. There should only be one instance of this
1133/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001134#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001135struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001136 /// The VMs which have been started. When VMs are started a weak reference is added to this
1137 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1138 /// the Binder client are dropped the weak reference here will become invalid, and will be
1139 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001140 vms: Vec<Weak<VmInstance>>,
1141}
1142
1143impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001144 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001145 fn vms(&self) -> Vec<Arc<VmInstance>> {
1146 // Attempt to upgrade the weak pointers to strong pointers.
1147 self.vms.iter().filter_map(Weak::upgrade).collect()
1148 }
1149
1150 /// Add a new VM to the list.
1151 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1152 // Garbage collect any entries from the stored list which no longer exist.
1153 self.vms.retain(|vm| vm.strong_count() > 0);
1154
1155 // Actually add the new VM.
1156 self.vms.push(vm);
1157 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001158
Jiyong Park8611a6c2021-07-09 18:17:44 +09001159 /// Get a VM that corresponds to the given cid
1160 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1161 self.vms().into_iter().find(|vm| vm.cid == cid)
1162 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001163}
1164
Andrew Walbran6b650662021-09-07 13:13:23 +00001165/// Gets the `VirtualMachineState` of the given `VmInstance`.
1166fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001167 match &*instance.vm_state.lock().unwrap() {
1168 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1169 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001170 PayloadState::Starting => VirtualMachineState::STARTING,
1171 PayloadState::Started => VirtualMachineState::STARTED,
1172 PayloadState::Ready => VirtualMachineState::READY,
1173 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001174 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001175 },
1176 VmState::Dead => VirtualMachineState::DEAD,
1177 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001178 }
1179}
1180
David Brazdilf50c7a62023-04-19 14:22:42 +00001181/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001182pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1183 file.as_ref()
1184 .try_clone()
1185 .context("Failed to clone File from ParcelFileDescriptor")
1186 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001187 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001188}
1189
Andrew Walbrand3a84182021-09-07 14:48:52 +00001190/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001191fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001192 file.as_ref().map(clone_file).transpose()
1193}
1194
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001195/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1196fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1197 // SAFETY: ownership is transferred from stream to f
1198 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1199 ParcelFileDescriptor::new(f)
1200}
1201
Jiyong Parkdcf17412022-02-08 15:07:23 +09001202/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001203fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1204 VersionReq::parse(s)
1205 .with_context(|| format!("Invalid platform version requirement {}", s))
1206 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001207}
1208
Jiyong Parked180932023-02-24 19:55:41 +09001209/// Create the empty ramdump file
1210fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1211 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1212 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1213 // owner) for readout.
1214 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001215 let ramdump = File::create(ramdump_path)
1216 .context("Failed to prepare ramdump file")
1217 .with_log()
1218 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001219 Ok(ramdump)
1220}
1221
Nikita Ioffe5776f082023-02-10 21:38:26 +00001222fn is_protected(config: &VirtualMachineConfig) -> bool {
1223 match config {
1224 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1225 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1226 }
1227}
1228
1229fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1230 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001231 return Err(anyhow!("Can't use gdb with protected VMs"))
1232 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001233 }
1234
1235 match config {
1236 VirtualMachineConfig::RawConfig(_) => Ok(()),
1237 VirtualMachineConfig::AppConfig(config) => {
1238 if config.debugLevel != DebugLevel::FULL {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001239 Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1240 .or_binder_exception(ExceptionCode::SECURITY)
Nikita Ioffe5776f082023-02-10 21:38:26 +00001241 } else {
1242 Ok(())
1243 }
1244 }
1245 }
1246}
1247
1248fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1249 match config {
1250 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001251 VirtualMachineConfig::AppConfig(config) => {
1252 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1253 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001254 }
1255}
1256
Nikita Ioffe631717e2023-09-05 13:38:07 +01001257fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1258 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1259 if let Some(custom_config) = &config.customConfig {
1260 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1261 return Err(anyhow!("vendor modules feature is disabled"))
1262 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1263 }
1264 }
1265 Ok(())
1266}
1267
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001268fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1269 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1270 if let Some(custom_config) = &config.customConfig {
1271 if !custom_config.devices.is_empty() {
1272 return Err(anyhow!("device assignment feature is disabled"))
1273 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1274 }
1275 }
1276 Ok(())
1277}
1278
Nikita Ioffe631717e2023-09-05 13:38:07 +01001279fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1280 if !cfg!(vendor_modules) {
1281 check_no_vendor_modules(config)?;
1282 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001283 if !cfg!(device_assignment) {
1284 check_no_devices(config)?;
1285 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001286 Ok(())
1287}
1288
Inseob Kim0168b462022-12-27 14:54:35 +09001289fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001290 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001291 fd: Option<&ParcelFileDescriptor>,
1292 tag: String,
1293) -> Result<Option<File>, Status> {
1294 if let Some(fd) = fd {
1295 return Ok(Some(clone_file(fd)?));
1296 }
1297
Jaewan Kim61f86142023-03-28 15:12:52 +09001298 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001299 return Ok(None);
1300 };
Inseob Kim0168b462022-12-27 14:54:35 +09001301
Jiyong Park2227eaa2023-08-04 11:59:18 +09001302 let (raw_read_fd, raw_write_fd) =
1303 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001304
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001305 // 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 +09001306 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001307 // 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 +09001308 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1309
1310 std::thread::spawn(move || loop {
1311 let mut buf = vec![];
1312 match reader.read_until(b'\n', &mut buf) {
1313 Ok(0) => {
1314 // EOF
1315 return;
1316 }
1317 Ok(size) => {
1318 if buf[size - 1] == b'\n' {
1319 buf.pop();
1320 }
1321 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1322 }
1323 Err(e) => {
1324 error!("Could not read console pipe: {:?}", e);
1325 return;
1326 }
1327 };
1328 });
1329
1330 Ok(Some(write_fd))
1331}
1332
Jooyung Han35edb8f2021-07-01 16:17:16 +09001333/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1334/// it doesn't require that T implements Clone.
1335enum BorrowedOrOwned<'a, T> {
1336 Borrowed(&'a T),
1337 Owned(T),
1338}
1339
1340impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1341 fn as_ref(&self) -> &T {
1342 match self {
1343 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001344 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001345 }
1346 }
1347}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001348
1349/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1350#[derive(Debug, Default)]
1351struct VirtualMachineService {
1352 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001353 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001354}
1355
1356impl Interface for VirtualMachineService {}
1357
1358impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001359 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1360 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001361 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001362 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001363 vm.update_payload_state(PayloadState::Started)
1364 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001365 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001366
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001367 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1368 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001369 Ok(())
1370 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001371 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001372 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001373 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001374 }
Inseob Kim2444af92021-08-31 01:22:50 +09001375
Inseob Kimc7d28c72021-10-25 14:28:10 +00001376 fn notifyPayloadReady(&self) -> binder::Result<()> {
1377 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001378 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001379 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001380 vm.update_payload_state(PayloadState::Ready)
1381 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001382 vm.callbacks.notify_payload_ready(cid);
1383 Ok(())
1384 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001385 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001386 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001387 }
1388 }
1389
Inseob Kimc7d28c72021-10-25 14:28:10 +00001390 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1391 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001392 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001393 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001394 vm.update_payload_state(PayloadState::Finished)
1395 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001396 vm.callbacks.notify_payload_finished(cid, exit_code);
1397 Ok(())
1398 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001399 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001400 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001401 }
1402 }
1403
Alan Stokes2bead0d2022-09-05 16:58:34 +01001404 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001405 let cid = self.cid;
1406 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001407 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001408 vm.update_payload_state(PayloadState::Finished)
1409 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001410 vm.callbacks.notify_error(cid, error_code, message);
1411 Ok(())
1412 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001413 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001414 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001415 }
1416 }
Alice Wangc2fec932023-02-23 16:24:02 +00001417
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001418 fn getSecretkeeper(&self) -> binder::Result<Option<Strong<dyn ISecretkeeper>>> {
Shikha Panwar8187ca22024-01-04 08:33:08 +00001419 let sk = if is_secretkeeper_present() {
1420 Some(binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?)
1421 } else {
1422 None
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001423 };
Shikha Panwar8187ca22024-01-04 08:33:08 +00001424 Ok(sk.map(|s| BnSecretkeeper::new_binder(SecretkeeperProxy(s), BinderFeatures::default())))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001425 }
1426
Alice Wang4e3015d2023-10-10 09:35:37 +00001427 fn requestAttestation(&self, csr: &[u8]) -> binder::Result<Vec<Certificate>> {
Alice Wangbff017f2023-11-09 14:43:28 +00001428 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32)
Alice Wangc2fec932023-02-23 16:24:02 +00001429 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001430}
1431
Shikha Panwar8187ca22024-01-04 08:33:08 +00001432fn is_secretkeeper_present() -> bool {
1433 binder::is_declared(SECRETKEEPER_IDENTIFIER)
1434 .expect("Could not check for declared Secretkeeper interface")
1435}
1436
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001437impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001438 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001439 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001440 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001441 BinderFeatures::default(),
1442 )
1443 }
1444}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001445
1446#[cfg(test)]
1447mod tests {
1448 use super::*;
1449
1450 #[test]
1451 fn test_is_allowed_label_for_partition() -> Result<()> {
1452 let expected_results = vec![
1453 ("u:object_r:system_file:s0", true),
1454 ("u:object_r:apk_data_file:s0", true),
1455 ("u:object_r:app_data_file:s0", false),
1456 ("u:object_r:app_data_file:s0:c512,c768", false),
1457 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1458 ("invalid", false),
1459 ("user:role:apk_data_file:severity:categories", true),
1460 ("user:role:apk_data_file:severity:categories:extraneous", false),
1461 ];
1462
1463 for (label, expected_valid) in expected_results {
1464 let context = SeContext::new(label)?;
1465 let result = check_label_is_allowed(&context);
1466 if expected_valid {
1467 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1468 } else if result.is_ok() {
1469 bail!("Expected label {} to be disallowed", label);
1470 }
1471 }
1472 Ok(())
1473 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001474
1475 #[test]
1476 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1477 let apk = tempfile::tempfile().unwrap();
1478 let idsig = tempfile::tempfile().unwrap();
1479
1480 let ret = create_or_update_idsig_file(
1481 &ParcelFileDescriptor::new(apk),
1482 &ParcelFileDescriptor::new(idsig),
1483 );
1484 assert!(ret.is_err(), "should fail");
1485 Ok(())
1486 }
1487
1488 #[test]
1489 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1490 let tmp_dir = tempfile::TempDir::new().unwrap();
1491 let apk = File::open(tmp_dir.path()).unwrap();
1492 let idsig = tempfile::tempfile().unwrap();
1493
1494 let ret = create_or_update_idsig_file(
1495 &ParcelFileDescriptor::new(apk),
1496 &ParcelFileDescriptor::new(idsig),
1497 );
1498 assert!(ret.is_err(), "should fail");
1499 Ok(())
1500 }
1501
1502 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1503 /// on ext4 filesystem is passed.
1504 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1505 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1506 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1507 #[test]
1508 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1509 // APEXes are backed by the ext4.
1510 let apk = File::open("/apex/com.android.virt/").unwrap();
1511 let idsig = tempfile::tempfile().unwrap();
1512
1513 let ret = create_or_update_idsig_file(
1514 &ParcelFileDescriptor::new(apk),
1515 &ParcelFileDescriptor::new(idsig),
1516 );
1517 assert!(ret.is_err(), "should fail");
1518 Ok(())
1519 }
Jiyong Park8d192952023-06-26 14:29:51 +09001520
1521 #[test]
1522 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1523 use std::io::Seek;
1524
1525 // Pick any APK
1526 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1527 let mut idsig = tempfile::tempfile().unwrap();
1528
1529 create_or_update_idsig_file(
1530 &ParcelFileDescriptor::new(apk.try_clone()?),
1531 &ParcelFileDescriptor::new(idsig.try_clone()?),
1532 )?;
1533 let modified_orig = idsig.metadata()?.modified()?;
1534 apk.rewind()?;
1535 idsig.rewind()?;
1536
1537 // Call the function again
1538 create_or_update_idsig_file(
1539 &ParcelFileDescriptor::new(apk.try_clone()?),
1540 &ParcelFileDescriptor::new(idsig.try_clone()?),
1541 )?;
1542 let modified_new = idsig.metadata()?.modified()?;
1543 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1544 Ok(())
1545 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001546
1547 #[test]
1548 fn test_append_kernel_param_first_param() {
1549 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1550 append_kernel_param("foo=1", &mut vm_config);
1551 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1552 }
1553
1554 #[test]
1555 fn test_append_kernel_param() {
1556 let mut vm_config =
1557 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1558 append_kernel_param("bar=42", &mut vm_config);
1559 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1560 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09001561
1562 #[test]
1563 fn test_create_dtbo_for_vendor_image() -> Result<()> {
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001564 let vendor_hashtree_descriptor_root_digest = String::from("foo");
1565 let vendor_hashtree_descriptor_root_digest =
1566 vendor_hashtree_descriptor_root_digest.as_bytes();
Seungjae Yooec3bc522023-11-09 10:14:30 +09001567
1568 let tmp_dir = tempfile::TempDir::new()?;
1569 let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
1570
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001571 create_dtbo_for_vendor_image(vendor_hashtree_descriptor_root_digest, &dtbo_path)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +09001572
1573 let data = std::fs::read(dtbo_path)?;
1574 let fdt = Fdt::from_slice(&data).unwrap();
1575
1576 let fragment_node_path = CString::new("/fragment@0")?;
1577 let fragment_node = fdt.node(fragment_node_path.as_c_str()).unwrap();
1578 let Some(fragment_node) = fragment_node else {
1579 bail!("fragment_node shouldn't be None.");
1580 };
1581 let target_path_prop_name = CString::new("target-path")?;
1582 let target_path_from_dtbo =
1583 fragment_node.getprop(target_path_prop_name.as_c_str()).unwrap();
1584 let target_path_expected = CString::new("/")?;
1585 assert_eq!(target_path_from_dtbo, Some(target_path_expected.to_bytes_with_nul()));
1586
1587 let avf_node_path = CString::new("/fragment@0/__overlay__/avf")?;
1588 let avf_node = fdt.node(avf_node_path.as_c_str()).unwrap();
1589 let Some(avf_node) = avf_node else {
1590 bail!("avf_node shouldn't be None.");
1591 };
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001592 let vendor_hashtree_descriptor_root_digest_name =
1593 CString::new("vendor_hashtree_descriptor_root_digest")?;
1594 let digest_from_dtbo =
1595 avf_node.getprop(vendor_hashtree_descriptor_root_digest_name.as_c_str()).unwrap();
1596 assert_eq!(digest_from_dtbo, Some(vendor_hashtree_descriptor_root_digest));
Seungjae Yooec3bc522023-11-09 10:14:30 +09001597
1598 tmp_dir.close()?;
1599 Ok(())
1600 }
1601
1602 #[test]
1603 fn test_create_dtbo_for_vendor_image_throws_error_if_already_exists() -> Result<()> {
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001604 let vendor_hashtree_descriptor_root_digest = String::from("foo");
1605 let vendor_hashtree_descriptor_root_digest =
1606 vendor_hashtree_descriptor_root_digest.as_bytes();
Seungjae Yooec3bc522023-11-09 10:14:30 +09001607
1608 let tmp_dir = tempfile::TempDir::new()?;
1609 let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
1610
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001611 create_dtbo_for_vendor_image(vendor_hashtree_descriptor_root_digest, &dtbo_path)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +09001612
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001613 let ret_second_trial =
1614 create_dtbo_for_vendor_image(vendor_hashtree_descriptor_root_digest, &dtbo_path);
Seungjae Yooec3bc522023-11-09 10:14:30 +09001615 assert!(ret_second_trial.is_err(), "should fail");
1616
1617 tmp_dir.close()?;
1618 Ok(())
1619 }
Inseob Kim46257382024-01-03 15:41:22 +09001620
1621 fn test_extract_os_name_from_config_path(
1622 path: &Path,
1623 expected_result: Option<&str>,
1624 ) -> Result<()> {
1625 let result = extract_os_name_from_config_path(path);
1626 if result.as_deref() != expected_result {
1627 bail!("Expected {:?} but was {:?}", expected_result, &result)
1628 }
1629 Ok(())
1630 }
1631
1632 #[test]
1633 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
1634 test_extract_os_name_from_config_path(
1635 Path::new("/apex/com.android.virt/etc/microdroid.json"),
1636 Some("microdroid"),
1637 )
1638 }
1639
1640 #[test]
1641 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
1642 test_extract_os_name_from_config_path(
1643 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
1644 Some("microdroid_gki-android14-6.1"),
1645 )
1646 }
1647
1648 #[test]
1649 fn test_extract_os_name_from_invalid_path() -> Result<()> {
1650 test_extract_os_name_from_config_path(
1651 Path::new("/apex/com.android.virt/etc/microdroid.img"),
1652 None,
1653 )
1654 }
1655
1656 #[test]
1657 fn test_extract_os_name_from_configs() -> Result<()> {
1658 let tmp_dir = tempfile::TempDir::new()?;
1659 let tmp_dir_path = tmp_dir.path().to_owned();
1660
1661 let mut os_names: HashSet<String> = HashSet::new();
1662 os_names.insert("microdroid".to_owned());
1663 os_names.insert("microdroid_gki-android14-6.1".to_owned());
1664 os_names.insert("microdroid_gki-android15-6.1".to_owned());
1665
1666 // config files
1667 for os_name in &os_names {
1668 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
1669 }
1670
1671 // fake files not related to configs
1672 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
1673 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
1674
1675 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
1676 Some(s) => s.to_owned(),
1677 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
1678 };
1679
1680 let result = extract_os_names_from_configs(&glob_pattern)?;
1681 if result != os_names {
1682 bail!("Expected {:?} but was {:?}", os_names, result);
1683 }
1684 Ok(())
1685 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001686}
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001687
1688struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
1689
1690impl Interface for SecretkeeperProxy {}
1691
1692impl ISecretkeeper for SecretkeeperProxy {
1693 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
1694 // Pass the request to the channel, and read the response.
1695 self.0.processSecretManagementRequest(req)
1696 }
1697
1698 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
1699 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
1700 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
1701 }
1702
1703 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
1704 self.0.deleteIds(ids)
1705 }
1706
1707 fn deleteAll(&self) -> binder::Result<()> {
1708 self.0.deleteAll()
1709 }
1710}
1711
1712struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
1713
1714impl Interface for AuthGraphKeyExchangeProxy {}
1715
1716impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
1717 fn create(&self) -> binder::Result<SessionInitiationInfo> {
1718 self.0.create()
1719 }
1720
1721 fn init(
1722 &self,
1723 peer_pub_key: &PubKey,
1724 peer_id: &Identity,
1725 peer_nonce: &[u8],
1726 peer_version: i32,
1727 ) -> binder::Result<KeInitResult> {
1728 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
1729 }
1730
1731 fn finish(
1732 &self,
1733 peer_pub_key: &PubKey,
1734 peer_id: &Identity,
1735 peer_signature: &SessionIdSignature,
1736 peer_nonce: &[u8],
1737 peer_version: i32,
1738 own_key: &Key,
1739 ) -> binder::Result<SessionInfo> {
1740 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
1741 }
1742
1743 fn authenticationComplete(
1744 &self,
1745 peer_signature: &SessionIdSignature,
1746 shared_keys: &[AuthgraphArc; 2],
1747 ) -> binder::Result<[AuthgraphArc; 2]> {
1748 self.0.authenticationComplete(peer_signature, shared_keys)
1749 }
1750}