blob: 70e9be9ed212e3609ffc85c23a65d4ce6fbb991e [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;
Inseob Kim7307a892023-09-14 13:37:58 +090021use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VfioDevice, 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};
Alan Stokes25f69362023-03-06 16:51:54 +000055use anyhow::{anyhow, bail, Context, Result};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090056use apkverify::{HashAlgorithm, V4Signature};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090057use avflog::LogResult;
Alan Stokes0e82b502022-08-08 14:44:48 +010058use binder::{
David Brazdilafc9a9e2023-01-12 16:08:10 +000059 self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor,
60 Status, StatusCode, Strong,
Jiyong Park2227eaa2023-08-04 11:59:18 +090061 IntoBinderResult,
Andrew Walbrana89fc132021-03-17 17:08:36 +000062};
David Brazdilf50c7a62023-04-19 14:22:42 +000063use disk::QcowFile;
David Brazdil49f96f52022-12-16 21:29:13 +000064use lazy_static::lazy_static;
Seungjae Yooec3bc522023-11-09 10:14:30 +090065use libfdt::Fdt;
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +000066use log::{debug, error, info, warn};
Seungjae Yoofd9a0622022-10-14 10:01:29 +090067use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Inseob Kim0168b462022-12-27 14:54:35 +090068use nix::unistd::pipe;
David Brazdil73988ea2022-11-11 15:10:32 +000069use rpcbinder::RpcServer;
Alan Stokes25f69362023-03-06 16:51:54 +000070use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090071use semver::VersionReq;
Inseob Kim6ef80972023-07-20 17:23:36 +090072use std::collections::HashSet;
Andrew Walbrandff3b942021-06-09 15:20:36 +000073use std::convert::TryInto;
Seungjae Yooec3bc522023-11-09 10:14:30 +090074use std::ffi::{CStr, CString};
Inseob Kim6ef80972023-07-20 17:23:36 +090075use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions};
David Brazdilf50c7a62023-04-19 14:22:42 +000076use std::io::{BufRead, BufReader, Error, ErrorKind, Write};
Nikita Ioffe5776f082023-02-10 21:38:26 +000077use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbrand3a84182021-09-07 14:48:52 +000078use std::os::unix::io::{FromRawFd, IntoRawFd};
David Brazdilafc9a9e2023-01-12 16:08:10 +000079use std::os::unix::raw::pid_t;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000080use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000081use std::sync::{Arc, Mutex, Weak};
Seungjae Yooec3bc522023-11-09 10:14:30 +090082use vbmeta::VbMetaImage;
Andrew Walbrancc0db522021-07-12 17:03:42 +000083use vmconfig::VmConfig;
David Brazdilafc9a9e2023-01-12 16:08:10 +000084use vsock::VsockStream;
Jooyung Han35edb8f2021-07-01 16:17:16 +090085use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000086
David Brazdil41d1a872022-10-05 14:44:19 +010087/// The unique ID of a VM used (together with a port number) for vsock communication.
88pub type Cid = u32;
89
David Brazdil4b4c5102022-12-19 22:56:20 +000090pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
91
Jooyung Han95884632021-07-06 22:27:54 +090092/// The size of zero.img.
93/// Gaps in composite disk images are filled with a shared zero.img.
94const ZERO_FILLER_SIZE: u64 = 4096;
95
David Brazdilf50c7a62023-04-19 14:22:42 +000096/// Magic string for the instance image
97const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
98
99/// Version of the instance image format
100const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
101
Alan Stokes0d1ef782022-09-27 13:46:35 +0100102const MICRODROID_OS_NAME: &str = "microdroid";
103
David Brazdilf50c7a62023-04-19 14:22:42 +0000104const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
105
Seungjae Yooec3bc522023-11-09 10:14:30 +0900106/// Roughly estimated sufficient size for storing vendor public key into DTBO.
107const EMPTY_VENDOR_DT_OVERLAY_BUF_SIZE: usize = 10000;
108
David Brazdilf50c7a62023-04-19 14:22:42 +0000109/// crosvm requires all partitions to be a multiple of 4KiB.
110const PARTITION_GRANULARITY_BYTES: u64 = 4096;
111
David Brazdil49f96f52022-12-16 21:29:13 +0000112lazy_static! {
David Brazdil4b4c5102022-12-19 22:56:20 +0000113 pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> =
114 wait_for_interface(BINDER_SERVICE_IDENTIFIER)
115 .expect("Could not connect to VirtualizationServiceInternal");
David Brazdil49f96f52022-12-16 21:29:13 +0000116}
117
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000118fn create_or_update_idsig_file(
119 input_fd: &ParcelFileDescriptor,
120 idsig_fd: &ParcelFileDescriptor,
121) -> Result<()> {
122 let mut input = clone_file(input_fd)?;
123 let metadata = input.metadata().context("failed to get input metadata")?;
124 if !metadata.is_file() {
125 bail!("input is not a regular file");
126 }
Alan Stokes25f69362023-03-06 16:51:54 +0000127 let mut sig =
128 V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
129 .context("failed to create idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000130
131 let mut output = clone_file(idsig_fd)?;
Jiyong Park8d192952023-06-26 14:29:51 +0900132
133 // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
134 // if the idsig file already has the same APK digest.
135 if output.metadata()?.len() > 0 {
136 if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
137 if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
138 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
139 return Ok(());
140 }
141 }
142 // if we fail to read v4signature from output, that's fine. User can pass a random file.
143 // We will anyway overwrite the file to the v4signature generated from input_fd.
144 }
145
Nikita Ioffec09b0492022-12-14 20:18:33 +0000146 output.set_len(0).context("failed to set_len on the idsig output")?;
147 sig.write_into(&mut output).context("failed to write idsig")?;
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000148 Ok(())
149}
150
Alan Stokes25f69362023-03-06 16:51:54 +0000151fn get_current_sdk() -> Result<u32> {
152 let current_sdk = system_properties::read("ro.build.version.sdk")?;
153 let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
154 current_sdk.parse().context("Malformed SDK version")
155}
156
David Brazdil4b4c5102022-12-19 22:56:20 +0000157pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
158 for dir_entry in read_dir(path)? {
159 remove_file(dir_entry?.path())?;
160 }
161 Ok(())
David Brazdil528e0472022-10-10 15:06:02 +0100162}
163
David Brazdil528e0472022-10-10 15:06:02 +0100164/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
David Brazdil49f96f52022-12-16 21:29:13 +0000165#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000166pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900167 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000168}
169
Shikha Panward8e35422021-10-11 13:51:27 +0000170impl Interface for VirtualizationService {
171 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
172 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
173 let state = &mut *self.state.lock().unwrap();
174 let vms = state.vms();
175 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
176 for vm in vms {
177 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
178 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
179 .or(Err(StatusCode::UNKNOWN_ERROR))?;
180 writeln!(file, "\tPayload state {:?}", vm.payload_state())
181 .or(Err(StatusCode::UNKNOWN_ERROR))?;
182 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
183 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
184 .or(Err(StatusCode::UNKNOWN_ERROR))?;
185 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
186 .or(Err(StatusCode::UNKNOWN_ERROR))?;
Shikha Panward8e35422021-10-11 13:51:27 +0000187 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
188 .or(Err(StatusCode::UNKNOWN_ERROR))?;
189 }
190 Ok(())
191 }
192}
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000193impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000194 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
195 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000196 ///
197 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000198 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000199 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000200 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900201 console_out_fd: Option<&ParcelFileDescriptor>,
202 console_in_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000203 log_fd: Option<&ParcelFileDescriptor>,
204 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000205 let mut is_protected = false;
Jiyong Parke6fb1672023-06-26 16:45:55 +0900206 let ret = self.create_vm_internal(
207 config,
208 console_out_fd,
209 console_in_fd,
210 log_fd,
211 &mut is_protected,
212 );
Seungjae Yoo0a8c84c2022-07-11 08:19:15 +0000213 write_vm_creation_stats(config, is_protected, &ret);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000214 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000215 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000216
Andrew Walbrandff3b942021-06-09 15:20:36 +0000217 /// Initialise an empty partition image of the given size to be used as a writable partition.
218 fn initializeWritablePartition(
219 &self,
220 image_fd: &ParcelFileDescriptor,
Alan Stokesff0005f2023-01-30 09:53:00 +0000221 size_bytes: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900222 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000223 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900224 check_manage_access()?;
Jiyong Park2227eaa2023-08-04 11:59:18 +0900225 let size_bytes = size_bytes
226 .try_into()
227 .with_context(|| format!("Invalid size: {}", size_bytes))
228 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000229 let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
230 let image = clone_file(image_fd)?;
231 // initialize the file. Any data in the file will be erased.
Jiyong Park2227eaa2023-08-04 11:59:18 +0900232 image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
233 let mut part = QcowFile::new(image, size_bytes)
234 .context("Failed to create QCOW2 image")
235 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000236
237 match partition_type {
238 PartitionType::RAW => Ok(()),
239 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
240 PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part),
241 _ => Err(Error::new(
242 ErrorKind::Unsupported,
243 format!("Unsupported partition type {:?}", partition_type),
244 )),
245 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900246 .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
247 .or_service_specific_exception(-1)?;
David Brazdilf50c7a62023-04-19 14:22:42 +0000248
249 Ok(())
Andrew Walbrandff3b942021-06-09 15:20:36 +0000250 }
251
Jiyong Park0a248432021-08-20 23:32:39 +0900252 /// Creates or update the idsig file by digesting the input APK file.
253 fn createOrUpdateIdsigFile(
254 &self,
255 input_fd: &ParcelFileDescriptor,
256 idsig_fd: &ParcelFileDescriptor,
257 ) -> binder::Result<()> {
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900258 check_manage_access()?;
259
Jiyong Park2227eaa2023-08-04 11:59:18 +0900260 create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
Jiyong Park0a248432021-08-20 23:32:39 +0900261 Ok(())
262 }
263
Andrew Walbran320b5602021-03-04 16:11:12 +0000264 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
265 /// and as such is only permitted from the shell user.
266 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
David Brazdil209074a2023-01-12 16:44:51 +0000267 // Delegate to the global service, including checking the debug permission.
David Brazdild4f51a52023-01-11 14:09:27 +0000268 GLOBAL_SERVICE.debugListVms()
Andrew Walbran320b5602021-03-04 16:11:12 +0000269 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900270
271 /// Get a list of assignable device types.
272 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
273 // Delegate to the global service, including checking the permission.
274 GLOBAL_SERVICE.getAssignableDevices()
275 }
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100276
277 /// Returns whether given feature is enabled
278 fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
279 check_manage_access()?;
280
281 // This approach is quite cumbersome, but will do the work for the short term.
282 // TODO(b/298012279): make this scalable.
283 match feature {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100284 FEATURE_DICE_CHANGES => Ok(cfg!(dice_changes)),
Alan Stokes27f3ef02023-09-29 15:09:35 +0100285 FEATURE_MULTI_TENANT => Ok(cfg!(multi_tenant)),
Nikita Ioffe631717e2023-09-05 13:38:07 +0100286 FEATURE_VENDOR_MODULES => Ok(cfg!(vendor_modules)),
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100287 _ => {
Alan Stokes7f27c0d2023-09-07 16:22:58 +0100288 warn!("unknown feature {feature}");
Nikita Ioffef7c742a2023-09-04 16:57:59 +0100289 Ok(false)
290 }
291 }
292 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000293}
294
Jiyong Park8611a6c2021-07-09 18:17:44 +0900295impl VirtualizationService {
296 pub fn init() -> VirtualizationService {
David Brazdil49f96f52022-12-16 21:29:13 +0000297 VirtualizationService::default()
Jiyong Park8611a6c2021-07-09 18:17:44 +0900298 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000299
David Brazdil209074a2023-01-12 16:44:51 +0000300 fn create_vm_context(
301 &self,
302 requester_debug_pid: pid_t,
303 ) -> binder::Result<(VmContext, Cid, PathBuf)> {
David Brazdil8cf8f482022-11-23 14:21:26 +0000304 const NUM_ATTEMPTS: usize = 5;
305
306 for _ in 0..NUM_ATTEMPTS {
Charisee96113f32023-01-26 09:00:42 +0000307 let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?;
David Brazdild4f51a52023-01-11 14:09:27 +0000308 let cid = vm_context.getCid()? as Cid;
309 let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
David Brazdil8cf8f482022-11-23 14:21:26 +0000310 let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
311
312 // Start VM service listening for connections from the new CID on port=CID.
David Brazdil8cf8f482022-11-23 14:21:26 +0000313 let port = cid;
David Brazdil3238da42022-11-18 10:04:51 +0000314 match RpcServer::new_vsock(service, cid, port) {
David Brazdil8cf8f482022-11-23 14:21:26 +0000315 Ok(vm_server) => {
316 vm_server.start();
David Brazdild4f51a52023-01-11 14:09:27 +0000317 return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir));
David Brazdil8cf8f482022-11-23 14:21:26 +0000318 }
319 Err(err) => {
320 warn!("Could not start RpcServer on port {}: {}", port, err);
321 }
322 }
323 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900324 Err(anyhow!("Too many attempts to create VM context failed"))
325 .or_service_specific_exception(-1)
David Brazdil8cf8f482022-11-23 14:21:26 +0000326 }
327
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000328 fn create_vm_internal(
329 &self,
330 config: &VirtualMachineConfig,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900331 console_out_fd: Option<&ParcelFileDescriptor>,
332 console_in_fd: Option<&ParcelFileDescriptor>,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000333 log_fd: Option<&ParcelFileDescriptor>,
334 is_protected: &mut bool,
335 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
David Brazdil209074a2023-01-12 16:44:51 +0000336 let requester_uid = get_calling_uid();
337 let requester_debug_pid = get_calling_pid();
338
Nikita Ioffe631717e2023-09-05 13:38:07 +0100339 check_config_features(config)?;
340
David Brazdil209074a2023-01-12 16:44:51 +0000341 // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
342 let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?;
Inseob Kim1119d702022-05-02 18:01:58 +0900343
Alan Stokes7bc146c2022-10-20 17:10:32 +0100344 let is_custom = match config {
345 VirtualMachineConfig::RawConfig(_) => true,
346 VirtualMachineConfig::AppConfig(config) => {
347 // Some features are reserved for platform apps only, even when using
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100348 // VirtualMachineAppConfig. Almost all of these features are grouped in the
349 // CustomConfig struct:
Alan Stokes7bc146c2022-10-20 17:10:32 +0100350 // - controlling CPUs;
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100351 // - specifying a config file in the APK; (this one is not part of CustomConfig)
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100352 // - gdbPort is set, meaning that crosvm will start a gdb server;
Inseob Kim6ef80972023-07-20 17:23:36 +0900353 // - using anything other than the default kernel;
354 // - specifying devices to be assigned.
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100355 config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_))
Inseob Kim1119d702022-05-02 18:01:58 +0900356 }
Alan Stokes7bc146c2022-10-20 17:10:32 +0100357 };
358 if is_custom {
359 check_use_custom_virtual_machine()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900360 }
361
Nikita Ioffe5776f082023-02-10 21:38:26 +0000362 let gdb_port = extract_gdb_port(config);
363
364 // Additional permission checks if caller request gdb.
365 if gdb_port.is_some() {
366 check_gdb_allowed(config)?;
367 }
368
Seungjae Yooec3bc522023-11-09 10:14:30 +0900369 let vendor_public_key = extract_vendor_public_key(config)
370 .context("Failed to extract vendor public key")
371 .or_service_specific_exception(-1)?;
372 let dtbo_vendor = if let Some(vendor_public_key) = vendor_public_key {
373 let dtbo_for_vendor_image = temporary_directory.join("dtbo_vendor");
374 create_dtbo_for_vendor_image(&vendor_public_key, &dtbo_for_vendor_image)
375 .context("Failed to write vendor_public_key")
376 .or_service_specific_exception(-1)?;
377 let file = File::open(dtbo_for_vendor_image)
378 .context("Failed to open dtbo_vendor")
379 .or_service_specific_exception(-1)?;
380 Some(file)
381 } else {
382 None
383 };
384
Jaewan Kim61f86142023-03-28 15:12:52 +0900385 let debug_level = match config {
386 VirtualMachineConfig::AppConfig(config) => config.debugLevel,
387 _ => DebugLevel::NONE,
388 };
389 let debug_config = DebugConfig::new(debug_level);
390
391 let ramdump = if debug_config.is_ramdump_needed() {
Jiyong Parked180932023-02-24 19:55:41 +0900392 Some(prepare_ramdump_file(&temporary_directory)?)
393 } else {
394 None
395 };
396
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000397 let state = &mut *self.state.lock().unwrap();
Jiyong Parke6fb1672023-06-26 16:45:55 +0900398 let console_out_fd =
399 clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?;
400 let console_in_fd = console_in_fd.map(clone_file).transpose()?;
Jaewan Kim61f86142023-03-28 15:12:52 +0900401 let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000402
403 // Counter to generate unique IDs for temporary image files.
404 let mut next_temporary_image_id = 0;
405 // Files which are referred to from composite images. These must be mapped to the crosvm
406 // child process, and not closed before it is started.
407 let mut indirect_files = vec![];
408
Alan Stokes7bc146c2022-10-20 17:10:32 +0100409 let (is_app_config, config) = match config {
410 VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
411 VirtualMachineConfig::AppConfig(config) => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900412 let config = load_app_config(config, &debug_config, &temporary_directory)
413 .or_service_specific_exception_with(-1, |e| {
Jaewan Kim61f86142023-03-28 15:12:52 +0900414 *is_protected = config.protectedVm;
415 let message = format!("Failed to load app config: {:?}", e);
416 error!("{}", message);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900417 message
Jaewan Kim61f86142023-03-28 15:12:52 +0900418 })?;
Alan Stokes7bc146c2022-10-20 17:10:32 +0100419 (true, BorrowedOrOwned::Owned(config))
420 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000421 };
422 let config = config.as_ref();
423 *is_protected = config.protectedVm;
424
425 // Check if partition images are labeled incorrectly. This is to prevent random images
426 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
Alan Stokes3e5eec12023-09-07 12:10:00 +0100427 // being loaded in a pVM. This applies to everything but the instance image in the raw
428 // config, and everything but the non-executable, generated partitions in the app
429 // config.
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000430 config
431 .disks
432 .iter()
433 .flat_map(|disk| disk.partitions.iter())
434 .filter(|partition| {
435 if is_app_config {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100436 !is_safe_app_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000437 } else {
Alice Wangc206b9b2023-08-28 14:13:51 +0000438 !is_safe_raw_partition(&partition.label)
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000439 }
440 })
441 .try_for_each(check_label_for_partition)
Jiyong Park2227eaa2023-08-04 11:59:18 +0900442 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000443
Alan Stokes185fe112023-01-10 16:20:55 +0000444 let kernel = maybe_clone_file(&config.kernel)?;
445 let initrd = maybe_clone_file(&config.initrd)?;
446
447 // In a protected VM, we require custom kernels to come from a trusted source (b/237054515).
448 if config.protectedVm {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900449 check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?;
Alan Stokes185fe112023-01-10 16:20:55 +0000450 }
451
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000452 let zero_filler_path = temporary_directory.join("zero.img");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900453 write_zero_filler(&zero_filler_path)
454 .context("Failed to make composite image")
455 .with_log()
456 .or_service_specific_exception(-1)?;
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000457
458 // Assemble disk images if needed.
459 let disks = config
460 .disks
461 .iter()
462 .map(|disk| {
463 assemble_disk_image(
464 disk,
465 &zero_filler_path,
466 &temporary_directory,
467 &mut next_temporary_image_id,
468 &mut indirect_files,
469 )
470 })
471 .collect::<Result<Vec<DiskFile>, _>>()?;
472
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000473 let (cpus, host_cpu_topology) = match config.cpuTopology {
474 CpuTopology::MATCH_HOST => (None, true),
475 CpuTopology::ONE_CPU => (NonZeroU32::new(1), false),
476 val => {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900477 return Err(anyhow!("Failed to parse CPU topology value {:?}", val))
478 .with_log()
479 .or_service_specific_exception(-1);
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000480 }
481 };
482
Inseob Kim7307a892023-09-14 13:37:58 +0900483 let vfio_devices = if !config.devices.is_empty() {
Inseob Kim6ef80972023-07-20 17:23:36 +0900484 let mut set = HashSet::new();
485 for device in config.devices.iter() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900486 let path = canonicalize(device)
487 .with_context(|| format!("can't canonicalize {device}"))
488 .or_service_specific_exception(-1)?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900489 if !set.insert(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900490 return Err(anyhow!("duplicated device {device}"))
491 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kim6ef80972023-07-20 17:23:36 +0900492 }
493 }
Inseob Kim7307a892023-09-14 13:37:58 +0900494 GLOBAL_SERVICE
495 .bindDevicesToVfioDriver(&config.devices)?
496 .into_iter()
497 .map(|x| VfioDevice {
498 sysfs_path: PathBuf::from(&x.sysfsPath),
Jaewan Kim35e818d2023-10-18 05:36:38 +0000499 dtbo_label: x.dtboLabel,
Inseob Kim7307a892023-09-14 13:37:58 +0900500 })
501 .collect::<Vec<_>>()
502 } else {
503 vec![]
504 };
Inseob Kim6ef80972023-07-20 17:23:36 +0900505
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000506 // Actually start the VM.
507 let crosvm_config = CrosvmConfig {
508 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000509 name: config.name.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000510 bootloader: maybe_clone_file(&config.bootloader)?,
Alan Stokes185fe112023-01-10 16:20:55 +0000511 kernel,
512 initrd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000513 disks,
514 params: config.params.to_owned(),
515 protected: *is_protected,
Jaewan Kim61f86142023-03-28 15:12:52 +0900516 debug_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000517 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000518 cpus,
519 host_cpu_topology,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900520 task_profiles: config.taskProfiles.clone(),
Jiyong Parke6fb1672023-06-26 16:45:55 +0900521 console_out_fd,
522 console_in_fd,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000523 log_fd,
Jiyong Parked180932023-02-24 19:55:41 +0900524 ramdump,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000525 indirect_files,
526 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900527 detect_hangup: is_app_config,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000528 gdb_port,
Inseob Kim7307a892023-09-14 13:37:58 +0900529 vfio_devices,
Seungjae Yooec3bc522023-11-09 10:14:30 +0900530 dtbo_vendor,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000531 };
532 let instance = Arc::new(
David Brazdil528e0472022-10-10 15:06:02 +0100533 VmInstance::new(
534 crosvm_config,
535 temporary_directory,
536 requester_uid,
537 requester_debug_pid,
538 vm_context,
539 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900540 .with_context(|| format!("Failed to create VM with config {:?}", config))
541 .with_log()
542 .or_service_specific_exception(-1)?,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000543 );
544 state.add_vm(Arc::downgrade(&instance));
545 Ok(VirtualMachine::create(instance))
546 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900547}
548
Seungjae Yooec3bc522023-11-09 10:14:30 +0900549fn extract_vendor_public_key(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
550 let VirtualMachineConfig::AppConfig(config) = config else {
551 return Ok(None);
552 };
553 let Some(custom_config) = &config.customConfig else {
554 return Ok(None);
555 };
556 let Some(file) = custom_config.vendorImage.as_ref() else {
557 return Ok(None);
558 };
559
560 let file = clone_file(file)?;
561 let size = file.metadata().context("Failed to get metadata from microdroid-vendor.img")?.len();
562 let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
563 .context("Failed to get vbmeta from microdroid-vendor.img")?;
564 let vendor_public_key = vbmeta
565 .public_key()
566 .ok_or(anyhow!("No public key is extracted from microdroid-vendor.img"))?
567 .to_vec();
568
569 Ok(Some(vendor_public_key))
570}
571
572fn create_dtbo_for_vendor_image(vendor_public_key: &[u8], dtbo: &PathBuf) -> Result<()> {
573 if dtbo.exists() {
574 return Err(anyhow!("DTBO file already exists"));
575 }
576
577 let mut buf = vec![0; EMPTY_VENDOR_DT_OVERLAY_BUF_SIZE];
578 let fdt = Fdt::create_empty_tree(buf.as_mut_slice())
579 .map_err(|e| anyhow!("Failed to create FDT: {:?}", e))?;
580 let mut root = fdt.root_mut().map_err(|e| anyhow!("Failed to get root node: {:?}", e))?;
581
582 let fragment_node_name = CString::new("fragment@0")?;
583 let mut fragment_node = root
584 .add_subnode(fragment_node_name.as_c_str())
585 .map_err(|e| anyhow!("Failed to create fragment node: {:?}", e))?;
586 let target_path_prop_name = CString::new("target-path")?;
587 let target_path = CString::new("/")?;
588 fragment_node
589 .setprop(target_path_prop_name.as_c_str(), target_path.to_bytes_with_nul())
590 .map_err(|e| anyhow!("Failed to set target-path: {:?}", e))?;
591 let overlay_node_name = CString::new("__overlay__")?;
592 let mut overlay_node = fragment_node
593 .add_subnode(overlay_node_name.as_c_str())
594 .map_err(|e| anyhow!("Failed to create overlay node: {:?}", e))?;
595
596 let avf_node_name = CString::new("avf")?;
597 let mut avf_node = overlay_node
598 .add_subnode(avf_node_name.as_c_str())
599 .map_err(|e| anyhow!("Failed to create avf node: {:?}", e))?;
600 let vendor_public_key_name = CString::new("vendor_public_key")?;
601 avf_node
602 .setprop(vendor_public_key_name.as_c_str(), vendor_public_key)
603 .map_err(|e| anyhow!("Failed to set avf/vendor_public_key: {:?}", e))?;
604
605 fdt.pack().map_err(|e| anyhow!("Failed to pack fdt: {:?}", e))?;
606 let mut file = File::create(dtbo)?;
607 file.write_all(fdt.as_slice())?;
608 Ok(file.flush()?)
609}
610
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000611fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900612 let file = OpenOptions::new()
613 .create_new(true)
614 .read(true)
615 .write(true)
616 .open(zero_filler_path)
617 .with_context(|| "Failed to create zero.img")?;
618 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000619 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900620}
621
David Brazdilf50c7a62023-04-19 14:22:42 +0000622fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
623 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
624 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
625 part.flush()
626}
627
628fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
629 part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
630 part.flush()
631}
632
633fn round_up(input: u64, granularity: u64) -> u64 {
634 if granularity == 0 {
635 return input;
636 }
637 // If the input is absurdly large we round down instead of up; it's going to fail anyway.
638 let result = input.checked_add(granularity - 1).unwrap_or(input);
639 (result / granularity) * granularity
640}
641
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000642/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
643///
644/// This may involve assembling a composite disk from a set of partition images.
645fn assemble_disk_image(
646 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900647 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000648 temporary_directory: &Path,
649 next_temporary_image_id: &mut u64,
650 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000651) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000652 let image = if !disk.partitions.is_empty() {
653 if disk.image.is_some() {
654 warn!("DiskImage {:?} contains both image and partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900655 return Err(anyhow!("DiskImage contains both image and partitions"))
656 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000657 }
658
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000659 let composite_image_filenames =
660 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
661 let (image, partition_files) = make_composite_image(
662 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900663 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000664 &composite_image_filenames.composite,
665 &composite_image_filenames.header,
666 &composite_image_filenames.footer,
667 )
Jiyong Park2227eaa2023-08-04 11:59:18 +0900668 .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
669 .with_log()
670 .or_service_specific_exception(-1)?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000671
672 // Pass the file descriptors for the various partition files to crosvm when it
673 // is run.
674 indirect_files.extend(partition_files);
675
676 image
677 } else if let Some(image) = &disk.image {
678 clone_file(image)?
679 } else {
680 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Jiyong Park2227eaa2023-08-04 11:59:18 +0900681 return Err(anyhow!("DiskImage didn't contain image or partitions."))
682 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000683 };
684
685 Ok(DiskFile { image, writable: disk.writable })
686}
687
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100688fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
689 if let Some(ref mut params) = vm_config.params {
690 params.push(' ');
691 params.push_str(param)
692 } else {
693 vm_config.params = Some(param.to_owned())
694 }
695}
696
Jooyung Han21e9b922021-06-26 04:14:16 +0900697fn load_app_config(
698 config: &VirtualMachineAppConfig,
Jaewan Kim61f86142023-03-28 15:12:52 +0900699 debug_config: &DebugConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +0900700 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900701) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000702 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
703 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900704 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900705
Shikha Panwar22e70452022-10-10 18:32:55 +0000706 let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
707 Some(clone_file(file)?)
708 } else {
709 None
710 };
711
Alan Stokes0d1ef782022-09-27 13:46:35 +0100712 let vm_payload_config = match &config.payload {
713 Payload::ConfigPath(config_path) => {
714 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
715 .with_context(|| format!("Couldn't read config from {}", config_path))?
716 }
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000717 Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100718 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900719
Alan Stokes0d1ef782022-09-27 13:46:35 +0100720 // For now, the only supported OS is Microdroid
721 let os_name = vm_payload_config.os.name.as_str();
722 if os_name != MICRODROID_OS_NAME {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000723 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900724 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000725
726 // It is safe to construct a filename based on the os_name because we've already checked that it
727 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900728 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
729 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000730 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900731
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +0100732 if let Some(custom_config) = &config.customConfig {
733 if let Some(file) = custom_config.customKernelImage.as_ref() {
734 vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
735 }
736 vm_config.taskProfiles = custom_config.taskProfiles.clone();
737 vm_config.gdbPort = custom_config.gdbPort;
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100738
739 if let Some(file) = custom_config.vendorImage.as_ref() {
Nikita Ioffeaa6858c2023-07-04 01:37:41 +0100740 add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
741 append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
Nikita Ioffe5dfddf22023-06-29 16:11:26 +0100742 }
Inseob Kim6ef80972023-07-20 17:23:36 +0900743
744 vm_config.devices = custom_config.devices.clone();
Nikita Ioffe26c35ed2023-06-05 17:49:08 +0100745 }
746
Andrew Walbrancc045902021-07-27 16:06:17 +0000747 if config.memoryMib > 0 {
748 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000749 }
750
Seungjae Yoo62085c02022-08-12 04:44:52 +0000751 vm_config.name = config.name.clone();
Andrew Walbran3994f002022-01-27 17:33:45 +0000752 vm_config.protectedVm = config.protectedVm;
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000753 vm_config.cpuTopology = config.cpuTopology;
Jiyong Park032615f2022-01-10 13:55:34 +0900754
Shikha Panwar22e70452022-10-10 18:32:55 +0000755 // Microdroid takes additional init ramdisk & (optionally) storage image
756 add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?;
757
758 // Include Microdroid payload disk (contains apks, idsigs) in vm config
759 add_microdroid_payload_images(
Alan Stokes0d1ef782022-09-27 13:46:35 +0100760 config,
Jaewan Kim61f86142023-03-28 15:12:52 +0900761 debug_config,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100762 temporary_directory,
763 apk_file,
764 idsig_file,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100765 &vm_payload_config,
766 &mut vm_config,
767 )?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900768
Andrew Walbrancc0db522021-07-12 17:03:42 +0000769 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900770}
771
Alan Stokes0d1ef782022-09-27 13:46:35 +0100772fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
773 let mut apk_zip = ZipArchive::new(apk_file)?;
774 let config_file = apk_zip.by_name(config_path)?;
775 Ok(serde_json::from_reader(config_file)?)
776}
777
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000778fn create_vm_payload_config(
779 payload_config: &VirtualMachinePayloadConfig,
780) -> Result<VmPayloadConfig> {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100781 // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
782 // parameters we've been given. Microdroid will do something equivalent inside the VM using the
783 // payload config that we send it via the metadata file.
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000784
785 let payload_binary_name = &payload_config.payloadBinaryName;
786 if payload_binary_name.contains('/') {
787 bail!("Payload binary name must not specify a path: {payload_binary_name}");
788 }
789
790 let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
791 Ok(VmPayloadConfig {
Alan Stokes0d1ef782022-09-27 13:46:35 +0100792 os: OsConfig { name: MICRODROID_OS_NAME.to_owned() },
793 task: Some(task),
794 apexes: vec![],
795 extra_apks: vec![],
796 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900797 export_tombstones: None,
Alan Stokes0d1ef782022-09-27 13:46:35 +0100798 enable_authfs: false,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000799 })
Alan Stokes0d1ef782022-09-27 13:46:35 +0100800}
801
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000802/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000803fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000804 temporary_directory: &Path,
805 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000806) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000807 let id = *next_temporary_image_id;
808 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000809 CompositeImageFilenames {
810 composite: temporary_directory.join(format!("composite-{}.img", id)),
811 header: temporary_directory.join(format!("composite-{}-header.img", id)),
812 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
813 }
814}
815
816/// Filenames for a composite disk image, including header and footer partitions.
817#[derive(Clone, Debug, Eq, PartialEq)]
818struct CompositeImageFilenames {
819 /// The composite disk image itself.
820 composite: PathBuf,
821 /// The header partition image.
822 header: PathBuf,
823 /// The footer partition image.
824 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000825}
826
Jiyong Park753553b2021-07-12 21:21:09 +0900827/// Checks whether the caller has a specific permission
828fn check_permission(perm: &str) -> binder::Result<()> {
David Brazdil1f530702022-10-03 12:18:10 +0100829 let calling_pid = get_calling_pid();
830 let calling_uid = get_calling_uid();
Jiyong Park753553b2021-07-12 21:21:09 +0900831 // Root can do anything
832 if calling_uid == 0 {
833 return Ok(());
834 }
835 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
836 binder::get_interface("permission")?;
837 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000838 Ok(())
839 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900840 Err(anyhow!("does not have the {} permission", perm))
841 .or_binder_exception(ExceptionCode::SECURITY)
Andrew Walbran806f1542021-06-10 14:07:12 +0000842 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000843}
844
Jiyong Park753553b2021-07-12 21:21:09 +0900845/// Check whether the caller of the current Binder method is allowed to manage VMs
846fn check_manage_access() -> binder::Result<()> {
847 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
848}
849
Inseob Kim1119d702022-05-02 18:01:58 +0900850/// Check whether the caller of the current Binder method is allowed to create custom VMs
851fn check_use_custom_virtual_machine() -> binder::Result<()> {
852 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
853}
854
Alan Stokes185fe112023-01-10 16:20:55 +0000855/// Return whether a partition is exempt from selinux label checks, because we know that it does
856/// not contain code and is likely to be generated in an app-writable directory.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100857fn is_safe_app_partition(label: &str) -> bool {
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000858 // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100859 label == "vm-instance"
Shikha Panwara2ff8c52022-11-30 19:25:46 +0000860 || label == "encryptedstore"
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100861 || label == "microdroid-apk-idsig"
862 || label == "payload-metadata"
863 || label.starts_with("extra-idsig-")
864}
865
Alice Wangc206b9b2023-08-28 14:13:51 +0000866/// Returns whether a partition with the given label is safe for a raw config VM.
867fn is_safe_raw_partition(label: &str) -> bool {
868 label == "vm-instance"
869}
870
Alan Stokes185fe112023-01-10 16:20:55 +0000871/// Check that a file SELinux label is acceptable.
872///
873/// We only want to allow code in a VM to be sourced from places that apps, and the
874/// system, do not have write access to.
875///
876/// Note that sepolicy must also grant read access for these types to both virtualization
877/// service and crosvm.
878///
879/// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
880/// user devices (W^X).
881fn check_label_is_allowed(context: &SeContext) -> Result<()> {
882 match context.selinux_type()? {
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100883 | "apk_data_file" // APKs of an installed app
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100884 | "shell_data_file" // test files created via adb shell
Alan Stokesfe4bb0c2023-03-20 14:15:36 +0000885 | "staging_data_file" // updated/staged APEX images
886 | "system_file" // immutable dm-verity protected partition
887 | "virtualizationservice_data_file" // files created by VS / VirtMgr
Alan Stokes53cc5ca2022-08-30 14:28:19 +0100888 => Ok(()),
Alan Stokes185fe112023-01-10 16:20:55 +0000889 _ => bail!("Label {} is not allowed", context),
Jiyong Park029977d2021-11-24 21:56:49 +0900890 }
891}
892
Alan Stokes185fe112023-01-10 16:20:55 +0000893fn check_label_for_partition(partition: &Partition) -> Result<()> {
894 let file = partition.image.as_ref().unwrap().as_ref();
895 check_label_is_allowed(&getfilecon(file)?)
896 .with_context(|| format!("Partition {} invalid", &partition.label))
897}
898
899fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> {
900 if let Some(f) = kernel {
901 check_label_for_file(f, "kernel")?;
902 }
903 if let Some(f) = initrd {
904 check_label_for_file(f, "initrd")?;
905 }
906 Ok(())
907}
908fn check_label_for_file(file: &File, name: &str) -> Result<()> {
909 check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name))
910}
911
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000912/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
913#[derive(Debug)]
914struct VirtualMachine {
915 instance: Arc<VmInstance>,
916}
917
918impl VirtualMachine {
919 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
David Brazdil4b4c5102022-12-19 22:56:20 +0000920 BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000921 }
922}
923
924impl Interface for VirtualMachine {}
925
926impl IVirtualMachine for VirtualMachine {
927 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900928 // Don't check permission. The owner of the VM might have passed this binder object to
929 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000930 Ok(self.instance.cid as i32)
931 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000932
Andrew Walbran6b650662021-09-07 13:13:23 +0000933 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900934 // Don't check permission. The owner of the VM might have passed this binder object to
935 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000936 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000937 }
938
939 fn registerCallback(
940 &self,
941 callback: &Strong<dyn IVirtualMachineCallback>,
942 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900943 // Don't check permission. The owner of the VM might have passed this binder object to
944 // others.
945 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000946 // TODO: Should this give an error if the VM is already dead?
947 self.instance.callbacks.add(callback.clone());
948 Ok(())
949 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000950
Andrew Walbranf8d94112021-09-07 11:45:36 +0000951 fn start(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900952 self.instance
953 .start()
954 .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
955 .with_log()
956 .or_service_specific_exception(-1)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000957 }
958
Inseob Kima446f802022-07-11 19:46:37 +0900959 fn stop(&self) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900960 self.instance
961 .kill()
962 .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
963 .with_log()
964 .or_service_specific_exception(-1)
Inseob Kima446f802022-07-11 19:46:37 +0900965 }
966
Keir Frasercdd4b112022-11-24 14:02:25 +0000967 fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900968 self.instance
969 .trim_memory(level)
970 .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid))
971 .with_log()
972 .or_service_specific_exception(-1)
Keir Frasercdd4b112022-11-24 14:02:25 +0000973 }
974
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000975 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000976 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900977 return Err(anyhow!("VM is not running")).or_service_specific_exception(-1);
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000978 }
Alan Stokes10c47672022-12-13 17:17:08 +0000979 let port = port as u32;
980 if port < 1024 {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900981 return Err(anyhow!("Can't connect to privileged port {port}"))
982 .or_service_specific_exception(-1);
Alan Stokes10c47672022-12-13 17:17:08 +0000983 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900984 let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
985 .context("Failed to connect")
986 .or_service_specific_exception(-1)?;
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000987 Ok(vsock_stream_to_pfd(stream))
988 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000989}
990
991impl Drop for VirtualMachine {
992 fn drop(&mut self) {
993 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900994 if let Err(e) = self.instance.kill() {
995 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
996 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000997 }
998}
999
1000/// A set of Binders to be called back in response to various events on the VM, such as when it
1001/// dies.
1002#[derive(Debug, Default)]
1003pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1004
1005impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001006 /// Call all registered callbacks to notify that the payload has started.
David Brazdil451cc962022-10-14 14:08:12 +01001007 pub fn notify_payload_started(&self, cid: Cid) {
Jiyong Park8611a6c2021-07-09 18:17:44 +09001008 let callbacks = &*self.0.lock().unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +09001009 for callback in callbacks {
David Brazdil451cc962022-10-14 14:08:12 +01001010 if let Err(e) = callback.onPayloadStarted(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001011 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +09001012 }
1013 }
1014 }
1015
Inseob Kim14cb8692021-08-31 21:50:39 +09001016 /// Call all registered callbacks to notify that the payload is ready to serve.
1017 pub fn notify_payload_ready(&self, cid: Cid) {
1018 let callbacks = &*self.0.lock().unwrap();
1019 for callback in callbacks {
1020 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001021 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +09001022 }
1023 }
1024 }
1025
Inseob Kim2444af92021-08-31 01:22:50 +09001026 /// Call all registered callbacks to notify that the payload has finished.
1027 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1028 let callbacks = &*self.0.lock().unwrap();
1029 for callback in callbacks {
1030 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001031 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +09001032 }
1033 }
1034 }
1035
Jooyung Handd0a1732021-11-23 15:26:20 +09001036 /// Call all registered callbacks to say that the VM encountered an error.
Alan Stokes2bead0d2022-09-05 16:58:34 +01001037 pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
Jooyung Handd0a1732021-11-23 15:26:20 +09001038 let callbacks = &*self.0.lock().unwrap();
1039 for callback in callbacks {
1040 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001041 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +09001042 }
1043 }
1044 }
1045
Andrew Walbrandae07162021-03-12 17:05:20 +00001046 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001047 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +00001048 let callbacks = &*self.0.lock().unwrap();
1049 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +00001050 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +01001051 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +00001052 }
1053 }
1054 }
1055
1056 /// Add a new callback to the set.
1057 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1058 self.0.lock().unwrap().push(callback);
1059 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001060}
1061
Andrew Walbranf6bf6862021-05-21 12:41:13 +00001062/// The mutable state of the VirtualizationService. There should only be one instance of this
1063/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -08001064#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001065struct State {
Alan Stokes3e5eec12023-09-07 12:10:00 +01001066 /// The VMs which have been started. When VMs are started a weak reference is added to this
1067 /// list while a strong reference is returned to the caller over Binder. Once all copies of
1068 /// the Binder client are dropped the weak reference here will become invalid, and will be
1069 /// removed from the list opportunistically the next time `add_vm` is called.
Andrew Walbran320b5602021-03-04 16:11:12 +00001070 vms: Vec<Weak<VmInstance>>,
1071}
1072
1073impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +00001074 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +00001075 fn vms(&self) -> Vec<Arc<VmInstance>> {
1076 // Attempt to upgrade the weak pointers to strong pointers.
1077 self.vms.iter().filter_map(Weak::upgrade).collect()
1078 }
1079
1080 /// Add a new VM to the list.
1081 fn add_vm(&mut self, vm: Weak<VmInstance>) {
1082 // Garbage collect any entries from the stored list which no longer exist.
1083 self.vms.retain(|vm| vm.strong_count() > 0);
1084
1085 // Actually add the new VM.
1086 self.vms.push(vm);
1087 }
David Brazdil3c2ddef2021-03-18 13:09:57 +00001088
Jiyong Park8611a6c2021-07-09 18:17:44 +09001089 /// Get a VM that corresponds to the given cid
1090 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1091 self.vms().into_iter().find(|vm| vm.cid == cid)
1092 }
Jiyong Parkd50a0242021-09-16 21:00:14 +09001093}
1094
Andrew Walbran6b650662021-09-07 13:13:23 +00001095/// Gets the `VirtualMachineState` of the given `VmInstance`.
1096fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +00001097 match &*instance.vm_state.lock().unwrap() {
1098 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
1099 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +00001100 PayloadState::Starting => VirtualMachineState::STARTING,
1101 PayloadState::Started => VirtualMachineState::STARTED,
1102 PayloadState::Ready => VirtualMachineState::READY,
1103 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +09001104 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +00001105 },
1106 VmState::Dead => VirtualMachineState::DEAD,
1107 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +00001108 }
1109}
1110
David Brazdilf50c7a62023-04-19 14:22:42 +00001111/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001112pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
1113 file.as_ref()
1114 .try_clone()
1115 .context("Failed to clone File from ParcelFileDescriptor")
1116 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
David Brazdilf50c7a62023-04-19 14:22:42 +00001117}
1118
Andrew Walbrand3a84182021-09-07 14:48:52 +00001119/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001120fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
Andrew Walbrand3a84182021-09-07 14:48:52 +00001121 file.as_ref().map(clone_file).transpose()
1122}
1123
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001124/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1125fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1126 // SAFETY: ownership is transferred from stream to f
1127 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1128 ParcelFileDescriptor::new(f)
1129}
1130
Jiyong Parkdcf17412022-02-08 15:07:23 +09001131/// Parses the platform version requirement string.
Jiyong Park2227eaa2023-08-04 11:59:18 +09001132fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
1133 VersionReq::parse(s)
1134 .with_context(|| format!("Invalid platform version requirement {}", s))
1135 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
Jiyong Parkdcf17412022-02-08 15:07:23 +09001136}
1137
Jiyong Parked180932023-02-24 19:55:41 +09001138/// Create the empty ramdump file
1139fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
1140 // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
1141 // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
1142 // owner) for readout.
1143 let ramdump_path = temporary_directory.join("ramdump");
Jiyong Park2227eaa2023-08-04 11:59:18 +09001144 let ramdump = File::create(ramdump_path)
1145 .context("Failed to prepare ramdump file")
1146 .with_log()
1147 .or_service_specific_exception(-1)?;
Jiyong Parked180932023-02-24 19:55:41 +09001148 Ok(ramdump)
1149}
1150
Nikita Ioffe5776f082023-02-10 21:38:26 +00001151fn is_protected(config: &VirtualMachineConfig) -> bool {
1152 match config {
1153 VirtualMachineConfig::RawConfig(config) => config.protectedVm,
1154 VirtualMachineConfig::AppConfig(config) => config.protectedVm,
1155 }
1156}
1157
1158fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
1159 if is_protected(config) {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001160 return Err(anyhow!("Can't use gdb with protected VMs"))
1161 .or_binder_exception(ExceptionCode::SECURITY);
Nikita Ioffe5776f082023-02-10 21:38:26 +00001162 }
1163
1164 match config {
1165 VirtualMachineConfig::RawConfig(_) => Ok(()),
1166 VirtualMachineConfig::AppConfig(config) => {
1167 if config.debugLevel != DebugLevel::FULL {
Jiyong Park2227eaa2023-08-04 11:59:18 +09001168 Err(anyhow!("Can't use gdb with non-debuggable VMs"))
1169 .or_binder_exception(ExceptionCode::SECURITY)
Nikita Ioffe5776f082023-02-10 21:38:26 +00001170 } else {
1171 Ok(())
1172 }
1173 }
1174 }
1175}
1176
1177fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
1178 match config {
1179 VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
Nikita Ioffea0eb5ee2023-06-26 18:18:21 +01001180 VirtualMachineConfig::AppConfig(config) => {
1181 NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
1182 }
Nikita Ioffe5776f082023-02-10 21:38:26 +00001183 }
1184}
1185
Nikita Ioffe631717e2023-09-05 13:38:07 +01001186fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
1187 let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
1188 if let Some(custom_config) = &config.customConfig {
1189 if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
1190 return Err(anyhow!("vendor modules feature is disabled"))
1191 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
1192 }
1193 }
1194 Ok(())
1195}
1196
1197fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
1198 if !cfg!(vendor_modules) {
1199 check_no_vendor_modules(config)?;
1200 }
1201 Ok(())
1202}
1203
Inseob Kim0168b462022-12-27 14:54:35 +09001204fn clone_or_prepare_logger_fd(
Jaewan Kim61f86142023-03-28 15:12:52 +09001205 debug_config: &DebugConfig,
Inseob Kim0168b462022-12-27 14:54:35 +09001206 fd: Option<&ParcelFileDescriptor>,
1207 tag: String,
1208) -> Result<Option<File>, Status> {
1209 if let Some(fd) = fd {
1210 return Ok(Some(clone_file(fd)?));
1211 }
1212
Jaewan Kim61f86142023-03-28 15:12:52 +09001213 if !debug_config.should_prepare_console_output() {
Jaewan Kim66f062e2023-02-25 01:07:43 +09001214 return Ok(None);
1215 };
Inseob Kim0168b462022-12-27 14:54:35 +09001216
Jiyong Park2227eaa2023-08-04 11:59:18 +09001217 let (raw_read_fd, raw_write_fd) =
1218 pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
Inseob Kim0168b462022-12-27 14:54:35 +09001219
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001220 // 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 +09001221 let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) });
Andrew Walbranb58d1b42023-07-07 13:54:49 +01001222 // 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 +09001223 let write_fd = unsafe { File::from_raw_fd(raw_write_fd) };
1224
1225 std::thread::spawn(move || loop {
1226 let mut buf = vec![];
1227 match reader.read_until(b'\n', &mut buf) {
1228 Ok(0) => {
1229 // EOF
1230 return;
1231 }
1232 Ok(size) => {
1233 if buf[size - 1] == b'\n' {
1234 buf.pop();
1235 }
1236 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
1237 }
1238 Err(e) => {
1239 error!("Could not read console pipe: {:?}", e);
1240 return;
1241 }
1242 };
1243 });
1244
1245 Ok(Some(write_fd))
1246}
1247
Jooyung Han35edb8f2021-07-01 16:17:16 +09001248/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1249/// it doesn't require that T implements Clone.
1250enum BorrowedOrOwned<'a, T> {
1251 Borrowed(&'a T),
1252 Owned(T),
1253}
1254
1255impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1256 fn as_ref(&self) -> &T {
1257 match self {
1258 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001259 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001260 }
1261 }
1262}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001263
1264/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1265#[derive(Debug, Default)]
1266struct VirtualMachineService {
1267 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001268 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001269}
1270
1271impl Interface for VirtualMachineService {}
1272
1273impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001274 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1275 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001276 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001277 info!("VM with CID {} started payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001278 vm.update_payload_state(PayloadState::Started)
1279 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
David Brazdil451cc962022-10-14 14:08:12 +01001280 vm.callbacks.notify_payload_started(cid);
Seungjae Yoo62085c02022-08-12 04:44:52 +00001281
Seungjae Yoo6d265d92022-11-15 10:51:33 +09001282 let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
1283 write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001284 Ok(())
1285 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001286 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001287 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001288 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001289 }
Inseob Kim2444af92021-08-31 01:22:50 +09001290
Inseob Kimc7d28c72021-10-25 14:28:10 +00001291 fn notifyPayloadReady(&self) -> binder::Result<()> {
1292 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001293 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001294 info!("VM with CID {} reported payload is ready", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001295 vm.update_payload_state(PayloadState::Ready)
1296 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001297 vm.callbacks.notify_payload_ready(cid);
1298 Ok(())
1299 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001300 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001301 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim14cb8692021-08-31 21:50:39 +09001302 }
1303 }
1304
Inseob Kimc7d28c72021-10-25 14:28:10 +00001305 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1306 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001307 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001308 info!("VM with CID {} finished payload", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001309 vm.update_payload_state(PayloadState::Finished)
1310 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Inseob Kim2444af92021-08-31 01:22:50 +09001311 vm.callbacks.notify_payload_finished(cid, exit_code);
1312 Ok(())
1313 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001314 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001315 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Jooyung Handd0a1732021-11-23 15:26:20 +09001316 }
1317 }
1318
Alan Stokes2bead0d2022-09-05 16:58:34 +01001319 fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
Jooyung Handd0a1732021-11-23 15:26:20 +09001320 let cid = self.cid;
1321 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
David Brazdil415097c2022-10-21 14:17:05 +01001322 info!("VM with CID {} encountered an error", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001323 vm.update_payload_state(PayloadState::Finished)
1324 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
Jooyung Handd0a1732021-11-23 15:26:20 +09001325 vm.callbacks.notify_error(cid, error_code, message);
1326 Ok(())
1327 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001328 error!("notifyError is called from an unknown CID {}", cid);
Jiyong Park2227eaa2023-08-04 11:59:18 +09001329 Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
Inseob Kim2444af92021-08-31 01:22:50 +09001330 }
1331 }
Alice Wangc2fec932023-02-23 16:24:02 +00001332
Alice Wang4e3015d2023-10-10 09:35:37 +00001333 fn requestAttestation(&self, csr: &[u8]) -> binder::Result<Vec<Certificate>> {
Alice Wanga410b642023-10-18 09:05:15 +00001334 GLOBAL_SERVICE.requestAttestation(csr)
Alice Wangc2fec932023-02-23 16:24:02 +00001335 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001336}
1337
1338impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001339 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001340 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001341 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001342 BinderFeatures::default(),
1343 )
1344 }
1345}
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001346
1347#[cfg(test)]
1348mod tests {
1349 use super::*;
1350
1351 #[test]
1352 fn test_is_allowed_label_for_partition() -> Result<()> {
1353 let expected_results = vec![
1354 ("u:object_r:system_file:s0", true),
1355 ("u:object_r:apk_data_file:s0", true),
1356 ("u:object_r:app_data_file:s0", false),
1357 ("u:object_r:app_data_file:s0:c512,c768", false),
1358 ("u:object_r:privapp_data_file:s0:c512,c768", false),
1359 ("invalid", false),
1360 ("user:role:apk_data_file:severity:categories", true),
1361 ("user:role:apk_data_file:severity:categories:extraneous", false),
1362 ];
1363
1364 for (label, expected_valid) in expected_results {
1365 let context = SeContext::new(label)?;
1366 let result = check_label_is_allowed(&context);
1367 if expected_valid {
1368 assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result);
1369 } else if result.is_ok() {
1370 bail!("Expected label {} to be disallowed", label);
1371 }
1372 }
1373 Ok(())
1374 }
Nikita Ioffef1ce9872022-12-09 13:31:59 +00001375
1376 #[test]
1377 fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
1378 let apk = tempfile::tempfile().unwrap();
1379 let idsig = tempfile::tempfile().unwrap();
1380
1381 let ret = create_or_update_idsig_file(
1382 &ParcelFileDescriptor::new(apk),
1383 &ParcelFileDescriptor::new(idsig),
1384 );
1385 assert!(ret.is_err(), "should fail");
1386 Ok(())
1387 }
1388
1389 #[test]
1390 fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
1391 let tmp_dir = tempfile::TempDir::new().unwrap();
1392 let apk = File::open(tmp_dir.path()).unwrap();
1393 let idsig = tempfile::tempfile().unwrap();
1394
1395 let ret = create_or_update_idsig_file(
1396 &ParcelFileDescriptor::new(apk),
1397 &ParcelFileDescriptor::new(idsig),
1398 );
1399 assert!(ret.is_err(), "should fail");
1400 Ok(())
1401 }
1402
1403 /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
1404 /// on ext4 filesystem is passed.
1405 /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
1406 /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
1407 /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
1408 #[test]
1409 fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
1410 // APEXes are backed by the ext4.
1411 let apk = File::open("/apex/com.android.virt/").unwrap();
1412 let idsig = tempfile::tempfile().unwrap();
1413
1414 let ret = create_or_update_idsig_file(
1415 &ParcelFileDescriptor::new(apk),
1416 &ParcelFileDescriptor::new(idsig),
1417 );
1418 assert!(ret.is_err(), "should fail");
1419 Ok(())
1420 }
Jiyong Park8d192952023-06-26 14:29:51 +09001421
1422 #[test]
1423 fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
1424 use std::io::Seek;
1425
1426 // Pick any APK
1427 let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
1428 let mut idsig = tempfile::tempfile().unwrap();
1429
1430 create_or_update_idsig_file(
1431 &ParcelFileDescriptor::new(apk.try_clone()?),
1432 &ParcelFileDescriptor::new(idsig.try_clone()?),
1433 )?;
1434 let modified_orig = idsig.metadata()?.modified()?;
1435 apk.rewind()?;
1436 idsig.rewind()?;
1437
1438 // Call the function again
1439 create_or_update_idsig_file(
1440 &ParcelFileDescriptor::new(apk.try_clone()?),
1441 &ParcelFileDescriptor::new(idsig.try_clone()?),
1442 )?;
1443 let modified_new = idsig.metadata()?.modified()?;
1444 assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
1445 Ok(())
1446 }
Nikita Ioffeaa6858c2023-07-04 01:37:41 +01001447
1448 #[test]
1449 fn test_append_kernel_param_first_param() {
1450 let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
1451 append_kernel_param("foo=1", &mut vm_config);
1452 assert_eq!(vm_config.params, Some("foo=1".to_owned()))
1453 }
1454
1455 #[test]
1456 fn test_append_kernel_param() {
1457 let mut vm_config =
1458 VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
1459 append_kernel_param("bar=42", &mut vm_config);
1460 assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
1461 }
Seungjae Yooec3bc522023-11-09 10:14:30 +09001462
1463 #[test]
1464 fn test_create_dtbo_for_vendor_image() -> Result<()> {
1465 let vendor_public_key = String::from("foo");
1466 let vendor_public_key = vendor_public_key.as_bytes();
1467
1468 let tmp_dir = tempfile::TempDir::new()?;
1469 let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
1470
1471 create_dtbo_for_vendor_image(vendor_public_key, &dtbo_path)?;
1472
1473 let data = std::fs::read(dtbo_path)?;
1474 let fdt = Fdt::from_slice(&data).unwrap();
1475
1476 let fragment_node_path = CString::new("/fragment@0")?;
1477 let fragment_node = fdt.node(fragment_node_path.as_c_str()).unwrap();
1478 let Some(fragment_node) = fragment_node else {
1479 bail!("fragment_node shouldn't be None.");
1480 };
1481 let target_path_prop_name = CString::new("target-path")?;
1482 let target_path_from_dtbo =
1483 fragment_node.getprop(target_path_prop_name.as_c_str()).unwrap();
1484 let target_path_expected = CString::new("/")?;
1485 assert_eq!(target_path_from_dtbo, Some(target_path_expected.to_bytes_with_nul()));
1486
1487 let avf_node_path = CString::new("/fragment@0/__overlay__/avf")?;
1488 let avf_node = fdt.node(avf_node_path.as_c_str()).unwrap();
1489 let Some(avf_node) = avf_node else {
1490 bail!("avf_node shouldn't be None.");
1491 };
1492 let vendor_public_key_name = CString::new("vendor_public_key")?;
1493 let key_from_dtbo = avf_node.getprop(vendor_public_key_name.as_c_str()).unwrap();
1494 assert_eq!(key_from_dtbo, Some(vendor_public_key));
1495
1496 tmp_dir.close()?;
1497 Ok(())
1498 }
1499
1500 #[test]
1501 fn test_create_dtbo_for_vendor_image_throws_error_if_already_exists() -> Result<()> {
1502 let vendor_public_key = String::from("foo");
1503 let vendor_public_key = vendor_public_key.as_bytes();
1504
1505 let tmp_dir = tempfile::TempDir::new()?;
1506 let dtbo_path = tmp_dir.path().to_path_buf().join("bar");
1507
1508 create_dtbo_for_vendor_image(vendor_public_key, &dtbo_path)?;
1509
1510 let ret_second_trial = create_dtbo_for_vendor_image(vendor_public_key, &dtbo_path);
1511 assert!(ret_second_trial.is_err(), "should fail");
1512
1513 tmp_dir.close()?;
1514 Ok(())
1515 }
Alan Stokes53cc5ca2022-08-30 14:28:19 +01001516}