• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // 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 
15 //! Implementation of the AIDL interface of the VirtualizationService.
16 
17 use crate::{get_calling_pid, get_calling_uid, get_this_pid};
18 use crate::atom::{write_vm_booted_stats, write_vm_creation_stats};
19 use crate::composite::make_composite_image;
20 use crate::crosvm::{AudioConfig, CrosvmConfig, DiskFile, SharedPathConfig, DisplayConfig, GpuConfig, InputDeviceOption, PayloadState, UsbConfig, VmContext, VmInstance, VmState};
21 use crate::debug_config::{DebugConfig, DebugPolicy};
22 use crate::dt_overlay::{create_device_tree_overlay, VM_DT_OVERLAY_MAX_SIZE, VM_DT_OVERLAY_PATH};
23 use crate::payload::{ApexInfoList, add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image};
24 use crate::selinux::{check_tee_service_permission, getfilecon, getprevcon, SeContext};
25 use android_os_permissions_aidl::aidl::android::os::IPermissionController;
26 use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
27     Certificate::Certificate,
28     DeathReason::DeathReason,
29     ErrorCode::ErrorCode,
30 };
31 use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
32     AssignedDevices::AssignedDevices,
33     AssignableDevice::AssignableDevice,
34     DiskImage::DiskImage,
35     SharedPath::SharedPath,
36     InputDevice::InputDevice,
37     IVirtualMachine::{self, BnVirtualMachine},
38     IVirtualMachineCallback::IVirtualMachineCallback,
39     IVirtualizationService::IVirtualizationService,
40     Partition::Partition,
41     PartitionType::PartitionType,
42     VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig},
43     VirtualMachineConfig::VirtualMachineConfig,
44     VirtualMachineDebugInfo::VirtualMachineDebugInfo,
45     VirtualMachinePayloadConfig::VirtualMachinePayloadConfig,
46     VirtualMachineRawConfig::VirtualMachineRawConfig,
47     VirtualMachineState::VirtualMachineState,
48 };
49 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
50 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal;
51 use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
52         BnVirtualMachineService, IVirtualMachineService,
53 };
54 use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{BnSecretkeeper, ISecretkeeper};
55 use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::SecretId::SecretId;
56 use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::PublicKey::PublicKey;
57 use 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 };
63 use anyhow::{anyhow, bail, ensure, Context, Result};
64 use apkverify::{HashAlgorithm, V4Signature};
65 use avflog::LogResult;
66 use binder::{
67     self, wait_for_interface, Accessor, BinderFeatures, ConnectionInfo, ExceptionCode, Interface, ParcelFileDescriptor,
68     SpIBinder, Status, StatusCode, Strong, IntoBinderResult,
69 };
70 use glob::glob;
71 use libc::{AF_VSOCK, sa_family_t, sockaddr_vm};
72 use log::{debug, error, info, warn};
73 use microdroid_payload_config::{ApexConfig, ApkConfig, Task, TaskType, VmPayloadConfig};
74 use nix::unistd::pipe;
75 use rpcbinder::RpcServer;
76 use rustutils::system_properties;
77 use semver::VersionReq;
78 use serde::Deserialize;
79 use std::collections::{HashSet, HashMap};
80 use std::convert::TryInto;
81 use std::fs;
82 use std::ffi::CStr;
83 use std::fs::{canonicalize, create_dir_all, read_dir, remove_dir_all, remove_file, File, OpenOptions};
84 use std::io::{BufRead, BufReader, Error, ErrorKind, Seek, SeekFrom, Write};
85 use std::iter;
86 use std::num::{NonZeroU16, NonZeroU32};
87 use std::ops::Range;
88 use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
89 use std::os::unix::raw::pid_t;
90 use std::path::{Path, PathBuf};
91 use std::sync::{Arc, Mutex, Weak, LazyLock};
92 use vbmeta::VbMetaImage;
93 use vmconfig::{VmConfig, get_debug_level};
94 use vsock::VsockStream;
95 use zip::ZipArchive;
96 
97 /// The unique ID of a VM used (together with a port number) for vsock communication.
98 pub type Cid = u32;
99 
100 pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
101 
102 /// Vsock privileged ports are below this number.
103 const VSOCK_PRIV_PORT_MAX: u32 = 1024;
104 
105 /// The size of zero.img.
106 /// Gaps in composite disk images are filled with a shared zero.img.
107 const ZERO_FILLER_SIZE: u64 = 4096;
108 
109 /// Magic string for the instance image
110 const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
111 
112 /// Version of the instance image format
113 const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
114 
115 const MICRODROID_OS_NAME: &str = "microdroid";
116 
117 const SECRETKEEPER_IDENTIFIER: &str =
118     "android.hardware.security.secretkeeper.ISecretkeeper/default";
119 
120 const VM_CAPABILITIES_HAL_IDENTIFIER: &str =
121     "android.hardware.virtualization.capabilities.IVmCapabilitiesService/default";
122 
123 const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
124 
125 /// crosvm requires all partitions to be a multiple of 4KiB.
126 const PARTITION_GRANULARITY_BYTES: u64 = 4096;
127 
128 const VM_REFERENCE_DT_ON_HOST_PATH: &str = "/proc/device-tree/avf/reference";
129 
130 pub static GLOBAL_SERVICE: LazyLock<Strong<dyn IVirtualizationServiceInternal>> =
131     LazyLock::new(|| {
132         if cfg!(early) {
133             panic!("Early virtmgr must not connect to VirtualizatinoServiceInternal")
134         } else {
135             wait_for_interface(BINDER_SERVICE_IDENTIFIER)
136                 .expect("Could not connect to VirtualizationServiceInternal")
137         }
138     });
139 static SUPPORTED_OS_NAMES: LazyLock<HashSet<String>> =
140     LazyLock::new(|| get_supported_os_names().expect("Failed to get list of supported os names"));
141 
142 static CALLING_EXE_PATH: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
143     let calling_exe_link = format!("/proc/{}/exe", get_calling_pid());
144     match fs::read_link(&calling_exe_link) {
145         Ok(calling_exe_path) => Some(calling_exe_path),
146         Err(e) => {
147             // virtmgr forked from apps fails to read /proc probably due to hidepid=2. As we
148             // discourage vendor apps, regarding such cases as system is safer.
149             // TODO(b/383969737): determine if this is okay. Or find a way how to track origins of
150             // apps.
151             warn!("can't read_link '{calling_exe_link}': {e:?}; regarding as system");
152             None
153         }
154     }
155 });
156 
157 // TODO(ioffe): add service for guest-ffa.
158 const KNOWN_TEE_SERVICES: [&str; 0] = [];
159 
check_known_tee_service(tee_service: &str) -> binder::Result<()>160 fn check_known_tee_service(tee_service: &str) -> binder::Result<()> {
161     if !KNOWN_TEE_SERVICES.contains(&tee_service) {
162         return Err(anyhow!("unknown tee_service {tee_service}"))
163             .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
164     }
165     Ok(())
166 }
167 
create_or_update_idsig_file( input_fd: &ParcelFileDescriptor, idsig_fd: &ParcelFileDescriptor, ) -> Result<()>168 fn create_or_update_idsig_file(
169     input_fd: &ParcelFileDescriptor,
170     idsig_fd: &ParcelFileDescriptor,
171 ) -> Result<()> {
172     let mut input = clone_file(input_fd)?;
173     let metadata = input.metadata().context("failed to get input metadata")?;
174     if !metadata.is_file() {
175         bail!("input is not a regular file");
176     }
177     let mut sig =
178         V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256)
179             .context("failed to create idsig")?;
180 
181     let mut output = clone_file(idsig_fd)?;
182 
183     // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it,
184     // if the idsig file already has the same APK digest.
185     if output.metadata()?.len() > 0 {
186         if let Ok(out_sig) = V4Signature::from_idsig(&mut output) {
187             if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest {
188                 debug!("idsig {:?} is up-to-date with apk {:?}.", output, input);
189                 return Ok(());
190             }
191         }
192         // if we fail to read v4signature from output, that's fine. User can pass a random file.
193         // We will anyway overwrite the file to the v4signature generated from input_fd.
194     }
195 
196     output
197         .seek(SeekFrom::Start(0))
198         .context("failed to move cursor to start on the idsig output")?;
199     output.set_len(0).context("failed to set_len on the idsig output")?;
200     sig.write_into(&mut output).context("failed to write idsig")?;
201     Ok(())
202 }
203 
get_current_sdk() -> Result<u32>204 fn get_current_sdk() -> Result<u32> {
205     let current_sdk = system_properties::read("ro.build.version.sdk")?;
206     let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?;
207     current_sdk.parse().context("Malformed SDK version")
208 }
209 
remove_temporary_files(path: &PathBuf) -> Result<()>210 pub fn remove_temporary_files(path: &PathBuf) -> Result<()> {
211     for dir_entry in read_dir(path)? {
212         remove_file(dir_entry?.path())?;
213     }
214     Ok(())
215 }
216 
217 /// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
218 #[derive(Debug, Default)]
219 pub struct VirtualizationService {
220     state: Arc<Mutex<State>>,
221 }
222 
223 impl Interface for VirtualizationService {
dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode>224     fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> {
225         check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
226         let state = &mut *self.state.lock().unwrap();
227         let vms = state.vms();
228         writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
229         for vm in vms {
230             writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
231             writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap())
232                 .or(Err(StatusCode::UNKNOWN_ERROR))?;
233             writeln!(writer, "\tPayload state {:?}", vm.payload_state())
234                 .or(Err(StatusCode::UNKNOWN_ERROR))?;
235             writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
236             writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
237                 .or(Err(StatusCode::UNKNOWN_ERROR))?;
238             writeln!(writer, "\trequester_uid: {}", vm.requester_uid)
239                 .or(Err(StatusCode::UNKNOWN_ERROR))?;
240             writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid)
241                 .or(Err(StatusCode::UNKNOWN_ERROR))?;
242         }
243         Ok(())
244     }
245 }
246 impl IVirtualizationService for VirtualizationService {
247     /// Creates (but does not start) a new VM with the given configuration, assigning it the next
248     /// available CID.
249     ///
250     /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
createVm( &self, config: &VirtualMachineConfig, console_out_fd: Option<&ParcelFileDescriptor>, console_in_fd: Option<&ParcelFileDescriptor>, log_fd: Option<&ParcelFileDescriptor>, dump_dt_fd: Option<&ParcelFileDescriptor>, ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>>251     fn createVm(
252         &self,
253         config: &VirtualMachineConfig,
254         console_out_fd: Option<&ParcelFileDescriptor>,
255         console_in_fd: Option<&ParcelFileDescriptor>,
256         log_fd: Option<&ParcelFileDescriptor>,
257         dump_dt_fd: Option<&ParcelFileDescriptor>,
258     ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
259         let mut is_protected = false;
260         let ret = self.create_vm_internal(
261             config,
262             console_out_fd,
263             console_in_fd,
264             log_fd,
265             &mut is_protected,
266             dump_dt_fd,
267         );
268         write_vm_creation_stats(config, is_protected, &ret);
269         ret
270     }
271 
272     /// Allocate a new instance_id to the VM
allocateInstanceId(&self) -> binder::Result<[u8; 64]>273     fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> {
274         check_manage_access()?;
275         GLOBAL_SERVICE.allocateInstanceId()
276     }
277 
278     /// Initialise an empty partition image of the given size to be used as a writable partition.
initializeWritablePartition( &self, image_fd: &ParcelFileDescriptor, size_bytes: i64, partition_type: PartitionType, ) -> binder::Result<()>279     fn initializeWritablePartition(
280         &self,
281         image_fd: &ParcelFileDescriptor,
282         size_bytes: i64,
283         partition_type: PartitionType,
284     ) -> binder::Result<()> {
285         check_manage_access()?;
286         let size_bytes = size_bytes
287             .try_into()
288             .with_context(|| format!("Invalid size: {}", size_bytes))
289             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
290         let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES);
291         let mut image = clone_file(image_fd)?;
292         // initialize the file. Any data in the file will be erased.
293         image
294             .seek(SeekFrom::Start(0))
295             .context("failed to move cursor to start")
296             .or_service_specific_exception(-1)?;
297         image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?;
298         // Set the file length. In most filesystems, this will not allocate any physical disk
299         // space, it will only change the logical size.
300         image
301             .set_len(size_bytes)
302             .context("Failed to extend file")
303             .or_service_specific_exception(-1)?;
304 
305         match partition_type {
306             PartitionType::RAW => Ok(()),
307             PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut image),
308             PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut image),
309             _ => Err(Error::new(
310                 ErrorKind::Unsupported,
311                 format!("Unsupported partition type {:?}", partition_type),
312             )),
313         }
314         .with_context(|| format!("Failed to initialize partition as {:?}", partition_type))
315         .or_service_specific_exception(-1)?;
316 
317         Ok(())
318     }
319 
setEncryptedStorageSize( &self, image_fd: &ParcelFileDescriptor, size: i64, ) -> binder::Result<()>320     fn setEncryptedStorageSize(
321         &self,
322         image_fd: &ParcelFileDescriptor,
323         size: i64,
324     ) -> binder::Result<()> {
325         check_manage_access()?;
326 
327         let size = size
328             .try_into()
329             .with_context(|| format!("Invalid size: {}", size))
330             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
331         let size = round_up(size, PARTITION_GRANULARITY_BYTES);
332 
333         let image = clone_file(image_fd)?;
334         let image_size = image.metadata().unwrap().len();
335 
336         if image_size > size {
337             return Err(Status::new_exception_str(
338                 ExceptionCode::ILLEGAL_ARGUMENT,
339                 Some("Can't shrink encrypted storage"),
340             ));
341         }
342         // Reset the file length. In most filesystems, this will not allocate any physical disk
343         // space, it will only change the logical size.
344         image.set_len(size).context("Failed to extend file").or_service_specific_exception(-1)?;
345         Ok(())
346     }
347 
348     /// Creates or update the idsig file by digesting the input APK file.
createOrUpdateIdsigFile( &self, input_fd: &ParcelFileDescriptor, idsig_fd: &ParcelFileDescriptor, ) -> binder::Result<()>349     fn createOrUpdateIdsigFile(
350         &self,
351         input_fd: &ParcelFileDescriptor,
352         idsig_fd: &ParcelFileDescriptor,
353     ) -> binder::Result<()> {
354         check_manage_access()?;
355 
356         create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?;
357         Ok(())
358     }
359 
360     /// Get a list of all currently running VMs. This method is only intended for debug purposes,
361     /// and as such is only permitted from the shell user.
debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>>362     fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
363         // Delegate to the global service, including checking the debug permission.
364         GLOBAL_SERVICE.debugListVms()
365     }
366 
367     /// Get a list of assignable device types.
getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>>368     fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
369         // Delegate to the global service, including checking the permission.
370         GLOBAL_SERVICE.getAssignableDevices()
371     }
372 
373     /// Get a list of supported OSes.
getSupportedOSList(&self) -> binder::Result<Vec<String>>374     fn getSupportedOSList(&self) -> binder::Result<Vec<String>> {
375         Ok(Vec::from_iter(SUPPORTED_OS_NAMES.iter().cloned()))
376     }
377 
378     /// Get printable debug policy for testing and debugging
getDebugPolicy(&self) -> binder::Result<String>379     fn getDebugPolicy(&self) -> binder::Result<String> {
380         let debug_policy = DebugPolicy::from_host();
381         Ok(format!("{debug_policy:?}"))
382     }
383 
384     /// Returns whether given feature is enabled
isFeatureEnabled(&self, feature: &str) -> binder::Result<bool>385     fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> {
386         check_manage_access()?;
387         Ok(avf_features::is_feature_enabled(feature))
388     }
389 
enableTestAttestation(&self) -> binder::Result<()>390     fn enableTestAttestation(&self) -> binder::Result<()> {
391         GLOBAL_SERVICE.enableTestAttestation()
392     }
393 
isRemoteAttestationSupported(&self) -> binder::Result<bool>394     fn isRemoteAttestationSupported(&self) -> binder::Result<bool> {
395         check_manage_access()?;
396         GLOBAL_SERVICE.isRemoteAttestationSupported()
397     }
398 
isUpdatableVmSupported(&self) -> binder::Result<bool>399     fn isUpdatableVmSupported(&self) -> binder::Result<bool> {
400         // The response is specific to Microdroid. Updatable VMs are only possible if device
401         // supports Secretkeeper. Guest OS needs to use Secretkeeper based secrets. Microdroid does
402         // this, however other guest OSes may do things differently.
403         check_manage_access()?;
404         Ok(is_secretkeeper_supported())
405     }
406 
removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()>407     fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
408         check_manage_access()?;
409         GLOBAL_SERVICE.removeVmInstance(instance_id)
410     }
411 
claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()>412     fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> {
413         check_manage_access()?;
414         GLOBAL_SERVICE.claimVmInstance(instance_id)
415     }
416 }
417 
418 /// Implementation of the AIDL `IGlobalVmContext` interface for early VMs.
419 #[derive(Debug, Default)]
420 struct EarlyVmContext {
421     /// The unique CID assigned to the VM for vsock communication.
422     cid: Cid,
423     /// Temporary directory for this VM instance.
424     temp_dir: PathBuf,
425 }
426 
427 impl EarlyVmContext {
new(cid: Cid, temp_dir: PathBuf) -> Result<Self>428     fn new(cid: Cid, temp_dir: PathBuf) -> Result<Self> {
429         // Remove the entire directory before creating a VM. Early VMs use predefined CIDs and AVF
430         // should trust clients, e.g. they won't run two VMs at the same time
431         let _ = remove_dir_all(&temp_dir);
432         create_dir_all(&temp_dir).context(format!("can't create '{}'", temp_dir.display()))?;
433 
434         Ok(Self { cid, temp_dir })
435     }
436 }
437 
438 impl Interface for EarlyVmContext {}
439 
440 impl Drop for EarlyVmContext {
drop(&mut self)441     fn drop(&mut self) {
442         if let Err(e) = remove_dir_all(&self.temp_dir) {
443             error!("Cannot remove {} upon dropping: {e}", self.temp_dir.display());
444         }
445     }
446 }
447 
448 impl IGlobalVmContext for EarlyVmContext {
getCid(&self) -> binder::Result<i32>449     fn getCid(&self) -> binder::Result<i32> {
450         Ok(self.cid as i32)
451     }
452 
getTemporaryDirectory(&self) -> binder::Result<String>453     fn getTemporaryDirectory(&self) -> binder::Result<String> {
454         Ok(self.temp_dir.to_string_lossy().to_string())
455     }
456 
setHostConsoleName(&self, _pathname: &str) -> binder::Result<()>457     fn setHostConsoleName(&self, _pathname: &str) -> binder::Result<()> {
458         Err(Status::new_exception_str(
459             ExceptionCode::UNSUPPORTED_OPERATION,
460             Some("Early VM doesn't support setting host console name"),
461         ))
462     }
463 }
464 
465 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
466 enum CallingPartition {
467     Odm,
468     Product,
469     System,
470     SystemExt,
471     Vendor,
472     Unknown,
473 }
474 
475 impl CallingPartition {
as_str(&self) -> &'static str476     fn as_str(&self) -> &'static str {
477         match self {
478             CallingPartition::Odm => "odm",
479             CallingPartition::Product => "product",
480             CallingPartition::System => "system",
481             CallingPartition::SystemExt => "system_ext",
482             CallingPartition::Vendor => "vendor",
483             CallingPartition::Unknown => "[unknown]",
484         }
485     }
486 }
487 
488 impl std::fmt::Display for CallingPartition {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result489     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
490         write!(f, "{}", self.as_str())
491     }
492 }
493 
find_partition(path: Option<&Path>) -> binder::Result<CallingPartition>494 fn find_partition(path: Option<&Path>) -> binder::Result<CallingPartition> {
495     let Some(path) = path else {
496         return Ok(CallingPartition::System);
497     };
498     if path.starts_with("/system/system_ext/") {
499         return Ok(CallingPartition::SystemExt);
500     }
501     if path.starts_with("/system/product/") {
502         return Ok(CallingPartition::Product);
503     }
504     if path.starts_with("/data/nativetest/vendor/")
505         || path.starts_with("/data/nativetest64/vendor/")
506     {
507         return Ok(CallingPartition::Vendor);
508     }
509 
510     let partition = {
511         let mut components = path.components();
512         let Some(std::path::Component::Normal(partition)) = components.nth(1) else {
513             return Err(anyhow!("Can't find partition in '{}'", path.display()))
514                 .or_service_specific_exception(-1);
515         };
516 
517         // If path is under /apex, find a partition of the preinstalled .apex path
518         if partition == "apex" {
519             let Some(std::path::Component::Normal(apex_name)) = components.next() else {
520                 return Err(anyhow!("Can't find apex name for '{}'", path.display()))
521                     .or_service_specific_exception(-1);
522             };
523             let apex_info_list = ApexInfoList::load()
524                 .context("Failed to get apex info list")
525                 .or_service_specific_exception(-1)?;
526             apex_info_list
527                 .list
528                 .iter()
529                 .find(|apex_info| apex_info.name.as_str() == apex_name)
530                 .map(|apex_info| apex_info.partition.to_lowercase())
531                 .ok_or(anyhow!("Can't find apex info for {apex_name:?}"))
532                 .or_service_specific_exception(-1)?
533         } else {
534             partition.to_string_lossy().into_owned()
535         }
536     };
537     Ok(match partition.as_str() {
538         "odm" => CallingPartition::Odm,
539         "product" => CallingPartition::Product,
540         "system" => CallingPartition::System,
541         "system_ext" => CallingPartition::SystemExt,
542         "vendor" => CallingPartition::Vendor,
543         _ => {
544             warn!("unknown partition for '{}'", path.display());
545             CallingPartition::Unknown
546         }
547     })
548 }
549 
550 impl VirtualizationService {
init() -> VirtualizationService551     pub fn init() -> VirtualizationService {
552         VirtualizationService::default()
553     }
554 
create_early_vm_context( &self, config: &VirtualMachineConfig, calling_exe_path: Option<&Path>, calling_partition: CallingPartition, ) -> binder::Result<(VmContext, Cid, PathBuf)>555     fn create_early_vm_context(
556         &self,
557         config: &VirtualMachineConfig,
558         calling_exe_path: Option<&Path>,
559         calling_partition: CallingPartition,
560     ) -> binder::Result<(VmContext, Cid, PathBuf)> {
561         let name = match config {
562             VirtualMachineConfig::RawConfig(config) => &config.name,
563             VirtualMachineConfig::AppConfig(config) => &config.name,
564         };
565         let early_vm = find_early_vm_for_partition(calling_partition, name)
566             .or_service_specific_exception(-1)?;
567         let calling_exe_path = match calling_exe_path {
568             Some(path) => path,
569             None => {
570                 return Err(anyhow!("Can't verify the path of PID {}", get_calling_pid()))
571                     .or_service_specific_exception(-1)
572             }
573         };
574         early_vm.check_exe_paths_match(calling_exe_path)?;
575 
576         let cid = early_vm.cid as Cid;
577         let temp_dir = PathBuf::from(format!("/mnt/vm/early/{cid}"));
578 
579         let context = EarlyVmContext::new(cid, temp_dir.clone())
580             .context(format!("Can't create early vm contexts for {cid}"))
581             .or_service_specific_exception(-1)?;
582 
583         if requires_vm_service(config) {
584             // Start VM service listening for connections from the new CID on port=CID.
585             let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
586             let port = cid;
587             let (vm_server, _) = RpcServer::new_vsock(service, cid, port)
588                 .context(format!("Could not start RpcServer on port {port}"))
589                 .or_service_specific_exception(-1)?;
590             vm_server.start();
591             Ok((VmContext::new(Strong::new(Box::new(context)), Some(vm_server)), cid, temp_dir))
592         } else {
593             Ok((VmContext::new(Strong::new(Box::new(context)), None), cid, temp_dir))
594         }
595     }
596 
create_vm_context( &self, requester_debug_pid: pid_t, config: &VirtualMachineConfig, ) -> binder::Result<(VmContext, Cid, PathBuf)>597     fn create_vm_context(
598         &self,
599         requester_debug_pid: pid_t,
600         config: &VirtualMachineConfig,
601     ) -> binder::Result<(VmContext, Cid, PathBuf)> {
602         const NUM_ATTEMPTS: usize = 5;
603         let name = get_name(config);
604 
605         for _ in 0..NUM_ATTEMPTS {
606             let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(name, requester_debug_pid)?;
607             let cid = vm_context.getCid()? as Cid;
608             let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into();
609 
610             // We don't need to start the VM service for custom VMs.
611             if !requires_vm_service(config) {
612                 return Ok((VmContext::new(vm_context, None), cid, temp_dir));
613             }
614 
615             let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder();
616 
617             // Start VM service listening for connections from the new CID on port=CID.
618             let port = cid;
619             match RpcServer::new_vsock(service, cid, port) {
620                 Ok((vm_server, _)) => {
621                     vm_server.start();
622                     return Ok((VmContext::new(vm_context, Some(vm_server)), cid, temp_dir));
623                 }
624                 Err(err) => {
625                     warn!("Could not start RpcServer on port {}: {}", port, err);
626                 }
627             }
628         }
629         Err(anyhow!("Too many attempts to create VM context failed"))
630             .or_service_specific_exception(-1)
631     }
632 
create_vm_internal( &self, config: &VirtualMachineConfig, console_out_fd: Option<&ParcelFileDescriptor>, console_in_fd: Option<&ParcelFileDescriptor>, log_fd: Option<&ParcelFileDescriptor>, is_protected: &mut bool, dump_dt_fd: Option<&ParcelFileDescriptor>, ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>>633     fn create_vm_internal(
634         &self,
635         config: &VirtualMachineConfig,
636         console_out_fd: Option<&ParcelFileDescriptor>,
637         console_in_fd: Option<&ParcelFileDescriptor>,
638         log_fd: Option<&ParcelFileDescriptor>,
639         is_protected: &mut bool,
640         dump_dt_fd: Option<&ParcelFileDescriptor>,
641     ) -> binder::Result<Strong<dyn IVirtualMachine::IVirtualMachine>> {
642         let requester_uid = get_calling_uid();
643         let requester_debug_pid = get_calling_pid();
644 
645         let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?;
646 
647         let instance_id = extract_instance_id(config);
648         // Require vendor instance IDs to start with a specific prefix so that they don't conflict
649         // with system instance IDs.
650         //
651         // We should also make sure that non-vendor VMs do not use the vendor prefix, but there are
652         // already system VMs in the wild that may have randomly generated IDs with the prefix, so,
653         // for now, we only check in one direction.
654         const INSTANCE_ID_VENDOR_PREFIX: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF];
655         if matches!(calling_partition, CallingPartition::Vendor | CallingPartition::Odm)
656             && !instance_id.starts_with(INSTANCE_ID_VENDOR_PREFIX)
657         {
658             return Err(anyhow!(
659                 "vendor initiated VMs must have instance IDs starting with 0xFFFFFFFF, got {}",
660                 hex::encode(instance_id)
661             ))
662             .or_service_specific_exception(-1);
663         }
664 
665         check_config_features(config)?;
666 
667         if cfg!(early) {
668             check_config_allowed_for_early_vms(config)?;
669         }
670 
671         let caller_secontext = getprevcon().or_service_specific_exception(-1)?;
672         info!("callers secontext: {}", caller_secontext);
673 
674         // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission.
675         let (vm_context, cid, temporary_directory) = if cfg!(early) {
676             self.create_early_vm_context(config, CALLING_EXE_PATH.as_deref(), calling_partition)?
677         } else {
678             self.create_vm_context(requester_debug_pid, config)?
679         };
680 
681         if is_custom_config(config) {
682             check_use_custom_virtual_machine()?;
683         }
684 
685         let gdb_port = extract_gdb_port(config);
686 
687         // Additional permission checks if caller request gdb.
688         if gdb_port.is_some() {
689             check_gdb_allowed(config)?;
690         }
691 
692         let mut device_tree_overlays = vec![];
693         if let Some(dt_overlay) =
694             maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
695         {
696             device_tree_overlays.push(dt_overlay);
697         }
698         if let Some(dtbo) = get_dtbo(config) {
699             let dtbo = File::from(
700                 dtbo.as_ref()
701                     .try_clone()
702                     .context("Failed to create VM DTBO from ParcelFileDescriptor")
703                     .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
704             );
705             device_tree_overlays.push(dtbo);
706         }
707 
708         let debug_config = DebugConfig::new(config);
709         let ramdump = if !uses_gki_kernel(config) && debug_config.is_ramdump_needed() {
710             Some(prepare_ramdump_file(&temporary_directory)?)
711         } else {
712             None
713         };
714 
715         let state = &mut *self.state.lock().unwrap();
716         let console_out_fd =
717             clone_or_prepare_logger_fd(console_out_fd, format!("Console({})", cid))?;
718         let console_in_fd = console_in_fd.map(clone_file).transpose()?;
719         let log_fd = clone_or_prepare_logger_fd(log_fd, format!("Log({})", cid))?;
720         let dump_dt_fd = if let Some(fd) = dump_dt_fd {
721             Some(clone_file(fd)?)
722         } else if debug_config.dump_device_tree {
723             Some(prepare_dump_dt_file(&temporary_directory)?)
724         } else {
725             None
726         };
727 
728         // Counter to generate unique IDs for temporary image files.
729         let mut next_temporary_image_id = 0;
730         // Files which are referred to from composite images. These must be mapped to the crosvm
731         // child process, and not closed before it is started.
732         let mut indirect_files = vec![];
733 
734         let (is_app_config, config) = match config {
735             VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)),
736             VirtualMachineConfig::AppConfig(config) => {
737                 let config = load_app_config(config, &debug_config, &temporary_directory)
738                     .or_service_specific_exception_with(-1, |e| {
739                         *is_protected = config.protectedVm;
740                         let message = format!("Failed to load app config: {:?}", e);
741                         error!("{}", message);
742                         message
743                     })?;
744                 (true, BorrowedOrOwned::Owned(config))
745             }
746         };
747         let config = config.as_ref();
748         *is_protected = config.protectedVm;
749 
750         if !config.teeServices.is_empty() {
751             if !config.protectedVm {
752                 return Err(anyhow!("only protected VMs can request tee services"))
753                     .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
754             }
755             check_tee_service_permission(&caller_secontext, &config.teeServices)
756                 .with_log()
757                 .or_binder_exception(ExceptionCode::SECURITY)?;
758         }
759 
760         let mut system_tee_services = Vec::new();
761         let mut vendor_tee_services = Vec::new();
762         for tee_service in config.teeServices.clone() {
763             if !tee_service.starts_with("vendor.") {
764                 check_known_tee_service(&tee_service)?;
765                 system_tee_services.push(tee_service);
766             } else {
767                 vendor_tee_services.push(tee_service);
768             }
769         }
770 
771         if !vendor_tee_services.is_empty() && !is_vm_capabilities_hal_supported() {
772             return Err(anyhow!(
773                 "requesting access to tee services requires {VM_CAPABILITIES_HAL_IDENTIFIER}"
774             ))
775             .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
776         }
777 
778         // TODO(b/391774181): remove this check in a follow-up patch.
779         if !system_tee_services.is_empty() {
780             return Err(anyhow!("support for system tee services is coming soon!"))
781                 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
782         }
783 
784         let kernel = maybe_clone_file(&config.kernel)?;
785         let initrd = maybe_clone_file(&config.initrd)?;
786 
787         if config.protectedVm {
788             // Fail fast with a meaningful error message in case device doesn't support pVMs.
789             check_protected_vm_is_supported()?;
790 
791             // In a protected VM, we require custom kernels to come from a trusted source
792             // (b/237054515).
793             check_label_for_kernel_files(&kernel, &initrd, calling_partition)
794                 .or_service_specific_exception(-1)?;
795 
796             // Check if partition images are labeled incorrectly. This is to prevent random images
797             // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps)
798             // from being loaded in a pVM. This applies to everything but the instance image in the
799             // raw config, and everything but the non-executable, generated partitions in the app
800             // config.
801             config
802                 .disks
803                 .iter()
804                 .flat_map(|disk| disk.image.as_ref())
805                 .try_for_each(|image| check_label_for_file(image, "disk image", calling_partition))
806                 .or_service_specific_exception(-1)?;
807             config
808                 .disks
809                 .iter()
810                 .flat_map(|disk| disk.partitions.iter())
811                 .filter(|partition| {
812                     if is_app_config {
813                         !is_safe_app_partition(&partition.label)
814                     } else {
815                         !is_safe_raw_partition(&partition.label)
816                     }
817                 })
818                 .try_for_each(|partition| check_label_for_partition(partition, calling_partition))
819                 .or_service_specific_exception(-1)?;
820         }
821 
822         // Check if files for payloads and bases are on the same side of the Treble boundary as the
823         // calling process, as they may have unstable interfaces.
824         check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?;
825 
826         let zero_filler_path = temporary_directory.join("zero.img");
827         write_zero_filler(&zero_filler_path)
828             .context("Failed to make composite image")
829             .with_log()
830             .or_service_specific_exception(-1)?;
831 
832         // Assemble disk images if needed.
833         let disks = config
834             .disks
835             .iter()
836             .map(|disk| {
837                 assemble_disk_image(
838                     disk,
839                     &zero_filler_path,
840                     &temporary_directory,
841                     &mut next_temporary_image_id,
842                     &mut indirect_files,
843                 )
844             })
845             .collect::<Result<Vec<DiskFile>, _>>()?;
846 
847         let shared_paths = assemble_shared_paths(&config.sharedPaths, &temporary_directory)?;
848 
849         let (vfio_devices, dtbo) = match &config.devices {
850             AssignedDevices::Devices(devices) if !devices.is_empty() => {
851                 let mut set = HashSet::new();
852                 for device in devices.iter() {
853                     let path = canonicalize(device)
854                         .with_context(|| format!("can't canonicalize {device}"))
855                         .or_service_specific_exception(-1)?;
856                     if !set.insert(path) {
857                         return Err(anyhow!("duplicated device {device}"))
858                             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
859                     }
860                 }
861                 let devices = GLOBAL_SERVICE.bindDevicesToVfioDriver(devices)?;
862                 let dtbo_file = File::from(
863                     GLOBAL_SERVICE
864                         .getDtboFile()?
865                         .as_ref()
866                         .try_clone()
867                         .context("Failed to create VM DTBO from ParcelFileDescriptor")
868                         .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
869                 );
870                 (devices, Some(dtbo_file))
871             }
872             _ => (vec![], None),
873         };
874         let display_config = if cfg!(paravirtualized_devices) {
875             config
876                 .displayConfig
877                 .as_ref()
878                 .map(DisplayConfig::new)
879                 .transpose()
880                 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
881         } else {
882             None
883         };
884         let gpu_config = if cfg!(paravirtualized_devices) {
885             config
886                 .gpuConfig
887                 .as_ref()
888                 .map(GpuConfig::new)
889                 .transpose()
890                 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
891         } else {
892             None
893         };
894 
895         let input_device_options = if cfg!(paravirtualized_devices) {
896             config
897                 .inputDevices
898                 .iter()
899                 .map(to_input_device_option_from)
900                 .collect::<Result<Vec<InputDeviceOption>, _>>()
901                 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?
902         } else {
903             vec![]
904         };
905 
906         // Create TAP network interface if the VM supports network.
907         let tap = if cfg!(network) && config.networkSupported {
908             if *is_protected {
909                 return Err(anyhow!("Network feature is not supported for pVM yet"))
910                     .with_log()
911                     .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)?;
912             }
913             Some(File::from(
914                 GLOBAL_SERVICE
915                     .createTapInterface(&get_this_pid().to_string())?
916                     .as_ref()
917                     .try_clone()
918                     .context("Failed to get TAP interface from ParcelFileDescriptor")
919                     .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
920             ))
921         } else {
922             None
923         };
924 
925         let audio_config = if cfg!(paravirtualized_devices) {
926             config.audioConfig.as_ref().map(AudioConfig::new)
927         } else {
928             None
929         };
930 
931         let usb_config = config
932             .usbConfig
933             .as_ref()
934             .map(UsbConfig::new)
935             .unwrap_or(Ok(UsbConfig { controller: false }))
936             .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
937 
938         let detect_hangup = is_app_config && gdb_port.is_none();
939 
940         let custom_memory_backing_files = config
941             .customMemoryBackingFiles
942             .iter()
943             .map(|memory_backing_file| {
944                 Ok((
945                     clone_file(
946                         memory_backing_file
947                             .file
948                             .as_ref()
949                             .context("missing CustomMemoryBackingFile FD")
950                             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?,
951                     )?
952                     .into(),
953                     memory_backing_file.rangeStart as u64,
954                     memory_backing_file.size as u64,
955                 ))
956             })
957             .collect::<binder::Result<_>>()?;
958 
959         let memory_reclaim_supported =
960             system_properties::read_bool("hypervisor.memory_reclaim.supported", false)
961                 .unwrap_or(false);
962 
963         let balloon = config.balloon && memory_reclaim_supported;
964 
965         if !balloon {
966             warn!(
967                 "Memory balloon not enabled:
968                 config.balloon={},hypervisor.memory_reclaim.supported={}",
969                 config.balloon, memory_reclaim_supported
970             );
971         }
972 
973         // Actually start the VM.
974         let crosvm_config = CrosvmConfig {
975             cid,
976             name: config.name.clone(),
977             bootloader: maybe_clone_file(&config.bootloader)?,
978             kernel,
979             initrd,
980             disks,
981             shared_paths,
982             params: config.params.to_owned(),
983             protected: *is_protected,
984             debug_config,
985             memory_mib: config
986                 .memoryMib
987                 .try_into()
988                 .ok()
989                 .and_then(NonZeroU32::new)
990                 .unwrap_or(NonZeroU32::new(256).unwrap()),
991             swiotlb_mib: config.swiotlbMib.try_into().ok().and_then(NonZeroU32::new),
992             cpus: config.cpuOptions.clone(),
993             console_out_fd,
994             console_in_fd,
995             log_fd,
996             ramdump,
997             indirect_files,
998             platform_version: parse_platform_version_req(&config.platformVersion)?,
999             detect_hangup,
1000             gdb_port,
1001             vfio_devices,
1002             dtbo,
1003             device_tree_overlays,
1004             display_config,
1005             input_device_options,
1006             hugepages: config.hugePages,
1007             tap,
1008             console_input_device: config.consoleInputDevice.clone(),
1009             boost_uclamp: config.boostUclamp,
1010             gpu_config,
1011             audio_config,
1012             balloon,
1013             usb_config,
1014             dump_dt_fd,
1015             enable_hypervisor_specific_auth_method: config.enableHypervisorSpecificAuthMethod,
1016             instance_id,
1017             custom_memory_backing_files,
1018             start_suspended: !vendor_tee_services.is_empty(),
1019         };
1020         let instance = Arc::new(
1021             VmInstance::new(
1022                 crosvm_config,
1023                 temporary_directory,
1024                 requester_uid,
1025                 requester_debug_pid,
1026                 vm_context,
1027                 vendor_tee_services,
1028             )
1029             .with_context(|| format!("Failed to create VM with config {:?}", config))
1030             .with_log()
1031             .or_service_specific_exception(-1)?,
1032         );
1033         state.add_vm(Arc::downgrade(&instance));
1034         Ok(VirtualMachine::create(instance))
1035     }
1036 }
1037 
1038 /// Returns whether a VM config represents a "custom" virtual machine, which requires the
1039 /// USE_CUSTOM_VIRTUAL_MACHINE.
is_custom_config(config: &VirtualMachineConfig) -> bool1040 fn is_custom_config(config: &VirtualMachineConfig) -> bool {
1041     match config {
1042         // Any raw (non-Microdroid) VM is considered custom.
1043         VirtualMachineConfig::RawConfig(_) => true,
1044         VirtualMachineConfig::AppConfig(config) => {
1045             // Some features are reserved for platform apps only, even when using
1046             // VirtualMachineAppConfig. Almost all of these features are grouped in the
1047             // CustomConfig struct:
1048             // - controlling CPUs;
1049             // - gdbPort is set, meaning that crosvm will start a gdb server;
1050             // - using anything other than the default kernel;
1051             // - specifying devices to be assigned.
1052             if config.customConfig.is_some() {
1053                 true
1054             } else {
1055                 // Additional custom features not included in CustomConfig:
1056                 // - specifying a config file;
1057                 // - specifying extra APKs;
1058                 // - specifying an OS other than Microdroid.
1059                 (match &config.payload {
1060                     Payload::ConfigPath(_) => true,
1061                     Payload::PayloadConfig(payload_config) => !payload_config.extraApks.is_empty(),
1062                 }) || config.osName != MICRODROID_OS_NAME
1063             }
1064         }
1065     }
1066 }
1067 
1068 /// Returns whether a VM config requires VirtualMachineService running on the host. Only Microdroid
1069 /// VM (i.e. AppConfig) requires it. However, a few Microdroid tests use RawConfig for Microdroid
1070 /// VM. To handle the exceptional case, we use name as a second criteria; if the name is
1071 /// "microdroid" we run VirtualMachineService
requires_vm_service(config: &VirtualMachineConfig) -> bool1072 fn requires_vm_service(config: &VirtualMachineConfig) -> bool {
1073     match config {
1074         VirtualMachineConfig::AppConfig(_) => true,
1075         VirtualMachineConfig::RawConfig(config) => config.name == "microdroid",
1076     }
1077 }
1078 
1079 /// Returns the name of the config
get_name(config: &VirtualMachineConfig) -> &str1080 fn get_name(config: &VirtualMachineConfig) -> &str {
1081     match config {
1082         VirtualMachineConfig::AppConfig(config) => &config.name,
1083         VirtualMachineConfig::RawConfig(config) => &config.name,
1084     }
1085 }
1086 
extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>>1087 fn extract_vendor_hashtree_digest(config: &VirtualMachineConfig) -> Result<Option<Vec<u8>>> {
1088     let VirtualMachineConfig::AppConfig(config) = config else {
1089         return Ok(None);
1090     };
1091     let Some(custom_config) = &config.customConfig else {
1092         return Ok(None);
1093     };
1094     let Some(file) = custom_config.vendorImage.as_ref() else {
1095         return Ok(None);
1096     };
1097 
1098     let file = clone_file(file)?;
1099     let size =
1100         file.metadata().context("Failed to get metadata from microdroid vendor image")?.len();
1101     let vbmeta = VbMetaImage::verify_reader_region(&file, 0, size)
1102         .context("Failed to get vbmeta from microdroid-vendor.img")?;
1103 
1104     for descriptor in vbmeta.descriptors()?.iter() {
1105         if let vbmeta::Descriptor::Hashtree(_) = descriptor {
1106             let root_digest = hex::encode(descriptor.to_hashtree()?.root_digest());
1107             return Ok(Some(root_digest.as_bytes().to_vec()));
1108         }
1109     }
1110     Err(anyhow!("No hashtree digest is extracted from microdroid vendor image"))
1111 }
1112 
maybe_create_reference_dt_overlay( config: &VirtualMachineConfig, instance_id: &[u8; 64], temporary_directory: &Path, ) -> binder::Result<Option<File>>1113 fn maybe_create_reference_dt_overlay(
1114     config: &VirtualMachineConfig,
1115     instance_id: &[u8; 64],
1116     temporary_directory: &Path,
1117 ) -> binder::Result<Option<File>> {
1118     // Currently, VirtMgr adds the host copy of reference DT & untrusted properties
1119     // (e.g. instance-id)
1120     let host_ref_dt = Path::new(VM_REFERENCE_DT_ON_HOST_PATH);
1121     let host_ref_dt = if host_ref_dt.exists()
1122         && read_dir(host_ref_dt).or_service_specific_exception(-1)?.next().is_some()
1123     {
1124         Some(host_ref_dt)
1125     } else {
1126         warn!("VM reference DT doesn't exist in host DT");
1127         None
1128     };
1129 
1130     let vendor_hashtree_digest = extract_vendor_hashtree_digest(config)
1131         .context("Failed to extract vendor hashtree digest")
1132         .or_service_specific_exception(-1)?;
1133 
1134     let mut trusted_props = if let Some(ref vendor_hashtree_digest) = vendor_hashtree_digest {
1135         info!(
1136             "Passing vendor hashtree digest to pvmfw. This will be rejected if it doesn't \
1137                 match the trusted digest in the pvmfw config, causing the VM to fail to start."
1138         );
1139         vec![(c"vendor_hashtree_descriptor_root_digest", vendor_hashtree_digest.as_slice())]
1140     } else {
1141         vec![]
1142     };
1143 
1144     let key_material;
1145     let mut untrusted_props = Vec::with_capacity(2);
1146     if cfg!(llpvm_changes) {
1147         untrusted_props.push((c"instance-id", &instance_id[..]));
1148         let want_updatable = extract_want_updatable(config);
1149         if want_updatable && is_secretkeeper_supported() {
1150             // Let guest know that it can defer rollback protection to Secretkeeper by setting
1151             // an empty property in untrusted node in DT. This enables Updatable VMs.
1152             untrusted_props.push((c"defer-rollback-protection", &[]));
1153             let sk: Strong<dyn ISecretkeeper> =
1154                 binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
1155             if sk.getInterfaceVersion()? >= 2 {
1156                 let PublicKey { keyMaterial } = sk.getSecretkeeperIdentity()?;
1157                 key_material = keyMaterial;
1158                 trusted_props.push((c"secretkeeper_public_key", key_material.as_slice()));
1159             }
1160         }
1161     }
1162 
1163     let device_tree_overlay = if host_ref_dt.is_some()
1164         || !untrusted_props.is_empty()
1165         || !trusted_props.is_empty()
1166     {
1167         let dt_output = temporary_directory.join(VM_DT_OVERLAY_PATH);
1168         let mut data = [0_u8; VM_DT_OVERLAY_MAX_SIZE];
1169         let fdt =
1170             create_device_tree_overlay(&mut data, host_ref_dt, &untrusted_props, &trusted_props)
1171                 .map_err(|e| anyhow!("Failed to create DT overlay, {e:?}"))
1172                 .or_service_specific_exception(-1)?;
1173         fs::write(&dt_output, fdt.as_slice()).or_service_specific_exception(-1)?;
1174         Some(File::open(dt_output).or_service_specific_exception(-1)?)
1175     } else {
1176         None
1177     };
1178     Ok(device_tree_overlay)
1179 }
1180 
get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor>1181 fn get_dtbo(config: &VirtualMachineConfig) -> Option<&ParcelFileDescriptor> {
1182     let VirtualMachineConfig::RawConfig(config) = config else {
1183         return None;
1184     };
1185     match &config.devices {
1186         AssignedDevices::Dtbo(dtbo) => dtbo.as_ref(),
1187         _ => None,
1188     }
1189 }
1190 
write_zero_filler(zero_filler_path: &Path) -> Result<()>1191 fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
1192     let file = OpenOptions::new()
1193         .create_new(true)
1194         .read(true)
1195         .write(true)
1196         .open(zero_filler_path)
1197         .with_context(|| "Failed to create zero.img")?;
1198     file.set_len(ZERO_FILLER_SIZE)?;
1199     Ok(())
1200 }
1201 
format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()>1202 fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
1203     part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
1204     part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
1205     part.flush()
1206 }
1207 
format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()>1208 fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> {
1209     part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?;
1210     part.flush()
1211 }
1212 
round_up(input: u64, granularity: u64) -> u641213 fn round_up(input: u64, granularity: u64) -> u64 {
1214     if granularity == 0 {
1215         return input;
1216     }
1217     // If the input is absurdly large we round down instead of up; it's going to fail anyway.
1218     let result = input.checked_add(granularity - 1).unwrap_or(input);
1219     (result / granularity) * granularity
1220 }
1221 
to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption>1222 fn to_input_device_option_from(input_device: &InputDevice) -> Result<InputDeviceOption> {
1223     Ok(match input_device {
1224         InputDevice::SingleTouch(single_touch) => InputDeviceOption::SingleTouch {
1225             file: clone_file(single_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1226             height: u32::try_from(single_touch.height)?,
1227             width: u32::try_from(single_touch.width)?,
1228             name: if !single_touch.name.is_empty() {
1229                 Some(single_touch.name.clone())
1230             } else {
1231                 None
1232             },
1233         },
1234         InputDevice::EvDev(evdev) => InputDeviceOption::EvDev(clone_file(
1235             evdev.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1236         )?),
1237         InputDevice::Keyboard(keyboard) => InputDeviceOption::Keyboard(clone_file(
1238             keyboard.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1239         )?),
1240         InputDevice::Mouse(mouse) => InputDeviceOption::Mouse(clone_file(
1241             mouse.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1242         )?),
1243         InputDevice::Switches(switches) => InputDeviceOption::Switches(clone_file(
1244             switches.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?,
1245         )?),
1246         InputDevice::Trackpad(trackpad) => InputDeviceOption::MultiTouchTrackpad {
1247             file: clone_file(trackpad.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1248             height: u32::try_from(trackpad.height)?,
1249             width: u32::try_from(trackpad.width)?,
1250             name: if !trackpad.name.is_empty() { Some(trackpad.name.clone()) } else { None },
1251         },
1252         InputDevice::MultiTouch(multi_touch) => InputDeviceOption::MultiTouch {
1253             file: clone_file(multi_touch.pfd.as_ref().ok_or(anyhow!("pfd should have value"))?)?,
1254             height: u32::try_from(multi_touch.height)?,
1255             width: u32::try_from(multi_touch.width)?,
1256             name: if !multi_touch.name.is_empty() { Some(multi_touch.name.clone()) } else { None },
1257         },
1258     })
1259 }
1260 
assemble_shared_paths( shared_paths: &[SharedPath], temporary_directory: &Path, ) -> Result<Vec<SharedPathConfig>, Status>1261 fn assemble_shared_paths(
1262     shared_paths: &[SharedPath],
1263     temporary_directory: &Path,
1264 ) -> Result<Vec<SharedPathConfig>, Status> {
1265     if shared_paths.is_empty() {
1266         return Ok(Vec::new()); // Return an empty vector if shared_paths is empty
1267     }
1268 
1269     shared_paths
1270         .iter()
1271         .map(|path| {
1272             Ok(SharedPathConfig {
1273                 path: path.sharedPath.clone(),
1274                 host_uid: path.hostUid,
1275                 host_gid: path.hostGid,
1276                 guest_uid: path.guestUid,
1277                 guest_gid: path.guestGid,
1278                 mask: path.mask,
1279                 tag: path.tag.clone(),
1280                 socket_path: temporary_directory
1281                     .join(&path.socketPath)
1282                     .to_string_lossy()
1283                     .to_string(),
1284                 socket_fd: maybe_clone_file(&path.socketFd)?,
1285                 app_domain: path.appDomain,
1286             })
1287         })
1288         .collect()
1289 }
1290 
1291 /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
1292 ///
1293 /// This may involve assembling a composite disk from a set of partition images.
assemble_disk_image( disk: &DiskImage, zero_filler_path: &Path, temporary_directory: &Path, next_temporary_image_id: &mut u64, indirect_files: &mut Vec<File>, ) -> Result<DiskFile, Status>1294 fn assemble_disk_image(
1295     disk: &DiskImage,
1296     zero_filler_path: &Path,
1297     temporary_directory: &Path,
1298     next_temporary_image_id: &mut u64,
1299     indirect_files: &mut Vec<File>,
1300 ) -> Result<DiskFile, Status> {
1301     let image = if !disk.partitions.is_empty() {
1302         if disk.image.is_some() {
1303             warn!("DiskImage {:?} contains both image and partitions.", disk);
1304             return Err(anyhow!("DiskImage contains both image and partitions"))
1305                 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
1306         }
1307 
1308         let composite_image_filenames =
1309             make_composite_image_filenames(temporary_directory, next_temporary_image_id);
1310         let (image, partition_files) = make_composite_image(
1311             &disk.partitions,
1312             zero_filler_path,
1313             &composite_image_filenames.composite,
1314             &composite_image_filenames.header,
1315             &composite_image_filenames.footer,
1316         )
1317         .with_context(|| format!("Failed to make composite disk image with config {:?}", disk))
1318         .with_log()
1319         .or_service_specific_exception(-1)?;
1320 
1321         // Pass the file descriptors for the various partition files to crosvm when it
1322         // is run.
1323         indirect_files.extend(partition_files);
1324 
1325         image
1326     } else if let Some(image) = &disk.image {
1327         clone_file(image)?
1328     } else {
1329         warn!("DiskImage {:?} didn't contain image or partitions.", disk);
1330         return Err(anyhow!("DiskImage didn't contain image or partitions."))
1331             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
1332     };
1333 
1334     Ok(DiskFile { image, writable: disk.writable })
1335 }
1336 
append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig)1337 fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) {
1338     if let Some(ref mut params) = vm_config.params {
1339         params.push(' ');
1340         params.push_str(param)
1341     } else {
1342         vm_config.params = Some(param.to_owned())
1343     }
1344 }
1345 
extract_os_name_from_config_path(config: &Path) -> Option<String>1346 fn extract_os_name_from_config_path(config: &Path) -> Option<String> {
1347     if config.extension()?.to_str()? != "json" {
1348         return None;
1349     }
1350 
1351     Some(config.with_extension("").file_name()?.to_str()?.to_owned())
1352 }
1353 
extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>>1354 fn extract_os_names_from_configs(config_glob_pattern: &str) -> Result<HashSet<String>> {
1355     let configs = glob(config_glob_pattern)?.collect::<Result<Vec<_>, _>>()?;
1356     let os_names =
1357         configs.iter().filter_map(|x| extract_os_name_from_config_path(x)).collect::<HashSet<_>>();
1358 
1359     Ok(os_names)
1360 }
1361 
get_supported_os_names() -> Result<HashSet<String>>1362 fn get_supported_os_names() -> Result<HashSet<String>> {
1363     if !cfg!(vendor_modules) {
1364         return Ok(iter::once(MICRODROID_OS_NAME.to_owned()).collect());
1365     }
1366 
1367     extract_os_names_from_configs("/apex/com.android.virt/etc/microdroid*.json")
1368 }
1369 
is_valid_os(os_name: &str) -> bool1370 fn is_valid_os(os_name: &str) -> bool {
1371     SUPPORTED_OS_NAMES.contains(os_name)
1372 }
1373 
uses_gki_kernel(config: &VirtualMachineConfig) -> bool1374 fn uses_gki_kernel(config: &VirtualMachineConfig) -> bool {
1375     if !cfg!(vendor_modules) {
1376         return false;
1377     }
1378     match config {
1379         VirtualMachineConfig::RawConfig(_) => false,
1380         VirtualMachineConfig::AppConfig(config) => config.osName.starts_with("microdroid_gki-"),
1381     }
1382 }
1383 
load_app_config( config: &VirtualMachineAppConfig, debug_config: &DebugConfig, temporary_directory: &Path, ) -> Result<VirtualMachineRawConfig>1384 fn load_app_config(
1385     config: &VirtualMachineAppConfig,
1386     debug_config: &DebugConfig,
1387     temporary_directory: &Path,
1388 ) -> Result<VirtualMachineRawConfig> {
1389     let apk_file = clone_file(config.apk.as_ref().unwrap())?;
1390     let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
1391     let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
1392 
1393     let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() {
1394         Some(clone_file(file)?)
1395     } else {
1396         None
1397     };
1398 
1399     let vm_payload_config;
1400     let extra_apk_files: Vec<_>;
1401     match &config.payload {
1402         Payload::ConfigPath(config_path) => {
1403             vm_payload_config =
1404                 load_vm_payload_config_from_file(&apk_file, config_path.as_str())
1405                     .with_context(|| format!("Couldn't read config from {}", config_path))?;
1406             extra_apk_files = vm_payload_config
1407                 .extra_apks
1408                 .iter()
1409                 .enumerate()
1410                 .map(|(i, apk)| {
1411                     File::open(PathBuf::from(&apk.path))
1412                         .with_context(|| format!("Failed to open extra apk #{i} {}", apk.path))
1413                 })
1414                 .collect::<Result<_>>()?;
1415         }
1416         Payload::PayloadConfig(payload_config) => {
1417             vm_payload_config = create_vm_payload_config(payload_config)?;
1418             extra_apk_files =
1419                 payload_config.extraApks.iter().map(clone_file).collect::<binder::Result<_>>()?;
1420         }
1421     };
1422 
1423     let payload_config_os = vm_payload_config.os.name.as_str();
1424     if !payload_config_os.is_empty() && payload_config_os != "microdroid" {
1425         bail!("'os' in payload config is deprecated");
1426     }
1427 
1428     // For now, the only supported OS is Microdroid and Microdroid GKI
1429     let os_name = config.osName.as_str();
1430     if !is_valid_os(os_name) {
1431         bail!("Unknown OS \"{}\"", os_name);
1432     }
1433 
1434     // It is safe to construct a filename based on the os_name because we've already checked that it
1435     // is one of the allowed values.
1436     let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
1437     let vm_config_file = File::open(vm_config_path)?;
1438     let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
1439 
1440     if let Some(custom_config) = &config.customConfig {
1441         if let Some(file) = custom_config.customKernelImage.as_ref() {
1442             vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?))
1443         }
1444         vm_config.gdbPort = custom_config.gdbPort;
1445 
1446         if let Some(file) = custom_config.vendorImage.as_ref() {
1447             add_microdroid_vendor_image(clone_file(file)?, &mut vm_config);
1448             append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config)
1449         }
1450 
1451         vm_config.devices = AssignedDevices::Devices(custom_config.devices.clone());
1452         vm_config.networkSupported = custom_config.networkSupported;
1453 
1454         for param in custom_config.extraKernelCmdlineParams.iter() {
1455             append_kernel_param(param, &mut vm_config);
1456         }
1457 
1458         vm_config.teeServices.clone_from(&custom_config.teeServices);
1459     }
1460 
1461     if config.memoryMib > 0 {
1462         vm_config.memoryMib = config.memoryMib;
1463     }
1464 
1465     vm_config.name.clone_from(&config.name);
1466     vm_config.protectedVm = config.protectedVm;
1467     vm_config.cpuOptions = config.cpuOptions.clone();
1468     vm_config.hugePages = config.hugePages || vm_payload_config.hugepages;
1469     vm_config.boostUclamp = config.boostUclamp;
1470 
1471     // Microdroid takes additional init ramdisk & (optionally) storage image
1472     add_microdroid_system_images(config, instance_file, storage_image, os_name, &mut vm_config)?;
1473 
1474     // Include Microdroid payload disk (contains apks, idsigs) in vm config
1475     add_microdroid_payload_images(
1476         config,
1477         debug_config,
1478         temporary_directory,
1479         apk_file,
1480         idsig_file,
1481         extra_apk_files,
1482         &vm_payload_config,
1483         &mut vm_config,
1484     )?;
1485 
1486     Ok(vm_config)
1487 }
1488 
check_partition_for_file( fd: &ParcelFileDescriptor, calling_partition: CallingPartition, ) -> Result<()>1489 fn check_partition_for_file(
1490     fd: &ParcelFileDescriptor,
1491     calling_partition: CallingPartition,
1492 ) -> Result<()> {
1493     let path = format!("/proc/self/fd/{}", fd.as_raw_fd());
1494     let link = fs::read_link(&path).with_context(|| format!("can't read_link {path}"))?;
1495 
1496     // microdroid vendor image is OK
1497     if cfg!(vendor_modules) && link == Path::new("/vendor/etc/avf/microdroid/microdroid_vendor.img")
1498     {
1499         return Ok(());
1500     }
1501 
1502     let fd_partition = find_partition(Some(&link))
1503         .with_context(|| format!("can't find_partition {}", link.display()))?;
1504     let is_fd_vendor =
1505         fd_partition == CallingPartition::Vendor || fd_partition == CallingPartition::Odm;
1506     let is_caller_vendor =
1507         calling_partition == CallingPartition::Vendor || calling_partition == CallingPartition::Odm;
1508 
1509     if is_fd_vendor != is_caller_vendor {
1510         bail!("{} can't be used for VM client in {calling_partition}", link.display());
1511     }
1512 
1513     Ok(())
1514 }
1515 
check_partitions_for_files( config: &VirtualMachineRawConfig, calling_partition: CallingPartition, ) -> Result<()>1516 fn check_partitions_for_files(
1517     config: &VirtualMachineRawConfig,
1518     calling_partition: CallingPartition,
1519 ) -> Result<()> {
1520     config
1521         .disks
1522         .iter()
1523         .flat_map(|disk| disk.partitions.iter())
1524         .filter_map(|partition| partition.image.as_ref())
1525         .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1526 
1527     config
1528         .disks
1529         .iter()
1530         .filter_map(|disk| disk.image.as_ref())
1531         .try_for_each(|fd| check_partition_for_file(fd, calling_partition))?;
1532 
1533     config.kernel.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1534     config.initrd.as_ref().map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1535     config
1536         .bootloader
1537         .as_ref()
1538         .map_or(Ok(()), |fd| check_partition_for_file(fd, calling_partition))?;
1539 
1540     Ok(())
1541 }
1542 
load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig>1543 fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> {
1544     let mut apk_zip = ZipArchive::new(apk_file)?;
1545     let config_file = apk_zip.by_name(config_path)?;
1546     Ok(serde_json::from_reader(config_file)?)
1547 }
1548 
create_vm_payload_config( payload_config: &VirtualMachinePayloadConfig, ) -> Result<VmPayloadConfig>1549 fn create_vm_payload_config(
1550     payload_config: &VirtualMachinePayloadConfig,
1551 ) -> Result<VmPayloadConfig> {
1552     // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit
1553     // parameters we've been given. Microdroid will do something equivalent inside the VM using the
1554     // payload config that we send it via the metadata file.
1555 
1556     let payload_binary_name = &payload_config.payloadBinaryName;
1557     if payload_binary_name.contains('/') {
1558         bail!("Payload binary name must not specify a path: {payload_binary_name}");
1559     }
1560 
1561     let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() };
1562 
1563     // The VM only cares about how many there are, these names are actually ignored.
1564     let extra_apk_count = payload_config.extraApks.len();
1565     let extra_apks =
1566         (0..extra_apk_count).map(|i| ApkConfig { path: format!("extra-apk-{i}") }).collect();
1567 
1568     if check_use_relaxed_microdroid_rollback_protection().is_ok() {
1569         // The only payload delivered via Mainline module in this release requires
1570         // com.android.i18n apex. However, we are past all the reasonable deadlines to add new
1571         // APIs, so we use the fact that the payload is granted
1572         // USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION permission as a signal that we should include
1573         // com.android.i18n APEX.
1574         // TODO: remove this after we provide a stable @SystemApi to load additional APEXes to
1575         // Microdroid pVMs.
1576         let apexes = vec![ApexConfig { name: String::from("com.android.i18n") }];
1577         Ok(VmPayloadConfig { task: Some(task), apexes, extra_apks, ..Default::default() })
1578     } else {
1579         Ok(VmPayloadConfig { task: Some(task), extra_apks, ..Default::default() })
1580     }
1581 }
1582 
1583 /// Generates a unique filename to use for a composite disk image.
make_composite_image_filenames( temporary_directory: &Path, next_temporary_image_id: &mut u64, ) -> CompositeImageFilenames1584 fn make_composite_image_filenames(
1585     temporary_directory: &Path,
1586     next_temporary_image_id: &mut u64,
1587 ) -> CompositeImageFilenames {
1588     let id = *next_temporary_image_id;
1589     *next_temporary_image_id += 1;
1590     CompositeImageFilenames {
1591         composite: temporary_directory.join(format!("composite-{}.img", id)),
1592         header: temporary_directory.join(format!("composite-{}-header.img", id)),
1593         footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
1594     }
1595 }
1596 
1597 /// Filenames for a composite disk image, including header and footer partitions.
1598 #[derive(Clone, Debug, Eq, PartialEq)]
1599 struct CompositeImageFilenames {
1600     /// The composite disk image itself.
1601     composite: PathBuf,
1602     /// The header partition image.
1603     header: PathBuf,
1604     /// The footer partition image.
1605     footer: PathBuf,
1606 }
1607 
1608 /// Checks whether the caller has a specific permission
check_permission(perm: &str) -> binder::Result<()>1609 fn check_permission(perm: &str) -> binder::Result<()> {
1610     if cfg!(early) {
1611         // Skip permission check for early VMs, in favor of SELinux
1612         return Ok(());
1613     }
1614     let calling_pid = get_calling_pid();
1615     let calling_uid = get_calling_uid();
1616     // Root can do anything
1617     if calling_uid == 0 {
1618         return Ok(());
1619     }
1620     let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
1621         binder::wait_for_interface("permission")?;
1622     if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
1623         Ok(())
1624     } else {
1625         Err(anyhow!("does not have the {} permission", perm))
1626             .or_binder_exception(ExceptionCode::SECURITY)
1627     }
1628 }
1629 
1630 /// Check whether the caller of the current Binder method is allowed to manage VMs
check_manage_access() -> binder::Result<()>1631 fn check_manage_access() -> binder::Result<()> {
1632     check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
1633 }
1634 
1635 /// Check whether the caller of the current Binder method is allowed to create custom VMs
check_use_custom_virtual_machine() -> binder::Result<()>1636 fn check_use_custom_virtual_machine() -> binder::Result<()> {
1637     check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
1638 }
1639 
1640 /// Check whether the caller of the current binder method is allowed to use relaxed microdroid
1641 /// rollback protection schema.
check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()>1642 fn check_use_relaxed_microdroid_rollback_protection() -> binder::Result<()> {
1643     check_permission("android.permission.USE_RELAXED_MICRODROID_ROLLBACK_PROTECTION")
1644 }
1645 
1646 /// Return whether a partition is exempt from selinux label checks, because we know that it does
1647 /// not contain code and is likely to be generated in an app-writable directory.
is_safe_app_partition(label: &str) -> bool1648 fn is_safe_app_partition(label: &str) -> bool {
1649     // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs.
1650     label == "vm-instance"
1651         || label == "encryptedstore"
1652         || label == "microdroid-apk-idsig"
1653         || label == "payload-metadata"
1654         || label.starts_with("extra-idsig-")
1655 }
1656 
1657 /// Returns whether a partition with the given label is safe for a raw config VM.
is_safe_raw_partition(label: &str) -> bool1658 fn is_safe_raw_partition(label: &str) -> bool {
1659     label == "vm-instance"
1660 }
1661 
1662 /// Check that a file SELinux label is acceptable.
1663 ///
1664 /// We only want to allow code in a VM to be sourced from places that apps, and the
1665 /// system or vendor, do not have write access to.
1666 ///
1667 /// Note that sepolicy must also grant read access for these types to both virtualization
1668 /// service and crosvm.
1669 ///
1670 /// App private data files are deliberately excluded, to avoid arbitrary payloads being run on
1671 /// user devices (W^X).
check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()>1672 fn check_label_is_allowed(context: &SeContext, calling_partition: CallingPartition) -> Result<()> {
1673     match context.selinux_type()? {
1674         | "apk_data_file" // APKs of an installed app
1675         | "shell_data_file" // test files created via adb shell
1676         | "staging_data_file" // updated/staged APEX images
1677         | "system_file" // immutable dm-verity protected partition
1678         | "virtualizationservice_data_file" // files created by VS / VirtMgr
1679         | "vendor_microdroid_file" // immutable dm-verity protected partition (/vendor/etc/avf/microdroid/.*)
1680          => Ok(()),
1681         // It is difficult to require specific label types for vendor initiated VM's files.
1682         _ if calling_partition == CallingPartition::Vendor => Ok(()),
1683         _ => bail!("Label {} is not allowed", context),
1684     }
1685 }
1686 
check_label_for_partition( partition: &Partition, calling_partition: CallingPartition, ) -> Result<()>1687 fn check_label_for_partition(
1688     partition: &Partition,
1689     calling_partition: CallingPartition,
1690 ) -> Result<()> {
1691     let file = partition.image.as_ref().unwrap().as_ref();
1692     check_label_is_allowed(&getfilecon(file)?, calling_partition)
1693         .with_context(|| format!("Partition {} invalid", &partition.label))
1694 }
1695 
check_label_for_kernel_files( kernel: &Option<File>, initrd: &Option<File>, calling_partition: CallingPartition, ) -> Result<()>1696 fn check_label_for_kernel_files(
1697     kernel: &Option<File>,
1698     initrd: &Option<File>,
1699     calling_partition: CallingPartition,
1700 ) -> Result<()> {
1701     if let Some(f) = kernel {
1702         check_label_for_file(f, "kernel", calling_partition)?;
1703     }
1704     if let Some(f) = initrd {
1705         check_label_for_file(f, "initrd", calling_partition)?;
1706     }
1707     Ok(())
1708 }
check_label_for_file( file: &impl AsRawFd, name: &str, calling_partition: CallingPartition, ) -> Result<()>1709 fn check_label_for_file(
1710     file: &impl AsRawFd,
1711     name: &str,
1712     calling_partition: CallingPartition,
1713 ) -> Result<()> {
1714     check_label_is_allowed(&getfilecon(file)?, calling_partition)
1715         .with_context(|| format!("{} file invalid", name))
1716 }
1717 
1718 /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
1719 #[derive(Debug)]
1720 struct VirtualMachine {
1721     instance: Arc<VmInstance>,
1722 }
1723 
1724 impl VirtualMachine {
create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine>1725     fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine::IVirtualMachine> {
1726         BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default())
1727     }
1728 
handle_vendor_tee_services(&self) -> binder::Result<()>1729     fn handle_vendor_tee_services(&self) -> binder::Result<()> {
1730         // TODO(b/360102915): get vm_fd from crosvm
1731         // TODO(b/360102915): talk to HAL
1732         self.instance
1733             .resume_full()
1734             .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1735             .with_log()
1736             .or_service_specific_exception(-1)
1737     }
1738 }
1739 
1740 impl Interface for VirtualMachine {}
1741 
1742 impl IVirtualMachine::IVirtualMachine for VirtualMachine {
getCid(&self) -> binder::Result<i32>1743     fn getCid(&self) -> binder::Result<i32> {
1744         // Don't check permission. The owner of the VM might have passed this binder object to
1745         // others.
1746         Ok(self.instance.cid as i32)
1747     }
1748 
getState(&self) -> binder::Result<VirtualMachineState>1749     fn getState(&self) -> binder::Result<VirtualMachineState> {
1750         // Don't check permission. The owner of the VM might have passed this binder object to
1751         // others.
1752         Ok(get_state(&self.instance))
1753     }
1754 
registerCallback( &self, callback: &Strong<dyn IVirtualMachineCallback>, ) -> binder::Result<()>1755     fn registerCallback(
1756         &self,
1757         callback: &Strong<dyn IVirtualMachineCallback>,
1758     ) -> binder::Result<()> {
1759         // Don't check permission. The owner of the VM might have passed this binder object to
1760         // others.
1761 
1762         // Only register callback if it may be notified.
1763         // This also ensures no cyclic reference between callback and VmInstance after VM is died.
1764         let vm_state = self.instance.vm_state.lock().unwrap();
1765         if matches!(*vm_state, VmState::Dead) {
1766             warn!("Ignoring registerCallback() after VM is died");
1767         } else {
1768             self.instance.callbacks.add(callback.clone());
1769         }
1770         drop(vm_state);
1771 
1772         Ok(())
1773     }
1774 
start(&self) -> binder::Result<()>1775     fn start(&self) -> binder::Result<()> {
1776         self.instance
1777             .start()
1778             .with_context(|| format!("Error starting VM with CID {}", self.instance.cid))
1779             .with_log()
1780             .or_service_specific_exception(-1)?;
1781         if !self.instance.vendor_tee_services.is_empty() {
1782             self.handle_vendor_tee_services()
1783         } else {
1784             Ok(())
1785         }
1786     }
1787 
stop(&self) -> binder::Result<()>1788     fn stop(&self) -> binder::Result<()> {
1789         self.instance
1790             .kill()
1791             .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid))
1792             .with_log()
1793             .or_service_specific_exception(-1)
1794     }
1795 
isMemoryBalloonEnabled(&self) -> binder::Result<bool>1796     fn isMemoryBalloonEnabled(&self) -> binder::Result<bool> {
1797         Ok(self.instance.balloon_enabled)
1798     }
1799 
getMemoryBalloon(&self) -> binder::Result<i64>1800     fn getMemoryBalloon(&self) -> binder::Result<i64> {
1801         let balloon = self
1802             .instance
1803             .get_memory_balloon()
1804             .with_context(|| format!("Error getting balloon for VM with CID {}", self.instance.cid))
1805             .with_log()
1806             .or_service_specific_exception(-1)?;
1807         Ok(balloon.try_into().unwrap())
1808     }
1809 
setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()>1810     fn setMemoryBalloon(&self, num_bytes: i64) -> binder::Result<()> {
1811         self.instance
1812             .set_memory_balloon(num_bytes.try_into().unwrap())
1813             .with_context(|| format!("Error setting balloon for VM with CID {}", self.instance.cid))
1814             .with_log()
1815             .or_service_specific_exception(-1)
1816     }
1817 
connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor>1818     fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
1819         if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1820             return Err(Status::new_service_specific_error_str(
1821                 IVirtualMachine::ERROR_UNEXPECTED,
1822                 Some("Virtual Machine is not running"),
1823             ));
1824         }
1825         let port = port as u32;
1826         if port < VSOCK_PRIV_PORT_MAX {
1827             return Err(Status::new_service_specific_error_str(
1828                 IVirtualMachine::ERROR_UNEXPECTED,
1829                 Some("Can't connect to privileged port {port}"),
1830             ));
1831         }
1832         let stream = VsockStream::connect_with_cid_port(self.instance.cid, port)
1833             .context("Failed to connect")
1834             .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)?;
1835         Ok(vsock_stream_to_pfd(stream))
1836     }
1837 
createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder>1838     fn createAccessorBinder(&self, name: &str, port: i32) -> binder::Result<SpIBinder> {
1839         if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
1840             return Err(Status::new_service_specific_error_str(
1841                 IVirtualMachine::ERROR_UNEXPECTED,
1842                 Some("Virtual Machine is not running"),
1843             ));
1844         }
1845         let port = port as u32;
1846         if port < VSOCK_PRIV_PORT_MAX {
1847             return Err(Status::new_service_specific_error_str(
1848                 IVirtualMachine::ERROR_UNEXPECTED,
1849                 Some("Can't connect to privileged port {port}"),
1850             ));
1851         }
1852         let cid = self.instance.cid;
1853         let addr = sockaddr_vm {
1854             svm_family: AF_VSOCK as sa_family_t,
1855             svm_reserved1: 0,
1856             svm_port: port,
1857             svm_cid: cid,
1858             svm_zero: [0u8; 4],
1859         };
1860         let get_connection_info = move |_instance: &str| Some(ConnectionInfo::Vsock(addr));
1861         let accessor = Accessor::new(name, get_connection_info);
1862         accessor
1863             .as_binder()
1864             .context("The newly created Accessor should always have a binder")
1865             .or_service_specific_exception(IVirtualMachine::ERROR_UNEXPECTED)
1866     }
1867 
setHostConsoleName(&self, ptsname: &str) -> binder::Result<()>1868     fn setHostConsoleName(&self, ptsname: &str) -> binder::Result<()> {
1869         self.instance.vm_context.global_context.setHostConsoleName(ptsname)
1870     }
1871 
suspend(&self) -> binder::Result<()>1872     fn suspend(&self) -> binder::Result<()> {
1873         self.instance
1874             .suspend()
1875             .with_context(|| format!("Error suspending VM with CID {}", self.instance.cid))
1876             .with_log()
1877             .or_service_specific_exception(-1)
1878     }
1879 
resume(&self) -> binder::Result<()>1880     fn resume(&self) -> binder::Result<()> {
1881         self.instance
1882             .resume()
1883             .with_context(|| format!("Error resuming VM with CID {}", self.instance.cid))
1884             .with_log()
1885             .or_service_specific_exception(-1)
1886     }
1887 }
1888 
1889 impl Drop for VirtualMachine {
drop(&mut self)1890     fn drop(&mut self) {
1891         debug!("Dropping {:?}", self);
1892         if let Err(e) = self.instance.kill() {
1893             debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
1894         }
1895     }
1896 }
1897 
1898 /// A set of Binders to be called back in response to various events on the VM, such as when it
1899 /// dies.
1900 #[derive(Debug, Default)]
1901 pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
1902 
1903 impl VirtualMachineCallbacks {
1904     /// Call all registered callbacks to notify that the payload has started.
notify_payload_started(&self, cid: Cid)1905     pub fn notify_payload_started(&self, cid: Cid) {
1906         let callbacks = &*self.0.lock().unwrap();
1907         for callback in callbacks {
1908             if let Err(e) = callback.onPayloadStarted(cid as i32) {
1909                 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
1910             }
1911         }
1912     }
1913 
1914     /// Call all registered callbacks to notify that the payload is ready to serve.
notify_payload_ready(&self, cid: Cid)1915     pub fn notify_payload_ready(&self, cid: Cid) {
1916         let callbacks = &*self.0.lock().unwrap();
1917         for callback in callbacks {
1918             if let Err(e) = callback.onPayloadReady(cid as i32) {
1919                 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
1920             }
1921         }
1922     }
1923 
1924     /// Call all registered callbacks to notify that the payload has finished.
notify_payload_finished(&self, cid: Cid, exit_code: i32)1925     pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
1926         let callbacks = &*self.0.lock().unwrap();
1927         for callback in callbacks {
1928             if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
1929                 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
1930             }
1931         }
1932     }
1933 
1934     /// Call all registered callbacks to say that the VM encountered an error.
notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str)1935     pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) {
1936         let callbacks = &*self.0.lock().unwrap();
1937         for callback in callbacks {
1938             if let Err(e) = callback.onError(cid as i32, error_code, message) {
1939                 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
1940             }
1941         }
1942     }
1943 
1944     /// Call all registered callbacks to say that the VM has died.
callback_on_died(&self, cid: Cid, reason: DeathReason)1945     pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
1946         let mut callbacks = self.0.lock().unwrap();
1947         for callback in &*callbacks {
1948             if let Err(e) = callback.onDied(cid as i32, reason) {
1949                 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
1950             }
1951         }
1952 
1953         // Nothing to notify afterward because VM cannot be restarted.
1954         // Explicitly clear callbacks to prevent potential cyclic references
1955         // between callback and VmInstance.
1956         (*callbacks).clear();
1957     }
1958 
1959     /// Add a new callback to the set.
add(&self, callback: Strong<dyn IVirtualMachineCallback>)1960     fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
1961         self.0.lock().unwrap().push(callback);
1962     }
1963 }
1964 
1965 /// The mutable state of the VirtualizationService. There should only be one instance of this
1966 /// struct.
1967 #[derive(Debug, Default)]
1968 struct State {
1969     /// The VMs which have been started. When VMs are started a weak reference is added to this
1970     /// list while a strong reference is returned to the caller over Binder. Once all copies of
1971     /// the Binder client are dropped the weak reference here will become invalid, and will be
1972     /// removed from the list opportunistically the next time `add_vm` is called.
1973     vms: Vec<Weak<VmInstance>>,
1974 }
1975 
1976 impl State {
1977     /// Get a list of VMs which still have Binder references to them.
vms(&self) -> Vec<Arc<VmInstance>>1978     fn vms(&self) -> Vec<Arc<VmInstance>> {
1979         // Attempt to upgrade the weak pointers to strong pointers.
1980         self.vms.iter().filter_map(Weak::upgrade).collect()
1981     }
1982 
1983     /// Add a new VM to the list.
add_vm(&mut self, vm: Weak<VmInstance>)1984     fn add_vm(&mut self, vm: Weak<VmInstance>) {
1985         // Garbage collect any entries from the stored list which no longer exist.
1986         self.vms.retain(|vm| vm.strong_count() > 0);
1987 
1988         // Actually add the new VM.
1989         self.vms.push(vm);
1990     }
1991 
1992     /// Get a VM that corresponds to the given cid
get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>>1993     fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
1994         self.vms().into_iter().find(|vm| vm.cid == cid)
1995     }
1996 }
1997 
1998 /// Gets the `VirtualMachineState` of the given `VmInstance`.
get_state(instance: &VmInstance) -> VirtualMachineState1999 fn get_state(instance: &VmInstance) -> VirtualMachineState {
2000     match &*instance.vm_state.lock().unwrap() {
2001         VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
2002         VmState::Running { .. } => match instance.payload_state() {
2003             PayloadState::Starting => VirtualMachineState::STARTING,
2004             PayloadState::Started => VirtualMachineState::STARTED,
2005             PayloadState::Ready => VirtualMachineState::READY,
2006             PayloadState::Finished => VirtualMachineState::FINISHED,
2007             PayloadState::Hangup => VirtualMachineState::DEAD,
2008         },
2009         VmState::Dead => VirtualMachineState::DEAD,
2010         VmState::Failed => VirtualMachineState::DEAD,
2011     }
2012 }
2013 
2014 /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
clone_file(file: &ParcelFileDescriptor) -> binder::Result<File>2015 pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> {
2016     file.as_ref()
2017         .try_clone()
2018         .context("Failed to clone File from ParcelFileDescriptor")
2019         .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
2020         .map(File::from)
2021 }
2022 
2023 /// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>>2024 fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> {
2025     file.as_ref().map(clone_file).transpose()
2026 }
2027 
2028 /// Converts a `VsockStream` to a `ParcelFileDescriptor`.
vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor2029 fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
2030     // SAFETY: ownership is transferred from stream to f
2031     let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
2032     ParcelFileDescriptor::new(f)
2033 }
2034 
2035 /// Parses the platform version requirement string.
parse_platform_version_req(s: &str) -> binder::Result<VersionReq>2036 fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> {
2037     VersionReq::parse(s)
2038         .with_context(|| format!("Invalid platform version requirement {}", s))
2039         .or_binder_exception(ExceptionCode::BAD_PARCELABLE)
2040 }
2041 
2042 /// Create the empty ramdump file
prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File>2043 fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> {
2044     // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where
2045     // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM
2046     // owner) for readout.
2047     let ramdump_path = temporary_directory.join("ramdump");
2048     let ramdump = File::create(ramdump_path)
2049         .context("Failed to prepare ramdump file")
2050         .with_log()
2051         .or_service_specific_exception(-1)?;
2052     Ok(ramdump)
2053 }
2054 
2055 /// Create the empty device tree dump file
prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File>2056 fn prepare_dump_dt_file(temporary_directory: &Path) -> binder::Result<File> {
2057     let path = temporary_directory.join("device_tree.dtb");
2058     let file = File::create(path)
2059         .context("Failed to prepare device tree dump file")
2060         .with_log()
2061         .or_service_specific_exception(-1)?;
2062     Ok(file)
2063 }
2064 
is_protected(config: &VirtualMachineConfig) -> bool2065 fn is_protected(config: &VirtualMachineConfig) -> bool {
2066     match config {
2067         VirtualMachineConfig::RawConfig(config) => config.protectedVm,
2068         VirtualMachineConfig::AppConfig(config) => config.protectedVm,
2069     }
2070 }
2071 
check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()>2072 fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> {
2073     if is_protected(config) {
2074         return Err(anyhow!("Can't use gdb with protected VMs"))
2075             .or_binder_exception(ExceptionCode::SECURITY);
2076     }
2077 
2078     if get_debug_level(config) == Some(DebugLevel::NONE) {
2079         return Err(anyhow!("Can't use gdb with non-debuggable VMs"))
2080             .or_binder_exception(ExceptionCode::SECURITY);
2081     }
2082 
2083     Ok(())
2084 }
2085 
extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64]2086 fn extract_instance_id(config: &VirtualMachineConfig) -> [u8; 64] {
2087     match config {
2088         VirtualMachineConfig::RawConfig(config) => config.instanceId,
2089         VirtualMachineConfig::AppConfig(config) => config.instanceId,
2090     }
2091 }
2092 
extract_want_updatable(config: &VirtualMachineConfig) -> bool2093 fn extract_want_updatable(config: &VirtualMachineConfig) -> bool {
2094     match config {
2095         VirtualMachineConfig::RawConfig(_) => true,
2096         VirtualMachineConfig::AppConfig(config) => {
2097             let Some(custom) = &config.customConfig else { return true };
2098             custom.wantUpdatable
2099         }
2100     }
2101 }
2102 
extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16>2103 fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> {
2104     match config {
2105         VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16),
2106         VirtualMachineConfig::AppConfig(config) => {
2107             NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16)
2108         }
2109     }
2110 }
2111 
check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()>2112 fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> {
2113     let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2114     if let Some(custom_config) = &config.customConfig {
2115         if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() {
2116             return Err(anyhow!("vendor modules feature is disabled"))
2117                 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2118         }
2119     }
2120     Ok(())
2121 }
2122 
check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()>2123 fn check_no_devices(config: &VirtualMachineConfig) -> binder::Result<()> {
2124     let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2125     if let Some(custom_config) = &config.customConfig {
2126         if !custom_config.devices.is_empty() {
2127             return Err(anyhow!("device assignment feature is disabled"))
2128                 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2129         }
2130     }
2131     Ok(())
2132 }
2133 
check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()>2134 fn check_no_extra_apks(config: &VirtualMachineConfig) -> binder::Result<()> {
2135     let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2136     let Payload::PayloadConfig(payload_config) = &config.payload else { return Ok(()) };
2137     if !payload_config.extraApks.is_empty() {
2138         return Err(anyhow!("multi-tenant feature is disabled"))
2139             .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2140     }
2141     Ok(())
2142 }
2143 
check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()>2144 fn check_no_extra_kernel_cmdline_params(config: &VirtualMachineConfig) -> binder::Result<()> {
2145     let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) };
2146     if let Some(custom_config) = &config.customConfig {
2147         if !custom_config.extraKernelCmdlineParams.is_empty() {
2148             return Err(anyhow!("debuggable_vms_improvements feature is disabled"))
2149                 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2150         }
2151     }
2152     Ok(())
2153 }
2154 
check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()>2155 fn check_no_tee_services(config: &VirtualMachineConfig) -> binder::Result<()> {
2156     match config {
2157         VirtualMachineConfig::RawConfig(config) => {
2158             if !config.teeServices.is_empty() {
2159                 return Err(anyhow!("tee_services_allowlist feature is disabled"))
2160                     .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2161             }
2162         }
2163         VirtualMachineConfig::AppConfig(config) => {
2164             if let Some(custom_config) = &config.customConfig {
2165                 if !custom_config.teeServices.is_empty() {
2166                     return Err(anyhow!("tee_services_allowlist feature is disabled"))
2167                         .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
2168                 }
2169             }
2170         }
2171     };
2172     Ok(())
2173 }
2174 
check_protected_vm_is_supported() -> binder::Result<()>2175 fn check_protected_vm_is_supported() -> binder::Result<()> {
2176     let is_pvm_supported =
2177         hypervisor_props::is_protected_vm_supported().or_service_specific_exception(-1)?;
2178     if is_pvm_supported {
2179         Ok(())
2180     } else {
2181         Err(anyhow!("pVM is not supported"))
2182             .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION)
2183     }
2184 }
2185 
check_config_features(config: &VirtualMachineConfig) -> binder::Result<()>2186 fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> {
2187     if !cfg!(vendor_modules) {
2188         check_no_vendor_modules(config)?;
2189     }
2190     if !cfg!(device_assignment) {
2191         check_no_devices(config)?;
2192     }
2193     if !cfg!(multi_tenant) {
2194         check_no_extra_apks(config)?;
2195     }
2196     if !cfg!(debuggable_vms_improvements) {
2197         check_no_extra_kernel_cmdline_params(config)?;
2198     }
2199     if !cfg!(tee_services_allowlist) {
2200         check_no_tee_services(config)?;
2201     }
2202     Ok(())
2203 }
2204 
check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()>2205 fn check_config_allowed_for_early_vms(config: &VirtualMachineConfig) -> binder::Result<()> {
2206     check_no_vendor_modules(config)?;
2207     check_no_devices(config)?;
2208 
2209     Ok(())
2210 }
2211 
clone_or_prepare_logger_fd( fd: Option<&ParcelFileDescriptor>, tag: String, ) -> Result<Option<File>, Status>2212 fn clone_or_prepare_logger_fd(
2213     fd: Option<&ParcelFileDescriptor>,
2214     tag: String,
2215 ) -> Result<Option<File>, Status> {
2216     if let Some(fd) = fd {
2217         return Ok(Some(clone_file(fd)?));
2218     }
2219 
2220     let (read_fd, write_fd) =
2221         pipe().context("Failed to create pipe").or_service_specific_exception(-1)?;
2222 
2223     let mut reader = BufReader::new(File::from(read_fd));
2224     let write_fd = File::from(write_fd);
2225 
2226     let mut buf = vec![];
2227     std::thread::spawn(move || loop {
2228         buf.clear();
2229         buf.shrink_to(1024);
2230         match reader.read_until(b'\n', &mut buf) {
2231             Ok(0) => {
2232                 // EOF
2233                 return;
2234             }
2235             Ok(_size) => {
2236                 if buf.last() == Some(&b'\n') {
2237                     buf.pop();
2238                     // Logs sent via TTY usually end lines with "\r\n".
2239                     if buf.last() == Some(&b'\r') {
2240                         buf.pop();
2241                     }
2242                 }
2243                 info!("{}: {}", &tag, &String::from_utf8_lossy(&buf));
2244             }
2245             Err(e) => {
2246                 error!("Could not read console pipe: {:?}", e);
2247                 return;
2248             }
2249         };
2250     });
2251 
2252     Ok(Some(write_fd))
2253 }
2254 
2255 /// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
2256 /// it doesn't require that T implements Clone.
2257 enum BorrowedOrOwned<'a, T> {
2258     Borrowed(&'a T),
2259     Owned(T),
2260 }
2261 
2262 impl<T> AsRef<T> for BorrowedOrOwned<'_, T> {
as_ref(&self) -> &T2263     fn as_ref(&self) -> &T {
2264         match self {
2265             Self::Borrowed(b) => b,
2266             Self::Owned(o) => o,
2267         }
2268     }
2269 }
2270 
2271 /// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
2272 #[derive(Debug, Default)]
2273 struct VirtualMachineService {
2274     state: Arc<Mutex<State>>,
2275     cid: Cid,
2276 }
2277 
2278 impl Interface for VirtualMachineService {}
2279 
2280 impl IVirtualMachineService for VirtualMachineService {
notifyPayloadStarted(&self) -> binder::Result<()>2281     fn notifyPayloadStarted(&self) -> binder::Result<()> {
2282         let cid = self.cid;
2283         if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
2284             info!("VM with CID {} started payload", cid);
2285             vm.update_payload_state(PayloadState::Started)
2286                 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
2287             vm.callbacks.notify_payload_started(cid);
2288 
2289             let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp;
2290             write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp);
2291             Ok(())
2292         } else {
2293             error!("notifyPayloadStarted is called from an unknown CID {}", cid);
2294             Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
2295         }
2296     }
2297 
notifyPayloadReady(&self) -> binder::Result<()>2298     fn notifyPayloadReady(&self) -> binder::Result<()> {
2299         let cid = self.cid;
2300         if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
2301             info!("VM with CID {} reported payload is ready", cid);
2302             vm.update_payload_state(PayloadState::Ready)
2303                 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
2304             vm.callbacks.notify_payload_ready(cid);
2305             Ok(())
2306         } else {
2307             error!("notifyPayloadReady is called from an unknown CID {}", cid);
2308             Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
2309         }
2310     }
2311 
notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()>2312     fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
2313         let cid = self.cid;
2314         if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
2315             info!("VM with CID {} finished payload", cid);
2316             vm.update_payload_state(PayloadState::Finished)
2317                 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
2318             vm.callbacks.notify_payload_finished(cid, exit_code);
2319             Ok(())
2320         } else {
2321             error!("notifyPayloadFinished is called from an unknown CID {}", cid);
2322             Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
2323         }
2324     }
2325 
notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()>2326     fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> {
2327         let cid = self.cid;
2328         if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
2329             info!("VM with CID {} encountered an error", cid);
2330             vm.update_payload_state(PayloadState::Finished)
2331                 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
2332             vm.callbacks.notify_error(cid, error_code, message);
2333             Ok(())
2334         } else {
2335             error!("notifyError is called from an unknown CID {}", cid);
2336             Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1)
2337         }
2338     }
2339 
getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>>2340     fn getSecretkeeper(&self) -> binder::Result<Strong<dyn ISecretkeeper>> {
2341         if !is_secretkeeper_supported() {
2342             return Err(StatusCode::NAME_NOT_FOUND)?;
2343         }
2344         let sk = binder::wait_for_interface(SECRETKEEPER_IDENTIFIER)?;
2345         Ok(BnSecretkeeper::new_binder(SecretkeeperProxy(sk), BinderFeatures::default()))
2346     }
2347 
requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>>2348     fn requestAttestation(&self, csr: &[u8], test_mode: bool) -> binder::Result<Vec<Certificate>> {
2349         GLOBAL_SERVICE.requestAttestation(csr, get_calling_uid() as i32, test_mode)
2350     }
2351 
claimSecretkeeperEntry(&self, id: &[u8; 64]) -> binder::Result<()>2352     fn claimSecretkeeperEntry(&self, id: &[u8; 64]) -> binder::Result<()> {
2353         GLOBAL_SERVICE.claimSecretkeeperEntry(id)
2354     }
2355 }
2356 
is_secretkeeper_supported() -> bool2357 fn is_secretkeeper_supported() -> bool {
2358     binder::is_declared(SECRETKEEPER_IDENTIFIER)
2359         .expect("Could not check for declared Secretkeeper interface")
2360 }
2361 
is_vm_capabilities_hal_supported() -> bool2362 fn is_vm_capabilities_hal_supported() -> bool {
2363     binder::is_declared(VM_CAPABILITIES_HAL_IDENTIFIER)
2364         .expect("failed to check if {VM_CAPABILITIES_HAL_IDENTIFIER} is present")
2365 }
2366 
2367 impl VirtualMachineService {
new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService>2368     fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
2369         BnVirtualMachineService::new_binder(
2370             VirtualMachineService { state, cid },
2371             BinderFeatures::default(),
2372         )
2373     }
2374 }
2375 
2376 struct SecretkeeperProxy(Strong<dyn ISecretkeeper>);
2377 
2378 impl Interface for SecretkeeperProxy {}
2379 
2380 impl ISecretkeeper for SecretkeeperProxy {
processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>>2381     fn processSecretManagementRequest(&self, req: &[u8]) -> binder::Result<Vec<u8>> {
2382         // Pass the request to the channel, and read the response.
2383         self.0.processSecretManagementRequest(req)
2384     }
2385 
getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>>2386     fn getAuthGraphKe(&self) -> binder::Result<Strong<dyn IAuthGraphKeyExchange>> {
2387         let ag = AuthGraphKeyExchangeProxy(self.0.getAuthGraphKe()?);
2388         Ok(BnAuthGraphKeyExchange::new_binder(ag, BinderFeatures::default()))
2389     }
2390 
deleteIds(&self, ids: &[SecretId]) -> binder::Result<()>2391     fn deleteIds(&self, ids: &[SecretId]) -> binder::Result<()> {
2392         self.0.deleteIds(ids)
2393     }
2394 
deleteAll(&self) -> binder::Result<()>2395     fn deleteAll(&self) -> binder::Result<()> {
2396         self.0.deleteAll()
2397     }
2398 
getSecretkeeperIdentity(&self) -> binder::Result<PublicKey>2399     fn getSecretkeeperIdentity(&self) -> binder::Result<PublicKey> {
2400         // SecretkeeperProxy is really a RPC binder service for PVM (It is called by
2401         // MicrodroidManager). PVMs do not & must not (for security reason) rely on
2402         // getSecretKeeperIdentity, so we throw an exception if someone attempts to
2403         // use this API from the proxy.
2404         Err(ExceptionCode::SECURITY.into())
2405     }
2406 }
2407 
2408 struct AuthGraphKeyExchangeProxy(Strong<dyn IAuthGraphKeyExchange>);
2409 
2410 impl Interface for AuthGraphKeyExchangeProxy {}
2411 
2412 impl IAuthGraphKeyExchange for AuthGraphKeyExchangeProxy {
create(&self) -> binder::Result<SessionInitiationInfo>2413     fn create(&self) -> binder::Result<SessionInitiationInfo> {
2414         self.0.create()
2415     }
2416 
init( &self, peer_pub_key: &PubKey, peer_id: &Identity, peer_nonce: &[u8], peer_version: i32, ) -> binder::Result<KeInitResult>2417     fn init(
2418         &self,
2419         peer_pub_key: &PubKey,
2420         peer_id: &Identity,
2421         peer_nonce: &[u8],
2422         peer_version: i32,
2423     ) -> binder::Result<KeInitResult> {
2424         self.0.init(peer_pub_key, peer_id, peer_nonce, peer_version)
2425     }
2426 
finish( &self, peer_pub_key: &PubKey, peer_id: &Identity, peer_signature: &SessionIdSignature, peer_nonce: &[u8], peer_version: i32, own_key: &Key, ) -> binder::Result<SessionInfo>2427     fn finish(
2428         &self,
2429         peer_pub_key: &PubKey,
2430         peer_id: &Identity,
2431         peer_signature: &SessionIdSignature,
2432         peer_nonce: &[u8],
2433         peer_version: i32,
2434         own_key: &Key,
2435     ) -> binder::Result<SessionInfo> {
2436         self.0.finish(peer_pub_key, peer_id, peer_signature, peer_nonce, peer_version, own_key)
2437     }
2438 
authenticationComplete( &self, peer_signature: &SessionIdSignature, shared_keys: &[AuthgraphArc; 2], ) -> binder::Result<[AuthgraphArc; 2]>2439     fn authenticationComplete(
2440         &self,
2441         peer_signature: &SessionIdSignature,
2442         shared_keys: &[AuthgraphArc; 2],
2443     ) -> binder::Result<[AuthgraphArc; 2]> {
2444         self.0.authenticationComplete(peer_signature, shared_keys)
2445     }
2446 }
2447 
2448 // KEEP IN SYNC WITH early_vms.xsd
2449 #[derive(Clone, Debug, Deserialize, PartialEq)]
2450 struct EarlyVm {
2451     name: String,
2452     cid: i32,
2453     path: String,
2454 }
2455 
2456 #[derive(Debug, Default, Deserialize)]
2457 struct EarlyVms {
2458     early_vm: Vec<EarlyVm>,
2459 }
2460 
2461 impl EarlyVm {
2462     /// Verifies that the provided executable path matches the expected path stored in the XML
2463     /// configuration.
2464     /// If the provided path starts with `/system`, it will be stripped before comparison.
check_exe_paths_match<P: AsRef<Path>>(&self, calling_exe_path: P) -> binder::Result<()>2465     fn check_exe_paths_match<P: AsRef<Path>>(&self, calling_exe_path: P) -> binder::Result<()> {
2466         let actual_path = calling_exe_path.as_ref();
2467         if Path::new(&self.path)
2468             == Path::new("/").join(actual_path.strip_prefix("/system").unwrap_or(actual_path))
2469         {
2470             return Ok(());
2471         }
2472         Err(Status::new_service_specific_error_str(
2473             -1,
2474             Some(format!(
2475                 "Early VM '{}' executable paths do not match. Expected: {}. Found: {:?}.",
2476                 self.name,
2477                 self.path,
2478                 actual_path.display()
2479             )),
2480         ))
2481     }
2482 }
2483 
2484 static EARLY_VMS_CACHE: LazyLock<Mutex<HashMap<CallingPartition, Vec<EarlyVm>>>> =
2485     LazyLock::new(|| Mutex::new(HashMap::new()));
2486 
range_for_partition(partition: CallingPartition) -> Range<Cid>2487 fn range_for_partition(partition: CallingPartition) -> Range<Cid> {
2488     match partition {
2489         CallingPartition::System => 100..200,
2490         CallingPartition::SystemExt | CallingPartition::Product => 200..300,
2491         CallingPartition::Vendor | CallingPartition::Odm => 300..400,
2492         CallingPartition::Unknown => 0..0,
2493     }
2494 }
2495 
get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>>2496 fn get_early_vms_in_path(xml_path: &Path) -> Result<Vec<EarlyVm>> {
2497     if !xml_path.exists() {
2498         bail!("{} doesn't exist", xml_path.display());
2499     }
2500 
2501     let xml =
2502         fs::read(xml_path).with_context(|| format!("Failed to read {}", xml_path.display()))?;
2503     let xml = String::from_utf8(xml)
2504         .with_context(|| format!("{} is not a valid UTF-8 file", xml_path.display()))?;
2505     let early_vms: EarlyVms = serde_xml_rs::from_str(&xml)
2506         .with_context(|| format!("Can't parse {}", xml_path.display()))?;
2507 
2508     Ok(early_vms.early_vm)
2509 }
2510 
validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()>2511 fn validate_cid_range(early_vms: &[EarlyVm], cid_range: &Range<Cid>) -> Result<()> {
2512     for early_vm in early_vms {
2513         let cid = early_vm
2514             .cid
2515             .try_into()
2516             .with_context(|| format!("VM '{}' uses Invalid CID {}", early_vm.name, early_vm.cid))?;
2517 
2518         ensure!(
2519             cid_range.contains(&cid),
2520             "VM '{}' uses CID {cid} which is out of range. Available CIDs: {cid_range:?}",
2521             early_vm.name
2522         );
2523     }
2524     Ok(())
2525 }
2526 
get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>>2527 fn get_early_vms_in_partition(partition: CallingPartition) -> Result<Vec<EarlyVm>> {
2528     let mut cache = EARLY_VMS_CACHE.lock().unwrap();
2529 
2530     if let Some(result) = cache.get(&partition) {
2531         return Ok(result.clone());
2532     }
2533 
2534     let pattern = format!("/{partition}/etc/avf/early_vms*.xml");
2535     let mut early_vms = Vec::new();
2536     for entry in glob::glob(&pattern).with_context(|| format!("Failed to glob {}", &pattern))? {
2537         match entry {
2538             Ok(path) => early_vms.extend(get_early_vms_in_path(&path)?),
2539             Err(e) => error!("Error while globbing (but continuing) {}: {}", &pattern, e),
2540         }
2541     }
2542 
2543     validate_cid_range(&early_vms, &range_for_partition(partition))
2544         .with_context(|| format!("CID validation for {partition} failed"))?;
2545 
2546     cache.insert(partition, early_vms.clone());
2547 
2548     Ok(early_vms)
2549 }
2550 
find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm>2551 fn find_early_vm<'a>(early_vms: &'a [EarlyVm], name: &str) -> Result<&'a EarlyVm> {
2552     let mut found_vm: Option<&EarlyVm> = None;
2553 
2554     for early_vm in early_vms {
2555         if early_vm.name != name {
2556             continue;
2557         }
2558 
2559         if found_vm.is_some() {
2560             bail!("Multiple VMs named '{name}' are found");
2561         }
2562 
2563         found_vm = Some(early_vm);
2564     }
2565 
2566     found_vm.ok_or_else(|| anyhow!("Can't find a VM named '{name}'"))
2567 }
2568 
find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm>2569 fn find_early_vm_for_partition(partition: CallingPartition, name: &str) -> Result<EarlyVm> {
2570     let early_vms = get_early_vms_in_partition(partition)
2571         .with_context(|| format!("Failed to get early VMs from {partition}"))?;
2572 
2573     Ok(find_early_vm(&early_vms, name)
2574         .with_context(|| format!("Failed to find early VM '{name}' in {partition}"))?
2575         .clone())
2576 }
2577 
2578 #[cfg(test)]
2579 mod tests {
2580     use super::*;
2581 
2582     #[test]
test_is_allowed_label_for_partition() -> Result<()>2583     fn test_is_allowed_label_for_partition() -> Result<()> {
2584         let expected_results = vec![
2585             (CallingPartition::System, "u:object_r:system_file:s0", true),
2586             (CallingPartition::System, "u:object_r:apk_data_file:s0", true),
2587             (CallingPartition::System, "u:object_r:app_data_file:s0", false),
2588             (CallingPartition::System, "u:object_r:app_data_file:s0:c512,c768", false),
2589             (CallingPartition::System, "u:object_r:privapp_data_file:s0:c512,c768", false),
2590             (CallingPartition::System, "invalid", false),
2591             (CallingPartition::System, "user:role:apk_data_file:severity:categories", true),
2592             (
2593                 CallingPartition::System,
2594                 "user:role:apk_data_file:severity:categories:extraneous",
2595                 false,
2596             ),
2597             (CallingPartition::System, "u:object_r:vendor_unknowable:s0", false),
2598             (CallingPartition::Vendor, "u:object_r:vendor_unknowable:s0", true),
2599         ];
2600 
2601         for (calling_partition, label, expected_valid) in expected_results {
2602             let context = SeContext::new(label)?;
2603             let result = check_label_is_allowed(&context, calling_partition);
2604             if expected_valid != result.is_ok() {
2605                 bail!(
2606                     "Expected label {label} to be {} for {calling_partition} partition",
2607                     if expected_valid { "allowed" } else { "disallowed" }
2608                 );
2609             }
2610         }
2611         Ok(())
2612     }
2613 
2614     #[test]
test_create_or_update_idsig_file_empty_apk() -> Result<()>2615     fn test_create_or_update_idsig_file_empty_apk() -> Result<()> {
2616         let apk = tempfile::tempfile().unwrap();
2617         let idsig = tempfile::tempfile().unwrap();
2618 
2619         let ret = create_or_update_idsig_file(
2620             &ParcelFileDescriptor::new(apk),
2621             &ParcelFileDescriptor::new(idsig),
2622         );
2623         assert!(ret.is_err(), "should fail");
2624         Ok(())
2625     }
2626 
2627     #[test]
test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()>2628     fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> {
2629         let tmp_dir = tempfile::TempDir::new().unwrap();
2630         let apk = File::open(tmp_dir.path()).unwrap();
2631         let idsig = tempfile::tempfile().unwrap();
2632 
2633         let ret = create_or_update_idsig_file(
2634             &ParcelFileDescriptor::new(apk),
2635             &ParcelFileDescriptor::new(idsig),
2636         );
2637         assert!(ret.is_err(), "should fail");
2638         Ok(())
2639     }
2640 
2641     /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory
2642     /// on ext4 filesystem is passed.
2643     /// On ext4 lseek on a directory fd will return (off_t)-1 (see:
2644     /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in
2645     /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory.
2646     #[test]
test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()>2647     fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> {
2648         // APEXes are backed by the ext4.
2649         let apk = File::open("/apex/com.android.virt/").unwrap();
2650         let idsig = tempfile::tempfile().unwrap();
2651 
2652         let ret = create_or_update_idsig_file(
2653             &ParcelFileDescriptor::new(apk),
2654             &ParcelFileDescriptor::new(idsig),
2655         );
2656         assert!(ret.is_err(), "should fail");
2657         Ok(())
2658     }
2659 
2660     #[test]
test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()>2661     fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> {
2662         use std::io::Seek;
2663 
2664         // Pick any APK
2665         let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2666         let mut idsig = tempfile::tempfile().unwrap();
2667 
2668         create_or_update_idsig_file(
2669             &ParcelFileDescriptor::new(apk.try_clone()?),
2670             &ParcelFileDescriptor::new(idsig.try_clone()?),
2671         )?;
2672         let modified_orig = idsig.metadata()?.modified()?;
2673         apk.rewind()?;
2674         idsig.rewind()?;
2675 
2676         // Call the function again
2677         create_or_update_idsig_file(
2678             &ParcelFileDescriptor::new(apk.try_clone()?),
2679             &ParcelFileDescriptor::new(idsig.try_clone()?),
2680         )?;
2681         let modified_new = idsig.metadata()?.modified()?;
2682         assert!(modified_orig == modified_new, "idsig file was updated unnecessarily");
2683         Ok(())
2684     }
2685 
2686     #[test]
test_create_or_update_idsig_on_non_empty_file() -> Result<()>2687     fn test_create_or_update_idsig_on_non_empty_file() -> Result<()> {
2688         use std::io::Read;
2689 
2690         // Pick any APK
2691         let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap();
2692         let idsig_empty = tempfile::tempfile().unwrap();
2693         let mut idsig_invalid = tempfile::tempfile().unwrap();
2694         idsig_invalid.write_all(b"Oops")?;
2695 
2696         // Create new idsig
2697         create_or_update_idsig_file(
2698             &ParcelFileDescriptor::new(apk.try_clone()?),
2699             &ParcelFileDescriptor::new(idsig_empty.try_clone()?),
2700         )?;
2701         apk.rewind()?;
2702 
2703         // Update idsig_invalid
2704         create_or_update_idsig_file(
2705             &ParcelFileDescriptor::new(apk.try_clone()?),
2706             &ParcelFileDescriptor::new(idsig_invalid.try_clone()?),
2707         )?;
2708 
2709         // Ensure the 2 idsig files have same size!
2710         assert!(
2711             idsig_empty.metadata()?.len() == idsig_invalid.metadata()?.len(),
2712             "idsig files differ in size"
2713         );
2714         // Ensure the 2 idsig files have same content!
2715         for (b1, b2) in idsig_empty.bytes().zip(idsig_invalid.bytes()) {
2716             assert!(b1.unwrap() == b2.unwrap(), "idsig files differ")
2717         }
2718         Ok(())
2719     }
2720     #[test]
test_append_kernel_param_first_param()2721     fn test_append_kernel_param_first_param() {
2722         let mut vm_config = VirtualMachineRawConfig { ..Default::default() };
2723         append_kernel_param("foo=1", &mut vm_config);
2724         assert_eq!(vm_config.params, Some("foo=1".to_owned()))
2725     }
2726 
2727     #[test]
test_append_kernel_param()2728     fn test_append_kernel_param() {
2729         let mut vm_config =
2730             VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() };
2731         append_kernel_param("bar=42", &mut vm_config);
2732         assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned()))
2733     }
2734 
test_extract_os_name_from_config_path( path: &Path, expected_result: Option<&str>, ) -> Result<()>2735     fn test_extract_os_name_from_config_path(
2736         path: &Path,
2737         expected_result: Option<&str>,
2738     ) -> Result<()> {
2739         let result = extract_os_name_from_config_path(path);
2740         if result.as_deref() != expected_result {
2741             bail!("Expected {:?} but was {:?}", expected_result, &result)
2742         }
2743         Ok(())
2744     }
2745 
2746     #[test]
test_extract_os_name_from_microdroid_config() -> Result<()>2747     fn test_extract_os_name_from_microdroid_config() -> Result<()> {
2748         test_extract_os_name_from_config_path(
2749             Path::new("/apex/com.android.virt/etc/microdroid.json"),
2750             Some("microdroid"),
2751         )
2752     }
2753 
2754     #[test]
test_extract_os_name_from_microdroid_16k_config() -> Result<()>2755     fn test_extract_os_name_from_microdroid_16k_config() -> Result<()> {
2756         test_extract_os_name_from_config_path(
2757             Path::new("/apex/com.android.virt/etc/microdroid_16k.json"),
2758             Some("microdroid_16k"),
2759         )
2760     }
2761 
2762     #[test]
test_extract_os_name_from_microdroid_gki_config() -> Result<()>2763     fn test_extract_os_name_from_microdroid_gki_config() -> Result<()> {
2764         test_extract_os_name_from_config_path(
2765             Path::new("/apex/com.android.virt/etc/microdroid_gki-android14-6.1.json"),
2766             Some("microdroid_gki-android14-6.1"),
2767         )
2768     }
2769 
2770     #[test]
test_extract_os_name_from_invalid_path() -> Result<()>2771     fn test_extract_os_name_from_invalid_path() -> Result<()> {
2772         test_extract_os_name_from_config_path(
2773             Path::new("/apex/com.android.virt/etc/microdroid.img"),
2774             None,
2775         )
2776     }
2777 
2778     #[test]
test_extract_os_name_from_configs() -> Result<()>2779     fn test_extract_os_name_from_configs() -> Result<()> {
2780         let tmp_dir = tempfile::TempDir::new()?;
2781         let tmp_dir_path = tmp_dir.path().to_owned();
2782 
2783         let mut os_names: HashSet<String> = HashSet::new();
2784         os_names.insert("microdroid".to_owned());
2785         os_names.insert("microdroid_gki-android14-6.1".to_owned());
2786         os_names.insert("microdroid_gki-android15-6.1".to_owned());
2787 
2788         // config files
2789         for os_name in &os_names {
2790             std::fs::write(tmp_dir_path.join(os_name.to_owned() + ".json"), b"")?;
2791         }
2792 
2793         // fake files not related to configs
2794         std::fs::write(tmp_dir_path.join("microdroid_super.img"), b"")?;
2795         std::fs::write(tmp_dir_path.join("microdroid_foobar.apk"), b"")?;
2796 
2797         let glob_pattern = match tmp_dir_path.join("microdroid*.json").to_str() {
2798             Some(s) => s.to_owned(),
2799             None => bail!("tmp_dir_path {:?} is not UTF-8", tmp_dir_path),
2800         };
2801 
2802         let result = extract_os_names_from_configs(&glob_pattern)?;
2803         if result != os_names {
2804             bail!("Expected {:?} but was {:?}", os_names, result);
2805         }
2806         Ok(())
2807     }
2808 
2809     #[test]
test_find_early_vms_from_xml() -> Result<()>2810     fn test_find_early_vms_from_xml() -> Result<()> {
2811         let tmp_dir = tempfile::TempDir::new()?;
2812         let tmp_dir_path = tmp_dir.path().to_owned();
2813         let xml_path = tmp_dir_path.join("early_vms.xml");
2814 
2815         std::fs::write(
2816             &xml_path,
2817             br#"<?xml version="1.0" encoding="utf-8"?>
2818         <early_vms>
2819             <early_vm>
2820                 <name>vm_demo_native_early</name>
2821                 <cid>123</cid>
2822                 <path>/system/bin/vm_demo_native_early</path>
2823             </early_vm>
2824             <early_vm>
2825                 <name>vm_demo_native_early_2</name>
2826                 <cid>456</cid>
2827                 <path>/system/bin/vm_demo_native_early_2</path>
2828             </early_vm>
2829         </early_vms>
2830         "#,
2831         )?;
2832 
2833         let cid_range = 100..1000;
2834 
2835         let early_vms = get_early_vms_in_path(&xml_path)?;
2836         validate_cid_range(&early_vms, &cid_range)?;
2837 
2838         let test_cases = [
2839             (
2840                 "vm_demo_native_early",
2841                 EarlyVm {
2842                     name: "vm_demo_native_early".to_owned(),
2843                     cid: 123,
2844                     path: "/system/bin/vm_demo_native_early".to_owned(),
2845                 },
2846             ),
2847             (
2848                 "vm_demo_native_early_2",
2849                 EarlyVm {
2850                     name: "vm_demo_native_early_2".to_owned(),
2851                     cid: 456,
2852                     path: "/system/bin/vm_demo_native_early_2".to_owned(),
2853                 },
2854             ),
2855         ];
2856 
2857         for (name, expected) in test_cases {
2858             let result = find_early_vm(&early_vms, name)?;
2859             assert_eq!(result, &expected);
2860         }
2861 
2862         Ok(())
2863     }
2864 
2865     #[test]
test_invalid_cid_validation() -> Result<()>2866     fn test_invalid_cid_validation() -> Result<()> {
2867         let tmp_dir = tempfile::TempDir::new()?;
2868         let xml_path = tmp_dir.path().join("early_vms.xml");
2869 
2870         let cid_range = 100..1000;
2871 
2872         for cid in [-1, 999999] {
2873             std::fs::write(
2874                 &xml_path,
2875                 format!(
2876                     r#"<?xml version="1.0" encoding="utf-8"?>
2877         <early_vms>
2878             <early_vm>
2879                 <name>vm_demo_invalid_cid</name>
2880                 <cid>{cid}</cid>
2881                 <path>/system/bin/vm_demo_invalid_cid</path>
2882             </early_vm>
2883         </early_vms>
2884         "#
2885                 ),
2886             )?;
2887 
2888             let early_vms = get_early_vms_in_path(&xml_path)?;
2889             assert!(validate_cid_range(&early_vms, &cid_range).is_err(), "should fail");
2890         }
2891 
2892         Ok(())
2893     }
2894 
2895     #[test]
test_symlink_to_system_ext_supported() -> Result<()>2896     fn test_symlink_to_system_ext_supported() -> Result<()> {
2897         let link_path = Path::new("/system/system_ext/file");
2898         let partition = find_partition(Some(link_path)).unwrap();
2899         assert_eq!(CallingPartition::SystemExt, partition);
2900         Ok(())
2901     }
2902 
2903     #[test]
test_symlink_to_product_supported() -> Result<()>2904     fn test_symlink_to_product_supported() -> Result<()> {
2905         let link_path = Path::new("/system/product/file");
2906         let partition = find_partition(Some(link_path)).unwrap();
2907         assert_eq!(CallingPartition::Product, partition);
2908         Ok(())
2909     }
2910 
2911     #[test]
test_vendor_in_data()2912     fn test_vendor_in_data() {
2913         assert_eq!(
2914             CallingPartition::Vendor,
2915             find_partition(Some(Path::new("/data/nativetest64/vendor/file"))).unwrap()
2916         );
2917     }
2918 
2919     #[test]
early_vm_exe_paths_match_succeeds_with_same_paths()2920     fn early_vm_exe_paths_match_succeeds_with_same_paths() {
2921         let early_vm = EarlyVm {
2922             name: "vm_demo_native_early".to_owned(),
2923             cid: 123,
2924             path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2925         };
2926         let calling_exe_path = "/system_ext/bin/vm_demo_native_early";
2927         assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2928     }
2929 
2930     #[test]
early_vm_exe_paths_match_succeeds_with_calling_exe_path_from_system()2931     fn early_vm_exe_paths_match_succeeds_with_calling_exe_path_from_system() {
2932         let early_vm = EarlyVm {
2933             name: "vm_demo_native_early".to_owned(),
2934             cid: 123,
2935             path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2936         };
2937         let calling_exe_path = "/system/system_ext/bin/vm_demo_native_early";
2938         assert!(early_vm.check_exe_paths_match(calling_exe_path).is_ok())
2939     }
2940 
2941     #[test]
early_vm_exe_paths_match_fails_with_unmatched_paths()2942     fn early_vm_exe_paths_match_fails_with_unmatched_paths() {
2943         let early_vm = EarlyVm {
2944             name: "vm_demo_native_early".to_owned(),
2945             cid: 123,
2946             path: "/system_ext/bin/vm_demo_native_early".to_owned(),
2947         };
2948         let calling_exe_path = "/system/etc/system_ext/bin/vm_demo_native_early";
2949         assert!(early_vm.check_exe_paths_match(calling_exe_path).is_err())
2950     }
2951 
2952     #[test]
test_duplicated_early_vms() -> Result<()>2953     fn test_duplicated_early_vms() -> Result<()> {
2954         let tmp_dir = tempfile::TempDir::new()?;
2955         let tmp_dir_path = tmp_dir.path().to_owned();
2956         let xml_path = tmp_dir_path.join("early_vms.xml");
2957 
2958         std::fs::write(
2959             &xml_path,
2960             br#"<?xml version="1.0" encoding="utf-8"?>
2961         <early_vms>
2962             <early_vm>
2963                 <name>vm_demo_duplicated_name</name>
2964                 <cid>456</cid>
2965                 <path>/system/bin/vm_demo_duplicated_name_1</path>
2966             </early_vm>
2967             <early_vm>
2968                 <name>vm_demo_duplicated_name</name>
2969                 <cid>789</cid>
2970                 <path>/system/bin/vm_demo_duplicated_name_2</path>
2971             </early_vm>
2972         </early_vms>
2973         "#,
2974         )?;
2975 
2976         let cid_range = 100..1000;
2977 
2978         let early_vms = get_early_vms_in_path(&xml_path)?;
2979         validate_cid_range(&early_vms, &cid_range)?;
2980 
2981         assert!(find_early_vm(&early_vms, "vm_demo_duplicated_name").is_err(), "should fail");
2982 
2983         Ok(())
2984     }
2985 }
2986