blob: 34994f89f530fc4438fdaa963f2434e7b89b6808 [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};
Shikha Panwar9ae2e622024-01-30 12:22:30 +000085use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, 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
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000162 output
163 .seek(SeekFrom::Start(0))
164 .context("failed to move cursor to start on the idsig output")?;
Nikita Ioffec09b0492022-12-14 20:18:33 +0000165 output.set_len(0).context("failed to set_len on the idsig output")?;
166 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000167 Ok(())
168}
169
Alan Stokes25f69362023-03-06 16:51:54 +0000170fn get_current_sdk() -> Result<u32> {
171 let current_sdk = system_properties::read("ro.build.version.sdk")?;
172 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
173 current_sdk.parse().context("Malformed SDK version")
174}
175
David Brazdil4b4c5102022-12-19 22:56:20 +0000176pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
177 for dir_entry in read_dir(path)? {
178 remove_file(dir_entry?.path())?;
179 }
180 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100181}
182
David Brazdil528e0472022-10-10 15:06:02 +0100183/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000184#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000185pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900186 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000187}
188
Shikha Panward8e35422021-10-11 13:51:27 +0000189impl Interface for VirtualizationService {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000190 fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
Shikha Panward8e35422021-10-11 13:51:27 +0000191 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
192 let state = &mut *self.state.lock().unwrap();
193 let vms = state.vms();
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000194 writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000195 for vm in vms {
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000196 writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
197 writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
Shikha Panward8e35422021-10-11 13:51:27 +0000198 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000199 writeln!(writer, "\tPayload state {:?}", vm.payload_state())
Shikha Panward8e35422021-10-11 13:51:27 +0000200 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000201 writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
202 writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
Shikha Panward8e35422021-10-11 13:51:27 +0000203 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000204 writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
Shikha Panward8e35422021-10-11 13:51:27 +0000205 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Andrei Homescu0cf8e222023-11-09 04:27:55 +0000206 writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
Shikha Panward8e35422021-10-11 13:51:27 +0000207 .or(Err(StatusCode::UNKNOWN_ERROR))?;
208 }
209 Ok(())
210 }
211}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000212impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000213 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
214 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000215 ///
216 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000217 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000218 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000219 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900220 console_out_fd: Option<&ParcelFileDescriptor>,
221 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000222 log_fd: Option<&ParcelFileDescriptor>,
223 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000224 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900225 let ret = self.create_vm_internal(
226 config,
227 console_out_fd,
228 console_in_fd,
229 log_fd,
230 &mut is_protected,
231 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000232 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000233 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000234 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000235
Andrew Walbrandff3b942021-06-09 15:20:36 +0000236 /// Initialise an empty partition image of the given size to be used as a writable partition.
237 fn initializeWritablePartition(
238 &self,
239 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000240 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900241 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000242 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900243 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900244 let size_bytes = size_bytes
245 .try_into()
246 .with_context(|| format!("Invalid size: {}", size_bytes))
247 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000248 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000249 let mut image = clone_file(image_fd)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000250 // initialize the file. Any data in the file will be erased.
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000251 image
252 .seek(SeekFrom::Start(0))
253 .context("failed to move cursor to start")
254 .or_service_specific_exception(-1)?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900255 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
Shikha Panwar9ae2e622024-01-30 12:22:30 +0000256
Jiyong Park2227eaa2023-08-04 11:59:18 +0900257 let mut part = QcowFile::new(image, size_bytes)
258 .context("Failed to create QCOW2 image")
259 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000260
261 match partition_type {
262 PartitionType::RAW => Ok(()),
263 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
264 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
265 _ => Err(Error::new(
266 ErrorKind::Unsupported,
267 format!("Unsupported partition type {:?}", partition_type),
268 )),
269 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900270 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
271 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000272
273 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000274 }
275
Jiyong Park0a248432021-08-20 23:32:39 +0900276 /// Creates or update the idsig file by digesting the input APK file.
277 fn createOrUpdateIdsigFile(
278 &self,
279 input_fd: &ParcelFileDescriptor,
280 idsig_fd: &ParcelFileDescriptor,
281 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900282 check_manage_access()?;
283
Jiyong Park2227eaa2023-08-04 11:59:18 +0900284 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900285 Ok(())
286 }
287
Andrew Walbran320b5602021-03-04 16:11:12 +0000288 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
289 /// and as such is only permitted from the shell user.
290 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000291 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000292 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000293 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900294
295 /// Get a list of assignable device types.
296 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
297 // Delegate to the global service, including checking the permission.
298 GLOBAL_SERVICE.getAssignableDevices()
299 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100300
Inseob Kim46257382024-01-03 15:41:22 +0900301 /// Get a list of supported OSes.
302 fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
303 Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
304 }
305
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100306 /// Returns whether given feature is enabled
307 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
308 check_manage_access()?;
309
310 // This approach is quite cumbersome, but will do the work for the short term.
311 // TODO(b/298012279): make this scalable.
312 match feature {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100313 FEATURE_DICE_CHANGES => Ok(cfg!(dice_changes)),
Alan Stokes27f3ef02023-09-29 15:09:35 +0100314 FEATURE_MULTI_TENANT => Ok(cfg!(multi_tenant)),
Nikita Ioffe631717e2023-09-05 13:38:07 +0100315 FEATURE_VENDOR_MODULES => Ok(cfg!(vendor_modules)),
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100316 _ => {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100317 warn!("unknown feature {feature}");
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100318 Ok(false)
319 }
320 }
321 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000322}
323
Jiyong Park8611a6c2021-07-09 18:17:44 +0900324impl VirtualizationService {
325 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000326 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900327 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000328
David Brazdil209074a2023-01-12 16:44:51 +0000329 fn create_vm_context(
330 &self,
331 requester_debug_pid: pid_t,
332 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000333 const NUM_ATTEMPTS: usize = 5;
334
335 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000336 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000337 let cid = vm_context.getCid()? as Cid;
338 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000339 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
340
341 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000342 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000343 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000344 Ok(vm_server) => {
345 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000346 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000347 }
348 Err(err) => {
349 warn!("Could not start RpcServer on port {}: {}", port, err);
350 }
351 }
352 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900353 Err(anyhow!("Too many attempts to create VM context failed"))
354 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000355 }
356
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000357 fn create_vm_internal(
358 &self,
359 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900360 console_out_fd: Option<&ParcelFileDescriptor>,
361 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000362 log_fd: Option<&ParcelFileDescriptor>,
363 is_protected: &mut bool,
364 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000365 let requester_uid = get_calling_uid();
366 let requester_debug_pid = get_calling_pid();
367
Nikita Ioffe631717e2023-09-05 13:38:07 +0100368 check_config_features(config)?;
369
David Brazdil209074a2023-01-12 16:44:51 +0000370 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
371 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900372
Alan Stokes7bc146c2022-10-20 17:10:32 +0100373 let is_custom = match config {
374 VirtualMachineConfig::RawConfig(_) => true,
375 VirtualMachineConfig::AppConfig(config) => {
376 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100377 // VirtualMachineAppConfig. Almost all of these features are grouped in the
378 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100379 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100380 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100381 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900382 // - using anything other than the default kernel;
383 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100384 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900385 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100386 };
387 if is_custom {
388 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900389 }
390
Nikita Ioffe5776f082023-02-10 21:38:26 +0000391 let gdb_port = extract_gdb_port(config);
392
393 // Additional permission checks if caller request gdb.
394 if gdb_port.is_some() {
395 check_gdb_allowed(config)?;
396 }
397
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900398 let vendor_hashtree_descriptor_root_digest =
399 extract_vendor_hashtree_descriptor_root_digest(config)
400 .context("Failed to extract root digest of vendor")
401 .or_service_specific_exception(-1)?;
402 let dtbo_vendor = if let Some(vendor_hashtree_descriptor_root_digest) =
403 vendor_hashtree_descriptor_root_digest
404 {
405 let root_digest_hex = hex::encode(vendor_hashtree_descriptor_root_digest);
Seungjae Yooec3bc522023-11-09 10:14:30 +0900406 let dtbo_for_vendor_image = temporary_directory.join("dtbo_vendor");
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900407 create_dtbo_for_vendor_image(root_digest_hex.as_bytes(), &dtbo_for_vendor_image)
408 .context("Failed to write root digest of vendor")
Seungjae Yooec3bc522023-11-09 10:14:30 +0900409 .or_service_specific_exception(-1)?;
410 let file = File::open(dtbo_for_vendor_image)
411 .context("Failed to open dtbo_vendor")
412 .or_service_specific_exception(-1)?;
413 Some(file)
414 } else {
415 None
416 };
417
Jaewan Kim61f86142023-03-28 15:12:52 +0900418 let debug_level = match config {
419 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
420 _ => DebugLevel::NONE,
421 };
422 let debug_config = DebugConfig::new(debug_level);
423
424 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900425 Some(prepare_ramdump_file(&temporary_directory)?)
426 } else {
427 None
428 };
429
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000430 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900431 let console_out_fd =
432 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
433 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900434 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000435
436 // Counter to generate unique IDs for temporary image files.
437 let mut next_temporary_image_id = 0;
438 // Files which are referred to from composite images. These must be mapped to the crosvm
439 // child process, and not closed before it is started.
440 let mut indirect_files = vec![];
441
Alan Stokes7bc146c2022-10-20 17:10:32 +0100442 let (is_app_config, config) = match config {
443 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
444 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900445 let config = load_app_config(config, &debug_config, &temporary_directory)
446 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900447 *is_protected = config.protectedVm;
448 let message = format!("Failed to load app config: {:?}", e);
449 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900450 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900451 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100452 (true, BorrowedOrOwned::Owned(config))
453 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000454 };
455 let config = config.as_ref();
456 *is_protected = config.protectedVm;
457
458 // Check if partition images are labeled incorrectly. This is to prevent random images
459 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100460 // being loaded in a pVM. This applies to everything but the instance image in the raw
461 // config, and everything but the non-executable, generated partitions in the app
462 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000463 config
464 .disks
465 .iter()
466 .flat_map(|disk| disk.partitions.iter())
467 .filter(|partition| {
468 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100469 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000470 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000471 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000472 }
473 })
474 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900475 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000476
Alan Stokes185fe112023-01-10 16:20:55 +0000477 let kernel = maybe_clone_file(&config.kernel)?;
478 let initrd = maybe_clone_file(&config.initrd)?;
479
480 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
481 if config.protectedVm {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900482 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Alan Stokes185fe112023-01-10 16:20:55 +0000483 }
484
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000485 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900486 write_zero_filler(&zero_filler_path)
487 .context("Failed to make composite image")
488 .with_log()
489 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000490
491 // Assemble disk images if needed.
492 let disks = config
493 .disks
494 .iter()
495 .map(|disk| {
496 assemble_disk_image(
497 disk,
498 &zero_filler_path,
499 &temporary_directory,
500 &mut next_temporary_image_id,
501 &mut indirect_files,
502 )
503 })
504 .collect::<Result<Vec<DiskFile>, _>>()?;
505
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000506 let (cpus, host_cpu_topology) = match config.cpuTopology {
507 CpuTopology::MATCH_HOST => (None, true),
508 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
509 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900510 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
511 .with_log()
512 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000513 }
514 };
515
David Brazdil2dfefd12023-11-17 14:07:36 +0000516 let (vfio_devices, dtbo) = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900517 let mut set = HashSet::new();
518 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900519 let path = canonicalize(device)
520 .with_context(|| format!("can't canonicalize {device}"))
521 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900522 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900523 return Err(anyhow!("duplicated device {device}"))
524 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900525 }
526 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000527 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(&config.devices)?;
David Brazdil2dfefd12023-11-17 14:07:36 +0000528 let dtbo_file = File::from(
529 GLOBAL_SERVICE
530 .getDtboFile()?
531 .as_ref()
532 .try_clone()
533 .context("Failed to create File from ParcelFileDescriptor")
534 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
535 );
536 (devices, Some(dtbo_file))
Inseob Kim7307a892023-09-14 13:37:58 +0900537 } else {
David Brazdil2dfefd12023-11-17 14:07:36 +0000538 (vec![], None)
Inseob Kim7307a892023-09-14 13:37:58 +0900539 };
Inseob Kim6ef80972023-07-20 17:23:36 +0900540
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000541 // Actually start the VM.
542 let crosvm_config = CrosvmConfig {
543 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000544 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000545 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000546 kernel,
547 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000548 disks,
549 params: config.params.to_owned(),
550 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900551 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000552 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000553 cpus,
554 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900555 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900556 console_out_fd,
557 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000558 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900559 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000560 indirect_files,
561 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900562 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000563 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900564 vfio_devices,
David Brazdil2dfefd12023-11-17 14:07:36 +0000565 dtbo,
Seungjae Yooec3bc522023-11-09 10:14:30 +0900566 dtbo_vendor,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000567 };
568 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100569 VmInstance::new(
570 crosvm_config,
571 temporary_directory,
572 requester_uid,
573 requester_debug_pid,
574 vm_context,
575 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900576 .with_context(|| format!("Failed to create VM with config {:?}", config))
577 .with_log()
578 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000579 );
580 state.add_vm(Arc::downgrade(&instance));
581 Ok(VirtualMachine::create(instance))
582 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900583}
584
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900585fn extract_vendor_hashtree_descriptor_root_digest(
586 config: &VirtualMachineConfig,
587) -> Result<Option<Vec<u8>>> {
Seungjae Yooec3bc522023-11-09 10:14:30 +0900588 let VirtualMachineConfig::AppConfig(config) = config else {
589 return Ok(None);
590 };
591 let Some(custom_config) = &config.customConfig else {
592 return Ok(None);
593 };
594 let Some(file) = custom_config.vendorImage.as_ref() else {
595 return Ok(None);
596 };
597
598 let file = clone_file(file)?;
599 let size = file.metadata().context("Failed to get metadata from microdroid-vendor.img")?.len();
600 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
601 .context("Failed to get vbmeta from microdroid-vendor.img")?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900602
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900603 for descriptor in vbmeta.descriptors()?.iter() {
604 if let vbmeta::Descriptor::Hashtree(_) = descriptor {
605 return Ok(Some(descriptor.to_hashtree()?.root_digest().to_vec()));
606 }
607 }
608 Err(anyhow!("No root digest is extracted from microdroid-vendor.img"))
Seungjae Yooec3bc522023-11-09 10:14:30 +0900609}
610
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900611fn create_dtbo_for_vendor_image(
612 vendor_hashtree_descriptor_root_digest: &[u8],
613 dtbo: &PathBuf,
614) -> Result<()> {
Seungjae Yooec3bc522023-11-09 10:14:30 +0900615 if dtbo.exists() {
616 return Err(anyhow!("DTBO file already exists"));
617 }
618
619 let mut buf = vec![0; EMPTY_VENDOR_DT_OVERLAY_BUF_SIZE];
620 let fdt = Fdt::create_empty_tree(buf.as_mut_slice())
621 .map_err(|e| anyhow!("Failed to create FDT: {:?}", e))?;
622 let mut root = fdt.root_mut().map_err(|e| anyhow!("Failed to get root node: {:?}", e))?;
623
624 let fragment_node_name = CString::new("fragment@0")?;
625 let mut fragment_node = root
626 .add_subnode(fragment_node_name.as_c_str())
627 .map_err(|e| anyhow!("Failed to create fragment node: {:?}", e))?;
628 let target_path_prop_name = CString::new("target-path")?;
629 let target_path = CString::new("/")?;
630 fragment_node
631 .setprop(target_path_prop_name.as_c_str(), target_path.to_bytes_with_nul())
632 .map_err(|e| anyhow!("Failed to set target-path: {:?}", e))?;
633 let overlay_node_name = CString::new("__overlay__")?;
634 let mut overlay_node = fragment_node
635 .add_subnode(overlay_node_name.as_c_str())
636 .map_err(|e| anyhow!("Failed to create overlay node: {:?}", e))?;
637
638 let avf_node_name = CString::new("avf")?;
639 let mut avf_node = overlay_node
640 .add_subnode(avf_node_name.as_c_str())
641 .map_err(|e| anyhow!("Failed to create avf node: {:?}", e))?;
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900642 let vendor_hashtree_descriptor_root_digest_name =
643 CString::new("vendor_hashtree_descriptor_root_digest")?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900644 avf_node
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900645 .setprop(
646 vendor_hashtree_descriptor_root_digest_name.as_c_str(),
647 vendor_hashtree_descriptor_root_digest,
648 )
649 .map_err(|e| {
650 anyhow!("Failed to set avf/vendor_hashtree_descriptor_root_digest: {:?}", e)
651 })?;
Seungjae Yooec3bc522023-11-09 10:14:30 +0900652
653 fdt.pack().map_err(|e| anyhow!("Failed to pack fdt: {:?}", e))?;
654 let mut file = File::create(dtbo)?;
655 file.write_all(fdt.as_slice())?;
656 Ok(file.flush()?)
657}
658
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000659fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900660 let file = OpenOptions::new()
661 .create_new(true)
662 .read(true)
663 .write(true)
664 .open(zero_filler_path)
665 .with_context(|| "Failed to create zero.img")?;
666 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000667 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900668}
669
David Brazdilf50c7a62023-04-19 14:22:42 +0000670fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
671 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
672 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
673 part.flush()
674}
675
676fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
677 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
678 part.flush()
679}
680
681fn round_up(input: u64, granularity: u64) -> u64 {
682 if granularity == 0 {
683 return input;
684 }
685 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
686 let result = input.checked_add(granularity - 1).unwrap_or(input);
687 (result / granularity) * granularity
688}
689
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000690/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
691///
692/// This may involve assembling a composite disk from a set of partition images.
693fn assemble_disk_image(
694 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900695 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000696 temporary_directory: &Path,
697 next_temporary_image_id: &mut u64,
698 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000699) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000700 let image = if !disk.partitions.is_empty() {
701 if disk.image.is_some() {
702 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900703 return Err(anyhow!("DiskImage contains both image and partitions"))
704 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000705 }
706
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000707 let composite_image_filenames =
708 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
709 let (image, partition_files) = make_composite_image(
710 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900711 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000712 &composite_image_filenames.composite,
713 &composite_image_filenames.header,
714 &composite_image_filenames.footer,
715 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900716 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
717 .with_log()
718 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000719
720 // Pass the file descriptors for the various partition files to crosvm when it
721 // is run.
722 indirect_files.extend(partition_files);
723
724 image
725 } else if let Some(image) = &disk.image {
726 clone_file(image)?
727 } else {
728 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900729 return Err(anyhow!("DiskImage didn't contain image or partitions."))
730 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000731 };
732
733 Ok(DiskFile { image, writable: disk.writable })
734}
735
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100736fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
737 if let Some(ref mut params) = vm_config.params {
738 params.push(' ');
739 params.push_str(param)
740 } else {
741 vm_config.params = Some(param.to_owned())
742 }
743}
744
Inseob Kim46257382024-01-03 15:41:22 +0900745fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
746 if config.extension()?.to_str()? != "json" {
747 return None;
Inseob Kim172f9eb2023-11-06 17:02:08 +0900748 }
Inseob Kim46257382024-01-03 15:41:22 +0900749
750 Some(config.with_extension("").file_name()?.to_str()?.to_owned())
751}
752
753fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
754 let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
755 let os_names =
756 configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
757
758 Ok(os_names)
759}
760
761fn get_supported_os_names() -> Result<HashSet<String>> {
762 if !cfg!(vendor_modules) {
763 return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
764 }
765
766 extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
767}
768
769fn is_valid_os(os_name: &str) -> bool {
770 SUPPORTED_OS_NAMES.contains(os_name)
Inseob Kim172f9eb2023-11-06 17:02:08 +0900771}
772
Jooyung Han21e9b922021-06-26 04:14:16 +0900773fn load_app_config(
774 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900775 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900776 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900777) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000778 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
779 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900780 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900781
Shikha Panwar22e70452022-10-10 18:32:55 +0000782 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
783 Some(clone_file(file)?)
784 } else {
785 None
786 };
787
Alan Stokes0d1ef782022-09-27 13:46:35 +0100788 let vm_payload_config = match &config.payload {
789 Payload::ConfigPath(config_path) => {
790 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
791 .with_context(|| format!("Couldn't read config from {}", config_path))?
792 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000793 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100794 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900795
Inseob Kim172f9eb2023-11-06 17:02:08 +0900796 // For now, the only supported OS is Microdroid and Microdroid GKI
Alan Stokes0d1ef782022-09-27 13:46:35 +0100797 let os_name = vm_payload_config.os.name.as_str();
Inseob Kim172f9eb2023-11-06 17:02:08 +0900798 if !is_valid_os(os_name) {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000799 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900800 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000801
802 // It is safe to construct a filename based on the os_name because we've already checked that it
803 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900804 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
805 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000806 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900807
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100808 if let Some(custom_config) = &config.customConfig {
809 if let Some(file) = custom_config.customKernelImage.as_ref() {
810 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
811 }
812 vm_config.taskProfiles = custom_config.taskProfiles.clone();
813 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100814
815 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100816 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
817 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100818 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900819
820 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100821 }
822
Andrew Walbrancc045902021-07-27 16:06:17 +0000823 if config.memoryMib > 0 {
824 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000825 }
826
Seungjae Yoo62085c02022-08-12 04:44:52 +0000827 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000828 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000829 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900830
Shikha Panwar22e70452022-10-10 18:32:55 +0000831 // Microdroid takes additional init ramdisk & (optionally) storage image
Inseob Kim172f9eb2023-11-06 17:02:08 +0900832 add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
Shikha Panwar22e70452022-10-10 18:32:55 +0000833
834 // Include Microdroid payload disk (contains apks, idsigs) in vm config
835 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100836 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900837 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100838 temporary_directory,
839 apk_file,
840 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100841 &vm_payload_config,
842 &mut vm_config,
843 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900844
Andrew Walbrancc0db522021-07-12 17:03:42 +0000845 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900846}
847
Alan Stokes0d1ef782022-09-27 13:46:35 +0100848fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
849 let mut apk_zip = ZipArchive::new(apk_file)?;
850 let config_file = apk_zip.by_name(config_path)?;
851 Ok(serde_json::from_reader(config_file)?)
852}
853
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000854fn create_vm_payload_config(
855 payload_config: &VirtualMachinePayloadConfig,
856) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100857 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
858 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
859 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000860
861 let payload_binary_name = &payload_config.payloadBinaryName;
862 if payload_binary_name.contains('/') {
863 bail!("Payload binary name must not specify a path: {payload_binary_name}");
864 }
865
866 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
Inseob Kim172f9eb2023-11-06 17:02:08 +0900867 let name = payload_config.osName.clone();
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000868 Ok(VmPayloadConfig {
Inseob Kim172f9eb2023-11-06 17:02:08 +0900869 os: OsConfig { name },
Alan Stokes0d1ef782022-09-27 13:46:35 +0100870 task: Some(task),
871 apexes: vec![],
872 extra_apks: vec![],
873 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900874 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100875 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000876 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100877}
878
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000879/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000880fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000881 temporary_directory: &Path,
882 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000883) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000884 let id = *next_temporary_image_id;
885 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000886 CompositeImageFilenames {
887 composite: temporary_directory.join(format!("composite-{}.img", id)),
888 header: temporary_directory.join(format!("composite-{}-header.img", id)),
889 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
890 }
891}
892
893/// Filenames for a composite disk image, including header and footer partitions.
894#[derive(Clone, Debug, Eq, PartialEq)]
895struct CompositeImageFilenames {
896 /// The composite disk image itself.
897 composite: PathBuf,
898 /// The header partition image.
899 header: PathBuf,
900 /// The footer partition image.
901 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000902}
903
Jiyong Park753553b2021-07-12 21:21:09 +0900904/// Checks whether the caller has a specific permission
905fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100906 let calling_pid = get_calling_pid();
907 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900908 // Root can do anything
909 if calling_uid == 0 {
910 return Ok(());
911 }
912 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
913 binder::get_interface("permission")?;
914 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000915 Ok(())
916 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900917 Err(anyhow!("does not have the {} permission", perm))
918 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000919 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000920}
921
Jiyong Park753553b2021-07-12 21:21:09 +0900922/// Check whether the caller of the current Binder method is allowed to manage VMs
923fn check_manage_access() -> binder::Result<()> {
924 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
925}
926
Inseob Kim1119d702022-05-02 18:01:58 +0900927/// Check whether the caller of the current Binder method is allowed to create custom VMs
928fn check_use_custom_virtual_machine() -> binder::Result<()> {
929 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
930}
931
Alan Stokes185fe112023-01-10 16:20:55 +0000932/// Return whether a partition is exempt from selinux label checks, because we know that it does
933/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100934fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000935 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100936 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000937 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100938 || label == "microdroid-apk-idsig"
939 || label == "payload-metadata"
940 || label.starts_with("extra-idsig-")
941}
942
Alice Wangc206b9b2023-08-28 14:13:51 +0000943/// Returns whether a partition with the given label is safe for a raw config VM.
944fn is_safe_raw_partition(label: &str) -> bool {
945 label == "vm-instance"
946}
947
Alan Stokes185fe112023-01-10 16:20:55 +0000948/// Check that a file SELinux label is acceptable.
949///
950/// 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 +0900951/// system or vendor, do not have write access to.
Alan Stokes185fe112023-01-10 16:20:55 +0000952///
953/// Note that sepolicy must also grant read access for these types to both virtualization
954/// service and crosvm.
955///
956/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
957/// user devices (W^X).
958fn check_label_is_allowed(context: &SeContext) -> Result<()> {
959 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100960 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100961 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000962 | "staging_data_file" // updated/staged APEX images
963 | "system_file" // immutable dm-verity protected partition
964 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Seungjae Yoo2b74c442023-11-15 18:05:07 +0900965 | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100966 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000967 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900968 }
969}
970
Alan Stokes185fe112023-01-10 16:20:55 +0000971fn check_label_for_partition(partition: &Partition) -> Result<()> {
972 let file = partition.image.as_ref().unwrap().as_ref();
973 check_label_is_allowed(&getfilecon(file)?)
974 .with_context(|| format!("Partition {} invalid", &partition.label))
975}
976
977fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
978 if let Some(f) = kernel {
979 check_label_for_file(f, "kernel")?;
980 }
981 if let Some(f) = initrd {
982 check_label_for_file(f, "initrd")?;
983 }
984 Ok(())
985}
986fn check_label_for_file(file: &File, name: &str) -> Result<()> {
987 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
988}
989
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000990/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
991#[derive(Debug)]
992struct VirtualMachine {
993 instance: Arc<VmInstance>,
994}
995
996impl VirtualMachine {
997 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000998 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000999 }
1000}
1001
1002impl Interface for VirtualMachine {}
1003
1004impl IVirtualMachine for VirtualMachine {
1005 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +09001006 // Don't check permission. The owner of the VM might have passed this binder object to
1007 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001008 Ok(self.instance.cid as i32)
1009 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001010
Andrew Walbran6b650662021-09-07 13:13:23 +00001011 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +09001012 // Don't check permission. The owner of the VM might have passed this binder object to
1013 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +00001014 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +00001015 }
1016
1017 fn registerCallback(
1018 &self,
1019 callback: &Strong<dyn IVirtualMachineCallback>,
1020 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +09001021 // Don't check permission. The owner of the VM might have passed this binder object to
1022 // others.
1023 //
Andrew Walbrandae07162021-03-12 17:05:20 +00001024 // TODO: Should this give an error if the VM is already dead?
1025 self.instance.callbacks.add(callback.clone());
1026 Ok(())
1027 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001028
Andrew Walbranf8d94112021-09-07 11:45:36 +00001029 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001030 self.instance
1031 .start()
1032 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1033 .with_log()
1034 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +00001035 }
1036
Inseob Kima446f802022-07-11 19:46:37 +09001037 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001038 self.instance
1039 .kill()
1040 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1041 .with_log()
1042 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +09001043 }
1044
Keir Frasercdd4b112022-11-24 14:02:25 +00001045 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001046 self.instance
1047 .trim_memory(level)
1048 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
1049 .with_log()
1050 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +00001051 }
1052
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001053 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001054 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001055 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001056 }
Alan Stokes10c47672022-12-13 17:17:08 +00001057 let port = port as u32;
1058 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001059 return Err(anyhow!("Can't connect to privileged port {port}"))
1060 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +00001061 }
Jiyong Park2227eaa2023-08-04 11:59:18 +09001062 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1063 .context("Failed to connect")
1064 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001065 Ok(vsock_stream_to_pfd(stream))
1066 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001067}
1068
1069impl Drop for VirtualMachine {
1070 fn drop(&mut self) {
1071 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +09001072 if let Err(e) = self.instance.kill() {
1073 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1074 }
Andrew Walbrandae07162021-03-12 17:05:20 +00001075 }
1076}
1077
1078/// A set of Binders to be called back in response to various events on the VM, such as when it
1079/// dies.
1080#[derive(Debug, Default)]
1081pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1082
1083impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001084 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001085 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001086 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001087 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001088 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001089 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001090 }
1091 }
1092 }
1093
Inseob Kim14cb8692021-08-31 21:50:39 +09001094 /// Call all registered callbacks to notify that the payload is ready to serve.
1095 pub fn notify_payload_ready(&self, cid: Cid) {
1096 let callbacks = &*self.0.lock().unwrap();
1097 for callback in callbacks {
1098 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001099 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001100 }
1101 }
1102 }
1103
Inseob Kim2444af92021-08-31 01:22:50 +09001104 /// Call all registered callbacks to notify that the payload has finished.
1105 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1106 let callbacks = &*self.0.lock().unwrap();
1107 for callback in callbacks {
1108 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001109 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001110 }
1111 }
1112 }
1113
Jooyung Handd0a1732021-11-23 15:26:20 +09001114 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001115 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001116 let callbacks = &*self.0.lock().unwrap();
1117 for callback in callbacks {
1118 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001119 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001120 }
1121 }
1122 }
1123
Andrew Walbrandae07162021-03-12 17:05:20 +00001124 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001125 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001126 let callbacks = &*self.0.lock().unwrap();
1127 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001128 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001129 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001130 }
1131 }
1132 }
1133
1134 /// Add a new callback to the set.
1135 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1136 self.0.lock().unwrap().push(callback);
1137 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001138}
1139
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001140/// The mutable state of the VirtualizationService. There should only be one instance of this
1141/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001142#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001143struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001144 /// The VMs which have been started. When VMs are started a weak reference is added to this
1145 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1146 /// the Binder client are dropped the weak reference here will become invalid, and will be
1147 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001148 vms: Vec<Weak<VmInstance>>,
1149}
1150
1151impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001152 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001153 fn vms(&self) -> Vec<Arc<VmInstance>> {
1154 // Attempt to upgrade the weak pointers to strong pointers.
1155 self.vms.iter().filter_map(Weak::upgrade).collect()
1156 }
1157
1158 /// Add a new VM to the list.
1159 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1160 // Garbage collect any entries from the stored list which no longer exist.
1161 self.vms.retain(|vm| vm.strong_count() > 0);
1162
1163 // Actually add the new VM.
1164 self.vms.push(vm);
1165 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001166
Jiyong Park8611a6c2021-07-09 18:17:44 +09001167 /// Get a VM that corresponds to the given cid
1168 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1169 self.vms().into_iter().find(|vm| vm.cid == cid)
1170 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001171}
1172
Andrew Walbran6b650662021-09-07 13:13:23 +00001173/// Gets the `VirtualMachineState` of the given `VmInstance`.
1174fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001175 match &*instance.vm_state.lock().unwrap() {
1176 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1177 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001178 PayloadState::Starting => VirtualMachineState::STARTING,
1179 PayloadState::Started => VirtualMachineState::STARTED,
1180 PayloadState::Ready => VirtualMachineState::READY,
1181 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001182 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001183 },
1184 VmState::Dead => VirtualMachineState::DEAD,
1185 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001186 }
1187}
1188
David Brazdilf50c7a62023-04-19 14:22:42 +00001189/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001190pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1191 file.as_ref()
1192 .try_clone()
1193 .context("Failed to clone File from ParcelFileDescriptor")
1194 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Andrei Homescu11333c62023-11-09 04:26:39 +00001195 .map(File::from)
David Brazdilf50c7a62023-04-19 14:22:42 +00001196}
1197
Andrew Walbrand3a84182021-09-07 14:48:52 +00001198/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001199fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001200 file.as_ref().map(clone_file).transpose()
1201}
1202
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001203/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1204fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1205 // SAFETY: ownership is transferred from stream to f
1206 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1207 ParcelFileDescriptor::new(f)
1208}
1209
Jiyong Parkdcf17412022-02-08 15:07:23 +09001210/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001211fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1212 VersionReq::parse(s)
1213 .with_context(|| format!("Invalid platform version requirement {}", s))
1214 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001215}
1216
Jiyong Parked180932023-02-24 19:55:41 +09001217/// Create the empty ramdump file
1218fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1219 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1220 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1221 // owner) for readout.
1222 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001223 let ramdump = File::create(ramdump_path)
1224 .context("Failed to prepare ramdump file")
1225 .with_log()
1226 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001227 Ok(ramdump)
1228}
1229
Nikita Ioffe5776f082023-02-10 21:38:26 +00001230fn is_protected(config: &VirtualMachineConfig) -> bool {
1231 match config {
1232 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1233 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1234 }
1235}
1236
1237fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1238 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001239 return Err(anyhow!("Can't use gdb with protected VMs"))
1240 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001241 }
1242
1243 match config {
1244 VirtualMachineConfig::RawConfig(_) => Ok(()),
1245 VirtualMachineConfig::AppConfig(config) => {
1246 if config.debugLevel != DebugLevel::FULL {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001247 Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1248 .or_binder_exception(ExceptionCode::SECURITY)
Nikita Ioffe5776f082023-02-10 21:38:26 +00001249 } else {
1250 Ok(())
1251 }
1252 }
1253 }
1254}
1255
1256fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1257 match config {
1258 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001259 VirtualMachineConfig::AppConfig(config) => {
1260 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1261 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001262 }
1263}
1264
Nikita Ioffe631717e2023-09-05 13:38:07 +01001265fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1266 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1267 if let Some(custom_config) = &config.customConfig {
1268 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1269 return Err(anyhow!("vendor modules feature is disabled"))
1270 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1271 }
1272 }
1273 Ok(())
1274}
1275
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001276fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
1277 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1278 if let Some(custom_config) = &config.customConfig {
1279 if !custom_config.devices.is_empty() {
1280 return Err(anyhow!("device assignment feature is disabled"))
1281 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1282 }
1283 }
1284 Ok(())
1285}
1286
Nikita Ioffe631717e2023-09-05 13:38:07 +01001287fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1288 if !cfg!(vendor_modules) {
1289 check_no_vendor_modules(config)?;
1290 }
Nikita Ioffe94a8a182023-11-16 16:37:48 +00001291 if !cfg!(device_assignment) {
1292 check_no_devices(config)?;
1293 }
Nikita Ioffe631717e2023-09-05 13:38:07 +01001294 Ok(())
1295}
1296
Inseob Kim0168b462022-12-27 14:54:35 +09001297fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001298 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001299 fd: Option<&ParcelFileDescriptor>,
1300 tag: String,
1301) -> Result<Option<File>, Status> {
1302 if let Some(fd) = fd {
1303 return Ok(Some(clone_file(fd)?));
1304 }
1305
Jaewan Kim61f86142023-03-28 15:12:52 +09001306 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001307 return Ok(None);
1308 };
Inseob Kim0168b462022-12-27 14:54:35 +09001309
Jiyong Park2227eaa2023-08-04 11:59:18 +09001310 let (raw_read_fd, raw_write_fd) =
1311 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001312
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001313 // 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 +09001314 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001315 // 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 +09001316 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1317
1318 std::thread::spawn(move || loop {
1319 let mut buf = vec![];
1320 match reader.read_until(b'\n', &mut buf) {
1321 Ok(0) => {
1322 // EOF
1323 return;
1324 }
1325 Ok(size) => {
1326 if buf[size - 1] == b'\n' {
1327 buf.pop();
1328 }
1329 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1330 }
1331 Err(e) => {
1332 error!("Could not read console pipe: {:?}", e);
1333 return;
1334 }
1335 };
1336 });
1337
1338 Ok(Some(write_fd))
1339}
1340
Jooyung Han35edb8f2021-07-01 16:17:16 +09001341/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1342/// it doesn't require that T implements Clone.
1343enum BorrowedOrOwned<'a, T> {
1344 Borrowed(&'a T),
1345 Owned(T),
1346}
1347
1348impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1349 fn as_ref(&self) -> &T {
1350 match self {
1351 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001352 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001353 }
1354 }
1355}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001356
1357/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1358#[derive(Debug, Default)]
1359struct VirtualMachineService {
1360 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001361 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001362}
1363
1364impl Interface for VirtualMachineService {}
1365
1366impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001367 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1368 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001369 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001370 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001371 vm.update_payload_state(PayloadState::Started)
1372 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001373 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001374
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001375 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1376 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001377 Ok(())
1378 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001379 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001380 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001381 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001382 }
Inseob Kim2444af92021-08-31 01:22:50 +09001383
Inseob Kimc7d28c72021-10-25 14:28:10 +00001384 fn notifyPayloadReady(&self) -> binder::Result<()> {
1385 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001386 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001387 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001388 vm.update_payload_state(PayloadState::Ready)
1389 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001390 vm.callbacks.notify_payload_ready(cid);
1391 Ok(())
1392 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001393 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001394 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001395 }
1396 }
1397
Inseob Kimc7d28c72021-10-25 14:28:10 +00001398 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1399 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001400 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001401 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001402 vm.update_payload_state(PayloadState::Finished)
1403 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001404 vm.callbacks.notify_payload_finished(cid, exit_code);
1405 Ok(())
1406 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001407 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001408 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001409 }
1410 }
1411
Alan Stokes2bead0d2022-09-05 16:58:34 +01001412 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001413 let cid = self.cid;
1414 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001415 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001416 vm.update_payload_state(PayloadState::Finished)
1417 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001418 vm.callbacks.notify_error(cid, error_code, message);
1419 Ok(())
1420 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001421 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001422 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001423 }
1424 }
Alice Wangc2fec932023-02-23 16:24:02 +00001425
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001426 fn getSecretkeeper(&self) -> binder::Result<Option<Strong<dyn ISecretkeeper>>> {
Shikha Panwar8187ca22024-01-04 08:33:08 +00001427 let sk = if is_secretkeeper_present() {
1428 Some(binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?)
1429 } else {
1430 None
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001431 };
Shikha Panwar8187ca22024-01-04 08:33:08 +00001432 Ok(sk.map(|s| BnSecretkeeper::new_binder(SecretkeeperProxy(s), BinderFeatures::default())))
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001433 }
1434
Alice Wang4e3015d2023-10-10 09:35:37 +00001435 fn requestAttestation(&self, csr: &[u8]) -> binder::Result<Vec<Certificate>> {
Alice Wangbff017f2023-11-09 14:43:28 +00001436 GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32)
Alice Wangc2fec932023-02-23 16:24:02 +00001437 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001438}
1439
Shikha Panwar8187ca22024-01-04 08:33:08 +00001440fn is_secretkeeper_present() -> bool {
1441 binder::is_declared(SECRETKEEPER_IDENTIFIER)
1442 .expect("Could not check for declared Secretkeeper interface")
1443}
1444
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001445impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001446 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001447 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001448 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001449 BinderFeatures::default(),
1450 )
1451 }
1452}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001453
1454#[cfg(test)]
1455mod tests {
1456 use super::*;
1457
1458 #[test]
1459 fn test_is_allowed_label_for_partition() -> Result<()> {
1460 let expected_results = vec![
1461 ("u:object_r:system_file:s0", true),
1462 ("u:object_r:apk_data_file:s0", true),
1463 ("u:object_r:app_data_file:s0", false),
1464 ("u:object_r:app_data_file:s0:c512,c768", false),
1465 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1466 ("invalid", false),
1467 ("user:role:apk_data_file:severity:categories", true),
1468 ("user:role:apk_data_file:severity:categories:extraneous", false),
1469 ];
1470
1471 for (label, expected_valid) in expected_results {
1472 let context = SeContext::new(label)?;
1473 let result = check_label_is_allowed(&context);
1474 if expected_valid {
1475 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1476 } else if result.is_ok() {
1477 bail!("Expected label {} to be disallowed", label);
1478 }
1479 }
1480 Ok(())
1481 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001482
1483 #[test]
1484 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1485 let apk = tempfile::tempfile().unwrap();
1486 let idsig = tempfile::tempfile().unwrap();
1487
1488 let ret = create_or_update_idsig_file(
1489 &ParcelFileDescriptor::new(apk),
1490 &ParcelFileDescriptor::new(idsig),
1491 );
1492 assert!(ret.is_err(), "should fail");
1493 Ok(())
1494 }
1495
1496 #[test]
1497 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1498 let tmp_dir = tempfile::TempDir::new().unwrap();
1499 let apk = File::open(tmp_dir.path()).unwrap();
1500 let idsig = tempfile::tempfile().unwrap();
1501
1502 let ret = create_or_update_idsig_file(
1503 &ParcelFileDescriptor::new(apk),
1504 &ParcelFileDescriptor::new(idsig),
1505 );
1506 assert!(ret.is_err(), "should fail");
1507 Ok(())
1508 }
1509
1510 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1511 /// on ext4 filesystem is passed.
1512 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1513 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1514 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1515 #[test]
1516 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1517 // APEXes are backed by the ext4.
1518 let apk = File::open("/apex/com.android.virt/").unwrap();
1519 let idsig = tempfile::tempfile().unwrap();
1520
1521 let ret = create_or_update_idsig_file(
1522 &ParcelFileDescriptor::new(apk),
1523 &ParcelFileDescriptor::new(idsig),
1524 );
1525 assert!(ret.is_err(), "should fail");
1526 Ok(())
1527 }
Jiyong Park8d192952023-06-26 14:29:51 +09001528
1529 #[test]
1530 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1531 use std::io::Seek;
1532
1533 // Pick any APK
1534 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1535 let mut idsig = tempfile::tempfile().unwrap();
1536
1537 create_or_update_idsig_file(
1538 &ParcelFileDescriptor::new(apk.try_clone()?),
1539 &ParcelFileDescriptor::new(idsig.try_clone()?),
1540 )?;
1541 let modified_orig = idsig.metadata()?.modified()?;
1542 apk.rewind()?;
1543 idsig.rewind()?;
1544
1545 // Call the function again
1546 create_or_update_idsig_file(
1547 &ParcelFileDescriptor::new(apk.try_clone()?),
1548 &ParcelFileDescriptor::new(idsig.try_clone()?),
1549 )?;
1550 let modified_new = idsig.metadata()?.modified()?;
1551 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1552 Ok(())
1553 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001554
1555 #[test]
Shikha Panwar9ae2e622024-01-30 12:22:30 +00001556 fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
1557 use std::io::Read;
1558
1559 // Pick any APK
1560 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1561 let idsig_empty = tempfile::tempfile().unwrap();
1562 let mut idsig_invalid = tempfile::tempfile().unwrap();
1563 idsig_invalid.write_all(b"Oops")?;
1564
1565 // Create new idsig
1566 create_or_update_idsig_file(
1567 &ParcelFileDescriptor::new(apk.try_clone()?),
1568 &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
1569 )?;
1570 apk.rewind()?;
1571
1572 // Update idsig_invalid
1573 create_or_update_idsig_file(
1574 &ParcelFileDescriptor::new(apk.try_clone()?),
1575 &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
1576 )?;
1577
1578 // Ensure the 2 idsig files have same size!
1579 assert!(
1580 idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
1581 "idsig files differ in size"
1582 );
1583 // Ensure the 2 idsig files have same content!
1584 for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
1585 assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
1586 }
1587 Ok(())
1588 }
1589 #[test]
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001590 fn test_append_kernel_param_first_param() {
1591 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1592 append_kernel_param("foo=1", &mut vm_config);
1593 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1594 }
1595
1596 #[test]
1597 fn test_append_kernel_param() {
1598 let mut vm_config =
1599 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1600 append_kernel_param("bar=42", &mut vm_config);
1601 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1602 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09001603
1604 #[test]
1605 fn test_create_dtbo_for_vendor_image() -> Result<()> {
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001606 let vendor_hashtree_descriptor_root_digest = String::from("foo");
1607 let vendor_hashtree_descriptor_root_digest =
1608 vendor_hashtree_descriptor_root_digest.as_bytes();
Seungjae Yooec3bc522023-11-09 10:14:30 +09001609
1610 let tmp_dir = tempfile::TempDir::new()?;
1611 let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
1612
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001613 create_dtbo_for_vendor_image(vendor_hashtree_descriptor_root_digest, &dtbo_path)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +09001614
1615 let data = std::fs::read(dtbo_path)?;
1616 let fdt = Fdt::from_slice(&data).unwrap();
1617
1618 let fragment_node_path = CString::new("/fragment@0")?;
1619 let fragment_node = fdt.node(fragment_node_path.as_c_str()).unwrap();
1620 let Some(fragment_node) = fragment_node else {
1621 bail!("fragment_node shouldn't be None.");
1622 };
1623 let target_path_prop_name = CString::new("target-path")?;
1624 let target_path_from_dtbo =
1625 fragment_node.getprop(target_path_prop_name.as_c_str()).unwrap();
1626 let target_path_expected = CString::new("/")?;
1627 assert_eq!(target_path_from_dtbo, Some(target_path_expected.to_bytes_with_nul()));
1628
1629 let avf_node_path = CString::new("/fragment@0/__overlay__/avf")?;
1630 let avf_node = fdt.node(avf_node_path.as_c_str()).unwrap();
1631 let Some(avf_node) = avf_node else {
1632 bail!("avf_node shouldn't be None.");
1633 };
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001634 let vendor_hashtree_descriptor_root_digest_name =
1635 CString::new("vendor_hashtree_descriptor_root_digest")?;
1636 let digest_from_dtbo =
1637 avf_node.getprop(vendor_hashtree_descriptor_root_digest_name.as_c_str()).unwrap();
1638 assert_eq!(digest_from_dtbo, Some(vendor_hashtree_descriptor_root_digest));
Seungjae Yooec3bc522023-11-09 10:14:30 +09001639
1640 tmp_dir.close()?;
1641 Ok(())
1642 }
1643
1644 #[test]
1645 fn test_create_dtbo_for_vendor_image_throws_error_if_already_exists() -> Result<()> {
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001646 let vendor_hashtree_descriptor_root_digest = String::from("foo");
1647 let vendor_hashtree_descriptor_root_digest =
1648 vendor_hashtree_descriptor_root_digest.as_bytes();
Seungjae Yooec3bc522023-11-09 10:14:30 +09001649
1650 let tmp_dir = tempfile::TempDir::new()?;
1651 let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
1652
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001653 create_dtbo_for_vendor_image(vendor_hashtree_descriptor_root_digest, &dtbo_path)?;
Seungjae Yooec3bc522023-11-09 10:14:30 +09001654
Seungjae Yoo192e99c2023-12-15 16:42:39 +09001655 let ret_second_trial =
1656 create_dtbo_for_vendor_image(vendor_hashtree_descriptor_root_digest, &dtbo_path);
Seungjae Yooec3bc522023-11-09 10:14:30 +09001657 assert!(ret_second_trial.is_err(), "should fail");
1658
1659 tmp_dir.close()?;
1660 Ok(())
1661 }
Inseob Kim46257382024-01-03 15:41:22 +09001662
1663 fn test_extract_os_name_from_config_path(
1664 path: &Path,
1665 expected_result: Option<&str>,
1666 ) -> Result<()> {
1667 let result = extract_os_name_from_config_path(path);
1668 if result.as_deref() != expected_result {
1669 bail!("Expected {:?} but was {:?}", expected_result, &result)
1670 }
1671 Ok(())
1672 }
1673
1674 #[test]
1675 fn test_extract_os_name_from_microdroid_config() -> Result<()> {
1676 test_extract_os_name_from_config_path(
1677 Path::new("/apex/com.android.virt/etc/microdroid.json"),
1678 Some("microdroid"),
1679 )
1680 }
1681
1682 #[test]
1683 fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
1684 test_extract_os_name_from_config_path(
1685 Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
1686 Some("microdroid_gki-android14-6.1"),
1687 )
1688 }
1689
1690 #[test]
1691 fn test_extract_os_name_from_invalid_path() -> Result<()> {
1692 test_extract_os_name_from_config_path(
1693 Path::new("/apex/com.android.virt/etc/microdroid.img"),
1694 None,
1695 )
1696 }
1697
1698 #[test]
1699 fn test_extract_os_name_from_configs() -> Result<()> {
1700 let tmp_dir = tempfile::TempDir::new()?;
1701 let tmp_dir_path = tmp_dir.path().to_owned();
1702
1703 let mut os_names: HashSet<String> = HashSet::new();
1704 os_names.insert("microdroid".to_owned());
1705 os_names.insert("microdroid_gki-android14-6.1".to_owned());
1706 os_names.insert("microdroid_gki-android15-6.1".to_owned());
1707
1708 // config files
1709 for os_name in &os_names {
1710 std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
1711 }
1712
1713 // fake files not related to configs
1714 std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
1715 std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
1716
1717 let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
1718 Some(s) => s.to_owned(),
1719 None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
1720 };
1721
1722 let result = extract_os_names_from_configs(&glob_pattern)?;
1723 if result != os_names {
1724 bail!("Expected {:?} but was {:?}", os_names, result);
1725 }
1726 Ok(())
1727 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001728}
Shikha Panwar5d6a6752023-12-14 22:08:26 +00001729
1730struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
1731
1732impl Interface for SecretkeeperProxy {}
1733
1734impl ISecretkeeper for SecretkeeperProxy {
1735 fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
1736 // Pass the request to the channel, and read the response.
1737 self.0.processSecretManagementRequest(req)
1738 }
1739
1740 fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
1741 let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
1742 Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
1743 }
1744
1745 fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
1746 self.0.deleteIds(ids)
1747 }
1748
1749 fn deleteAll(&self) -> binder::Result<()> {
1750 self.0.deleteAll()
1751 }
1752}
1753
1754struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
1755
1756impl Interface for AuthGraphKeyExchangeProxy {}
1757
1758impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
1759 fn create(&self) -> binder::Result<SessionInitiationInfo> {
1760 self.0.create()
1761 }
1762
1763 fn init(
1764 &self,
1765 peer_pub_key: &PubKey,
1766 peer_id: &Identity,
1767 peer_nonce: &[u8],
1768 peer_version: i32,
1769 ) -> binder::Result<KeInitResult> {
1770 self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
1771 }
1772
1773 fn finish(
1774 &self,
1775 peer_pub_key: &PubKey,
1776 peer_id: &Identity,
1777 peer_signature: &SessionIdSignature,
1778 peer_nonce: &[u8],
1779 peer_version: i32,
1780 own_key: &Key,
1781 ) -> binder::Result<SessionInfo> {
1782 self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
1783 }
1784
1785 fn authenticationComplete(
1786 &self,
1787 peer_signature: &SessionIdSignature,
1788 shared_keys: &[AuthgraphArc; 2],
1789 ) -> binder::Result<[AuthgraphArc; 2]> {
1790 self.0.authenticationComplete(peer_signature, shared_keys)
1791 }
1792}