Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 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 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 15 | //! Implementation of the AIDL interface of the VirtualizationService. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 16 | |
David Brazdil | 1f53070 | 2022-10-03 12:18:10 +0100 | [diff] [blame] | 17 | use crate::{get_calling_pid, get_calling_uid}; |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 18 | use crate::atom::{ |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 19 | write_vm_booted_stats, write_vm_creation_stats}; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 20 | use crate::composite::make_composite_image; |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 21 | use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VfioDevice, VmContext, VmInstance, VmState}; |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 22 | use crate::debug_config::DebugConfig; |
Nikita Ioffe | 5dfddf2 | 2023-06-29 16:11:26 +0100 | [diff] [blame] | 23 | use crate::payload::{add_microdroid_payload_images, add_microdroid_system_images, add_microdroid_vendor_image}; |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 24 | use crate::selinux::{getfilecon, SeContext}; |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 25 | use android_os_permissions_aidl::aidl::android::os::IPermissionController; |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 26 | use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{ |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 27 | Certificate::Certificate, |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 28 | DeathReason::DeathReason, |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 29 | ErrorCode::ErrorCode, |
| 30 | }; |
| 31 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 32 | AssignableDevice::AssignableDevice, |
David Brazdil | 7d1e5ec | 2023-02-06 17:56:29 +0000 | [diff] [blame] | 33 | CpuTopology::CpuTopology, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 34 | DiskImage::DiskImage, |
Alan Stokes | 0cc59ee | 2021-09-24 11:20:34 +0100 | [diff] [blame] | 35 | IVirtualMachine::{BnVirtualMachine, IVirtualMachine}, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 36 | IVirtualMachineCallback::IVirtualMachineCallback, |
| 37 | IVirtualizationService::IVirtualizationService, |
Alan Stokes | 27f3ef0 | 2023-09-29 15:09:35 +0100 | [diff] [blame] | 38 | IVirtualizationService::FEATURE_MULTI_TENANT, |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 39 | IVirtualizationService::FEATURE_VENDOR_MODULES, |
Alan Stokes | 7f27c0d | 2023-09-07 16:22:58 +0100 | [diff] [blame] | 40 | IVirtualizationService::FEATURE_DICE_CHANGES, |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame] | 41 | MemoryTrimLevel::MemoryTrimLevel, |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 42 | Partition::Partition, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 43 | PartitionType::PartitionType, |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 44 | VirtualMachineAppConfig::{DebugLevel::DebugLevel, Payload::Payload, VirtualMachineAppConfig}, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 45 | VirtualMachineConfig::VirtualMachineConfig, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 46 | VirtualMachineDebugInfo::VirtualMachineDebugInfo, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 47 | VirtualMachinePayloadConfig::VirtualMachinePayloadConfig, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 48 | VirtualMachineRawConfig::VirtualMachineRawConfig, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 49 | VirtualMachineState::VirtualMachineState, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 50 | }; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 51 | use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVirtualizationServiceInternal::IVirtualizationServiceInternal; |
Seungjae Yoo | dd91f0f | 2022-11-09 15:25:21 +0900 | [diff] [blame] | 52 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{ |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 53 | BnVirtualMachineService, IVirtualMachineService, |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 54 | }; |
Alan Stokes | 25f6936 | 2023-03-06 16:51:54 +0000 | [diff] [blame] | 55 | use anyhow::{anyhow, bail, Context, Result}; |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 56 | use apkverify::{HashAlgorithm, V4Signature}; |
Jiyong Park | d7bd2f2 | 2023-08-10 20:41:19 +0900 | [diff] [blame] | 57 | use avflog::LogResult; |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 58 | use binder::{ |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 59 | self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, |
| 60 | Status, StatusCode, Strong, |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 61 | IntoBinderResult, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 62 | }; |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 63 | use disk::QcowFile; |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 64 | use lazy_static::lazy_static; |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 65 | use log::{debug, error, info, warn}; |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 66 | use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig}; |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 67 | use nix::unistd::pipe; |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 68 | use rpcbinder::RpcServer; |
Alan Stokes | 25f6936 | 2023-03-06 16:51:54 +0000 | [diff] [blame] | 69 | use rustutils::system_properties; |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 70 | use semver::VersionReq; |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 71 | use std::collections::HashSet; |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 72 | use std::convert::TryInto; |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 73 | use std::ffi::CStr; |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 74 | use std::fs::{canonicalize, read_dir, remove_file, File, OpenOptions}; |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 75 | use std::io::{BufRead, BufReader, Error, ErrorKind, Write}; |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 76 | use std::num::{NonZeroU16, NonZeroU32}; |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 77 | use std::os::unix::io::{FromRawFd, IntoRawFd}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 78 | use std::os::unix::raw::pid_t; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 79 | use std::path::{Path, PathBuf}; |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 80 | use std::sync::{Arc, Mutex, Weak}; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 81 | use vmconfig::VmConfig; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 82 | use vsock::VsockStream; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 83 | use zip::ZipArchive; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 84 | |
David Brazdil | 41d1a87 | 2022-10-05 14:44:19 +0100 | [diff] [blame] | 85 | /// The unique ID of a VM used (together with a port number) for vsock communication. |
| 86 | pub type Cid = u32; |
| 87 | |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 88 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice"; |
| 89 | |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 90 | /// The size of zero.img. |
| 91 | /// Gaps in composite disk images are filled with a shared zero.img. |
| 92 | const ZERO_FILLER_SIZE: u64 = 4096; |
| 93 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 94 | /// Magic string for the instance image |
| 95 | const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance"; |
| 96 | |
| 97 | /// Version of the instance image format |
| 98 | const ANDROID_VM_INSTANCE_VERSION: u16 = 1; |
| 99 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 100 | const MICRODROID_OS_NAME: &str = "microdroid"; |
| 101 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 102 | const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE"; |
| 103 | |
| 104 | /// crosvm requires all partitions to be a multiple of 4KiB. |
| 105 | const PARTITION_GRANULARITY_BYTES: u64 = 4096; |
| 106 | |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 107 | lazy_static! { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 108 | pub static ref GLOBAL_SERVICE: Strong<dyn IVirtualizationServiceInternal> = |
| 109 | wait_for_interface(BINDER_SERVICE_IDENTIFIER) |
| 110 | .expect("Could not connect to VirtualizationServiceInternal"); |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 111 | } |
| 112 | |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 113 | fn create_or_update_idsig_file( |
| 114 | input_fd: &ParcelFileDescriptor, |
| 115 | idsig_fd: &ParcelFileDescriptor, |
| 116 | ) -> Result<()> { |
| 117 | let mut input = clone_file(input_fd)?; |
| 118 | let metadata = input.metadata().context("failed to get input metadata")?; |
| 119 | if !metadata.is_file() { |
| 120 | bail!("input is not a regular file"); |
| 121 | } |
Alan Stokes | 25f6936 | 2023-03-06 16:51:54 +0000 | [diff] [blame] | 122 | let mut sig = |
| 123 | V4Signature::create(&mut input, get_current_sdk()?, 4096, &[], HashAlgorithm::SHA256) |
| 124 | .context("failed to create idsig")?; |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 125 | |
| 126 | let mut output = clone_file(idsig_fd)?; |
Jiyong Park | 8d19295 | 2023-06-26 14:29:51 +0900 | [diff] [blame] | 127 | |
| 128 | // Optimization. We don't have to update idsig file whenever a VM is started. Don't update it, |
| 129 | // if the idsig file already has the same APK digest. |
| 130 | if output.metadata()?.len() > 0 { |
| 131 | if let Ok(out_sig) = V4Signature::from_idsig(&mut output) { |
| 132 | if out_sig.signing_info.apk_digest == sig.signing_info.apk_digest { |
| 133 | debug!("idsig {:?} is up-to-date with apk {:?}.", output, input); |
| 134 | return Ok(()); |
| 135 | } |
| 136 | } |
| 137 | // if we fail to read v4signature from output, that's fine. User can pass a random file. |
| 138 | // We will anyway overwrite the file to the v4signature generated from input_fd. |
| 139 | } |
| 140 | |
Nikita Ioffe | c09b049 | 2022-12-14 20:18:33 +0000 | [diff] [blame] | 141 | output.set_len(0).context("failed to set_len on the idsig output")?; |
| 142 | sig.write_into(&mut output).context("failed to write idsig")?; |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 143 | Ok(()) |
| 144 | } |
| 145 | |
Alan Stokes | 25f6936 | 2023-03-06 16:51:54 +0000 | [diff] [blame] | 146 | fn get_current_sdk() -> Result<u32> { |
| 147 | let current_sdk = system_properties::read("ro.build.version.sdk")?; |
| 148 | let current_sdk = current_sdk.ok_or_else(|| anyhow!("SDK version missing"))?; |
| 149 | current_sdk.parse().context("Malformed SDK version") |
| 150 | } |
| 151 | |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 152 | pub fn remove_temporary_files(path: &PathBuf) -> Result<()> { |
| 153 | for dir_entry in read_dir(path)? { |
| 154 | remove_file(dir_entry?.path())?; |
| 155 | } |
| 156 | Ok(()) |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 157 | } |
| 158 | |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 159 | /// Implementation of `IVirtualizationService`, the entry point of the AIDL service. |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 160 | #[derive(Debug, Default)] |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 161 | pub struct VirtualizationService { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 162 | state: Arc<Mutex<State>>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 163 | } |
| 164 | |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 165 | impl Interface for VirtualizationService { |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame^] | 166 | fn dump(&self, writer: &mut dyn Write, _args: &[&CStr]) -> Result<(), StatusCode> { |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 167 | check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?; |
| 168 | let state = &mut *self.state.lock().unwrap(); |
| 169 | let vms = state.vms(); |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame^] | 170 | writeln!(writer, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?; |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 171 | for vm in vms { |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame^] | 172 | writeln!(writer, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 173 | writeln!(writer, "\tState: {:?}", vm.vm_state.lock().unwrap()) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 174 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame^] | 175 | writeln!(writer, "\tPayload state {:?}", vm.payload_state()) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 176 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame^] | 177 | writeln!(writer, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 178 | writeln!(writer, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy()) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 179 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame^] | 180 | writeln!(writer, "\trequester_uid: {}", vm.requester_uid) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 181 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
Andrei Homescu | 0cf8e22 | 2023-11-09 04:27:55 +0000 | [diff] [blame^] | 182 | writeln!(writer, "\trequester_debug_pid: {}", vm.requester_debug_pid) |
Shikha Panwar | d8e3542 | 2021-10-11 13:51:27 +0000 | [diff] [blame] | 183 | .or(Err(StatusCode::UNKNOWN_ERROR))?; |
| 184 | } |
| 185 | Ok(()) |
| 186 | } |
| 187 | } |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 188 | impl IVirtualizationService for VirtualizationService { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 189 | /// Creates (but does not start) a new VM with the given configuration, assigning it the next |
| 190 | /// available CID. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 191 | /// |
| 192 | /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client. |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 193 | fn createVm( |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 194 | &self, |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 195 | config: &VirtualMachineConfig, |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 196 | console_out_fd: Option<&ParcelFileDescriptor>, |
| 197 | console_in_fd: Option<&ParcelFileDescriptor>, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 198 | log_fd: Option<&ParcelFileDescriptor>, |
| 199 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 200 | let mut is_protected = false; |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 201 | let ret = self.create_vm_internal( |
| 202 | config, |
| 203 | console_out_fd, |
| 204 | console_in_fd, |
| 205 | log_fd, |
| 206 | &mut is_protected, |
| 207 | ); |
Seungjae Yoo | 0a8c84c | 2022-07-11 08:19:15 +0000 | [diff] [blame] | 208 | write_vm_creation_stats(config, is_protected, &ret); |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 209 | ret |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 210 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 211 | |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 212 | /// Initialise an empty partition image of the given size to be used as a writable partition. |
| 213 | fn initializeWritablePartition( |
| 214 | &self, |
| 215 | image_fd: &ParcelFileDescriptor, |
Alan Stokes | ff0005f | 2023-01-30 09:53:00 +0000 | [diff] [blame] | 216 | size_bytes: i64, |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 217 | partition_type: PartitionType, |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 218 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 219 | check_manage_access()?; |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 220 | let size_bytes = size_bytes |
| 221 | .try_into() |
| 222 | .with_context(|| format!("Invalid size: {}", size_bytes)) |
| 223 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?; |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 224 | let size_bytes = round_up(size_bytes, PARTITION_GRANULARITY_BYTES); |
| 225 | let image = clone_file(image_fd)?; |
| 226 | // initialize the file. Any data in the file will be erased. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 227 | image.set_len(0).context("Failed to reset a file").or_service_specific_exception(-1)?; |
| 228 | let mut part = QcowFile::new(image, size_bytes) |
| 229 | .context("Failed to create QCOW2 image") |
| 230 | .or_service_specific_exception(-1)?; |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 231 | |
| 232 | match partition_type { |
| 233 | PartitionType::RAW => Ok(()), |
| 234 | PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part), |
| 235 | PartitionType::ENCRYPTEDSTORE => format_as_encryptedstore(&mut part), |
| 236 | _ => Err(Error::new( |
| 237 | ErrorKind::Unsupported, |
| 238 | format!("Unsupported partition type {:?}", partition_type), |
| 239 | )), |
| 240 | } |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 241 | .with_context(|| format!("Failed to initialize partition as {:?}", partition_type)) |
| 242 | .or_service_specific_exception(-1)?; |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 243 | |
| 244 | Ok(()) |
Andrew Walbran | dff3b94 | 2021-06-09 15:20:36 +0000 | [diff] [blame] | 245 | } |
| 246 | |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 247 | /// Creates or update the idsig file by digesting the input APK file. |
| 248 | fn createOrUpdateIdsigFile( |
| 249 | &self, |
| 250 | input_fd: &ParcelFileDescriptor, |
| 251 | idsig_fd: &ParcelFileDescriptor, |
| 252 | ) -> binder::Result<()> { |
Jiyong Park | c3ca24f | 2022-06-28 10:45:15 +0900 | [diff] [blame] | 253 | check_manage_access()?; |
| 254 | |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 255 | create_or_update_idsig_file(input_fd, idsig_fd).or_service_specific_exception(-1)?; |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 256 | Ok(()) |
| 257 | } |
| 258 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 259 | /// Get a list of all currently running VMs. This method is only intended for debug purposes, |
| 260 | /// and as such is only permitted from the shell user. |
| 261 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
David Brazdil | 209074a | 2023-01-12 16:44:51 +0000 | [diff] [blame] | 262 | // Delegate to the global service, including checking the debug permission. |
David Brazdil | d4f51a5 | 2023-01-11 14:09:27 +0000 | [diff] [blame] | 263 | GLOBAL_SERVICE.debugListVms() |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 264 | } |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 265 | |
| 266 | /// Get a list of assignable device types. |
| 267 | fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> { |
| 268 | // Delegate to the global service, including checking the permission. |
| 269 | GLOBAL_SERVICE.getAssignableDevices() |
| 270 | } |
Nikita Ioffe | f7c742a | 2023-09-04 16:57:59 +0100 | [diff] [blame] | 271 | |
| 272 | /// Returns whether given feature is enabled |
| 273 | fn isFeatureEnabled(&self, feature: &str) -> binder::Result<bool> { |
| 274 | check_manage_access()?; |
| 275 | |
| 276 | // This approach is quite cumbersome, but will do the work for the short term. |
| 277 | // TODO(b/298012279): make this scalable. |
| 278 | match feature { |
Alan Stokes | 7f27c0d | 2023-09-07 16:22:58 +0100 | [diff] [blame] | 279 | FEATURE_DICE_CHANGES => Ok(cfg!(dice_changes)), |
Alan Stokes | 27f3ef0 | 2023-09-29 15:09:35 +0100 | [diff] [blame] | 280 | FEATURE_MULTI_TENANT => Ok(cfg!(multi_tenant)), |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 281 | FEATURE_VENDOR_MODULES => Ok(cfg!(vendor_modules)), |
Nikita Ioffe | f7c742a | 2023-09-04 16:57:59 +0100 | [diff] [blame] | 282 | _ => { |
Alan Stokes | 7f27c0d | 2023-09-07 16:22:58 +0100 | [diff] [blame] | 283 | warn!("unknown feature {feature}"); |
Nikita Ioffe | f7c742a | 2023-09-04 16:57:59 +0100 | [diff] [blame] | 284 | Ok(false) |
| 285 | } |
| 286 | } |
| 287 | } |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 288 | } |
| 289 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 290 | impl VirtualizationService { |
| 291 | pub fn init() -> VirtualizationService { |
David Brazdil | 49f96f5 | 2022-12-16 21:29:13 +0000 | [diff] [blame] | 292 | VirtualizationService::default() |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 293 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 294 | |
David Brazdil | 209074a | 2023-01-12 16:44:51 +0000 | [diff] [blame] | 295 | fn create_vm_context( |
| 296 | &self, |
| 297 | requester_debug_pid: pid_t, |
| 298 | ) -> binder::Result<(VmContext, Cid, PathBuf)> { |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 299 | const NUM_ATTEMPTS: usize = 5; |
| 300 | |
| 301 | for _ in 0..NUM_ATTEMPTS { |
Charisee | 96113f3 | 2023-01-26 09:00:42 +0000 | [diff] [blame] | 302 | let vm_context = GLOBAL_SERVICE.allocateGlobalVmContext(requester_debug_pid)?; |
David Brazdil | d4f51a5 | 2023-01-11 14:09:27 +0000 | [diff] [blame] | 303 | let cid = vm_context.getCid()? as Cid; |
| 304 | let temp_dir: PathBuf = vm_context.getTemporaryDirectory()?.into(); |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 305 | let service = VirtualMachineService::new_binder(self.state.clone(), cid).as_binder(); |
| 306 | |
| 307 | // Start VM service listening for connections from the new CID on port=CID. |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 308 | let port = cid; |
David Brazdil | 3238da4 | 2022-11-18 10:04:51 +0000 | [diff] [blame] | 309 | match RpcServer::new_vsock(service, cid, port) { |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 310 | Ok(vm_server) => { |
| 311 | vm_server.start(); |
David Brazdil | d4f51a5 | 2023-01-11 14:09:27 +0000 | [diff] [blame] | 312 | return Ok((VmContext::new(vm_context, vm_server), cid, temp_dir)); |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 313 | } |
| 314 | Err(err) => { |
| 315 | warn!("Could not start RpcServer on port {}: {}", port, err); |
| 316 | } |
| 317 | } |
| 318 | } |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 319 | Err(anyhow!("Too many attempts to create VM context failed")) |
| 320 | .or_service_specific_exception(-1) |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 321 | } |
| 322 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 323 | fn create_vm_internal( |
| 324 | &self, |
| 325 | config: &VirtualMachineConfig, |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 326 | console_out_fd: Option<&ParcelFileDescriptor>, |
| 327 | console_in_fd: Option<&ParcelFileDescriptor>, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 328 | log_fd: Option<&ParcelFileDescriptor>, |
| 329 | is_protected: &mut bool, |
| 330 | ) -> binder::Result<Strong<dyn IVirtualMachine>> { |
David Brazdil | 209074a | 2023-01-12 16:44:51 +0000 | [diff] [blame] | 331 | let requester_uid = get_calling_uid(); |
| 332 | let requester_debug_pid = get_calling_pid(); |
| 333 | |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 334 | check_config_features(config)?; |
| 335 | |
David Brazdil | 209074a | 2023-01-12 16:44:51 +0000 | [diff] [blame] | 336 | // Allocating VM context checks the MANAGE_VIRTUAL_MACHINE permission. |
| 337 | let (vm_context, cid, temporary_directory) = self.create_vm_context(requester_debug_pid)?; |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 338 | |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 339 | let is_custom = match config { |
| 340 | VirtualMachineConfig::RawConfig(_) => true, |
| 341 | VirtualMachineConfig::AppConfig(config) => { |
| 342 | // Some features are reserved for platform apps only, even when using |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 343 | // VirtualMachineAppConfig. Almost all of these features are grouped in the |
| 344 | // CustomConfig struct: |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 345 | // - controlling CPUs; |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 346 | // - specifying a config file in the APK; (this one is not part of CustomConfig) |
Nikita Ioffe | 26c35ed | 2023-06-05 17:49:08 +0100 | [diff] [blame] | 347 | // - gdbPort is set, meaning that crosvm will start a gdb server; |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 348 | // - using anything other than the default kernel; |
| 349 | // - specifying devices to be assigned. |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 350 | config.customConfig.is_some() || matches!(config.payload, Payload::ConfigPath(_)) |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 351 | } |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 352 | }; |
| 353 | if is_custom { |
| 354 | check_use_custom_virtual_machine()?; |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 355 | } |
| 356 | |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 357 | let gdb_port = extract_gdb_port(config); |
| 358 | |
| 359 | // Additional permission checks if caller request gdb. |
| 360 | if gdb_port.is_some() { |
| 361 | check_gdb_allowed(config)?; |
| 362 | } |
| 363 | |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 364 | let debug_level = match config { |
| 365 | VirtualMachineConfig::AppConfig(config) => config.debugLevel, |
| 366 | _ => DebugLevel::NONE, |
| 367 | }; |
| 368 | let debug_config = DebugConfig::new(debug_level); |
| 369 | |
| 370 | let ramdump = if debug_config.is_ramdump_needed() { |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 371 | Some(prepare_ramdump_file(&temporary_directory)?) |
| 372 | } else { |
| 373 | None |
| 374 | }; |
| 375 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 376 | let state = &mut *self.state.lock().unwrap(); |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 377 | let console_out_fd = |
| 378 | clone_or_prepare_logger_fd(&debug_config, console_out_fd, format!("Console({})", cid))?; |
| 379 | let console_in_fd = console_in_fd.map(clone_file).transpose()?; |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 380 | let log_fd = clone_or_prepare_logger_fd(&debug_config, log_fd, format!("Log({})", cid))?; |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 381 | |
| 382 | // Counter to generate unique IDs for temporary image files. |
| 383 | let mut next_temporary_image_id = 0; |
| 384 | // Files which are referred to from composite images. These must be mapped to the crosvm |
| 385 | // child process, and not closed before it is started. |
| 386 | let mut indirect_files = vec![]; |
| 387 | |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 388 | let (is_app_config, config) = match config { |
| 389 | VirtualMachineConfig::RawConfig(config) => (false, BorrowedOrOwned::Borrowed(config)), |
| 390 | VirtualMachineConfig::AppConfig(config) => { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 391 | let config = load_app_config(config, &debug_config, &temporary_directory) |
| 392 | .or_service_specific_exception_with(-1, |e| { |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 393 | *is_protected = config.protectedVm; |
| 394 | let message = format!("Failed to load app config: {:?}", e); |
| 395 | error!("{}", message); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 396 | message |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 397 | })?; |
Alan Stokes | 7bc146c | 2022-10-20 17:10:32 +0100 | [diff] [blame] | 398 | (true, BorrowedOrOwned::Owned(config)) |
| 399 | } |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 400 | }; |
| 401 | let config = config.as_ref(); |
| 402 | *is_protected = config.protectedVm; |
| 403 | |
| 404 | // Check if partition images are labeled incorrectly. This is to prevent random images |
| 405 | // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from |
Alan Stokes | 3e5eec1 | 2023-09-07 12:10:00 +0100 | [diff] [blame] | 406 | // being loaded in a pVM. This applies to everything but the instance image in the raw |
| 407 | // config, and everything but the non-executable, generated partitions in the app |
| 408 | // config. |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 409 | config |
| 410 | .disks |
| 411 | .iter() |
| 412 | .flat_map(|disk| disk.partitions.iter()) |
| 413 | .filter(|partition| { |
| 414 | if is_app_config { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 415 | !is_safe_app_partition(&partition.label) |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 416 | } else { |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 417 | !is_safe_raw_partition(&partition.label) |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 418 | } |
| 419 | }) |
| 420 | .try_for_each(check_label_for_partition) |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 421 | .or_service_specific_exception(-1)?; |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 422 | |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 423 | let kernel = maybe_clone_file(&config.kernel)?; |
| 424 | let initrd = maybe_clone_file(&config.initrd)?; |
| 425 | |
| 426 | // In a protected VM, we require custom kernels to come from a trusted source (b/237054515). |
| 427 | if config.protectedVm { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 428 | check_label_for_kernel_files(&kernel, &initrd).or_service_specific_exception(-1)?; |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 429 | } |
| 430 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 431 | let zero_filler_path = temporary_directory.join("zero.img"); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 432 | write_zero_filler(&zero_filler_path) |
| 433 | .context("Failed to make composite image") |
| 434 | .with_log() |
| 435 | .or_service_specific_exception(-1)?; |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 436 | |
| 437 | // Assemble disk images if needed. |
| 438 | let disks = config |
| 439 | .disks |
| 440 | .iter() |
| 441 | .map(|disk| { |
| 442 | assemble_disk_image( |
| 443 | disk, |
| 444 | &zero_filler_path, |
| 445 | &temporary_directory, |
| 446 | &mut next_temporary_image_id, |
| 447 | &mut indirect_files, |
| 448 | ) |
| 449 | }) |
| 450 | .collect::<Result<Vec<DiskFile>, _>>()?; |
| 451 | |
David Brazdil | 7d1e5ec | 2023-02-06 17:56:29 +0000 | [diff] [blame] | 452 | let (cpus, host_cpu_topology) = match config.cpuTopology { |
| 453 | CpuTopology::MATCH_HOST => (None, true), |
| 454 | CpuTopology::ONE_CPU => (NonZeroU32::new(1), false), |
| 455 | val => { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 456 | return Err(anyhow!("Failed to parse CPU topology value {:?}", val)) |
| 457 | .with_log() |
| 458 | .or_service_specific_exception(-1); |
David Brazdil | 7d1e5ec | 2023-02-06 17:56:29 +0000 | [diff] [blame] | 459 | } |
| 460 | }; |
| 461 | |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 462 | let vfio_devices = if !config.devices.is_empty() { |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 463 | let mut set = HashSet::new(); |
| 464 | for device in config.devices.iter() { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 465 | let path = canonicalize(device) |
| 466 | .with_context(|| format!("can't canonicalize {device}")) |
| 467 | .or_service_specific_exception(-1)?; |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 468 | if !set.insert(path) { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 469 | return Err(anyhow!("duplicated device {device}")) |
| 470 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 471 | } |
| 472 | } |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 473 | GLOBAL_SERVICE |
| 474 | .bindDevicesToVfioDriver(&config.devices)? |
| 475 | .into_iter() |
| 476 | .map(|x| VfioDevice { |
| 477 | sysfs_path: PathBuf::from(&x.sysfsPath), |
Jaewan Kim | 35e818d | 2023-10-18 05:36:38 +0000 | [diff] [blame] | 478 | dtbo_label: x.dtboLabel, |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 479 | }) |
| 480 | .collect::<Vec<_>>() |
| 481 | } else { |
| 482 | vec![] |
| 483 | }; |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 484 | |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 485 | // Actually start the VM. |
| 486 | let crosvm_config = CrosvmConfig { |
| 487 | cid, |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 488 | name: config.name.clone(), |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 489 | bootloader: maybe_clone_file(&config.bootloader)?, |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 490 | kernel, |
| 491 | initrd, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 492 | disks, |
| 493 | params: config.params.to_owned(), |
| 494 | protected: *is_protected, |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 495 | debug_config, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 496 | memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new), |
David Brazdil | 7d1e5ec | 2023-02-06 17:56:29 +0000 | [diff] [blame] | 497 | cpus, |
| 498 | host_cpu_topology, |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 499 | task_profiles: config.taskProfiles.clone(), |
Jiyong Park | e6fb167 | 2023-06-26 16:45:55 +0900 | [diff] [blame] | 500 | console_out_fd, |
| 501 | console_in_fd, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 502 | log_fd, |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 503 | ramdump, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 504 | indirect_files, |
| 505 | platform_version: parse_platform_version_req(&config.platformVersion)?, |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 506 | detect_hangup: is_app_config, |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 507 | gdb_port, |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 508 | vfio_devices, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 509 | }; |
| 510 | let instance = Arc::new( |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 511 | VmInstance::new( |
| 512 | crosvm_config, |
| 513 | temporary_directory, |
| 514 | requester_uid, |
| 515 | requester_debug_pid, |
| 516 | vm_context, |
| 517 | ) |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 518 | .with_context(|| format!("Failed to create VM with config {:?}", config)) |
| 519 | .with_log() |
| 520 | .or_service_specific_exception(-1)?, |
Shikha Panwar | 061aa2c | 2022-04-05 12:52:56 +0000 | [diff] [blame] | 521 | ); |
| 522 | state.add_vm(Arc::downgrade(&instance)); |
| 523 | Ok(VirtualMachine::create(instance)) |
| 524 | } |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 525 | } |
| 526 | |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 527 | fn write_zero_filler(zero_filler_path: &Path) -> Result<()> { |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 528 | let file = OpenOptions::new() |
| 529 | .create_new(true) |
| 530 | .read(true) |
| 531 | .write(true) |
| 532 | .open(zero_filler_path) |
| 533 | .with_context(|| "Failed to create zero.img")?; |
| 534 | file.set_len(ZERO_FILLER_SIZE)?; |
Andrew Walbran | fbb39d2 | 2021-07-28 17:01:25 +0000 | [diff] [blame] | 535 | Ok(()) |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 536 | } |
| 537 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 538 | fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> { |
| 539 | part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?; |
| 540 | part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?; |
| 541 | part.flush() |
| 542 | } |
| 543 | |
| 544 | fn format_as_encryptedstore(part: &mut dyn Write) -> std::io::Result<()> { |
| 545 | part.write_all(UNFORMATTED_STORAGE_MAGIC.as_bytes())?; |
| 546 | part.flush() |
| 547 | } |
| 548 | |
| 549 | fn round_up(input: u64, granularity: u64) -> u64 { |
| 550 | if granularity == 0 { |
| 551 | return input; |
| 552 | } |
| 553 | // If the input is absurdly large we round down instead of up; it's going to fail anyway. |
| 554 | let result = input.checked_add(granularity - 1).unwrap_or(input); |
| 555 | (result / granularity) * granularity |
| 556 | } |
| 557 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 558 | /// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm. |
| 559 | /// |
| 560 | /// This may involve assembling a composite disk from a set of partition images. |
| 561 | fn assemble_disk_image( |
| 562 | disk: &DiskImage, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 563 | zero_filler_path: &Path, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 564 | temporary_directory: &Path, |
| 565 | next_temporary_image_id: &mut u64, |
| 566 | indirect_files: &mut Vec<File>, |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 567 | ) -> Result<DiskFile, Status> { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 568 | let image = if !disk.partitions.is_empty() { |
| 569 | if disk.image.is_some() { |
| 570 | warn!("DiskImage {:?} contains both image and partitions.", disk); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 571 | return Err(anyhow!("DiskImage contains both image and partitions")) |
| 572 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 573 | } |
| 574 | |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 575 | let composite_image_filenames = |
| 576 | make_composite_image_filenames(temporary_directory, next_temporary_image_id); |
| 577 | let (image, partition_files) = make_composite_image( |
| 578 | &disk.partitions, |
Jooyung Han | 9588463 | 2021-07-06 22:27:54 +0900 | [diff] [blame] | 579 | zero_filler_path, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 580 | &composite_image_filenames.composite, |
| 581 | &composite_image_filenames.header, |
| 582 | &composite_image_filenames.footer, |
| 583 | ) |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 584 | .with_context(|| format!("Failed to make composite disk image with config {:?}", disk)) |
| 585 | .with_log() |
| 586 | .or_service_specific_exception(-1)?; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 587 | |
| 588 | // Pass the file descriptors for the various partition files to crosvm when it |
| 589 | // is run. |
| 590 | indirect_files.extend(partition_files); |
| 591 | |
| 592 | image |
| 593 | } else if let Some(image) = &disk.image { |
| 594 | clone_file(image)? |
| 595 | } else { |
| 596 | warn!("DiskImage {:?} didn't contain image or partitions.", disk); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 597 | return Err(anyhow!("DiskImage didn't contain image or partitions.")) |
| 598 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 599 | }; |
| 600 | |
| 601 | Ok(DiskFile { image, writable: disk.writable }) |
| 602 | } |
| 603 | |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 604 | fn append_kernel_param(param: &str, vm_config: &mut VirtualMachineRawConfig) { |
| 605 | if let Some(ref mut params) = vm_config.params { |
| 606 | params.push(' '); |
| 607 | params.push_str(param) |
| 608 | } else { |
| 609 | vm_config.params = Some(param.to_owned()) |
| 610 | } |
| 611 | } |
| 612 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 613 | fn load_app_config( |
| 614 | config: &VirtualMachineAppConfig, |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 615 | debug_config: &DebugConfig, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 616 | temporary_directory: &Path, |
Jooyung Han | adfb76c | 2021-06-28 17:29:30 +0900 | [diff] [blame] | 617 | ) -> Result<VirtualMachineRawConfig> { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 618 | let apk_file = clone_file(config.apk.as_ref().unwrap())?; |
| 619 | let idsig_file = clone_file(config.idsig.as_ref().unwrap())?; |
Jiyong Park | 8d08181 | 2021-07-23 17:45:04 +0900 | [diff] [blame] | 620 | let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 621 | |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 622 | let storage_image = if let Some(file) = config.encryptedStorageImage.as_ref() { |
| 623 | Some(clone_file(file)?) |
| 624 | } else { |
| 625 | None |
| 626 | }; |
| 627 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 628 | let vm_payload_config = match &config.payload { |
| 629 | Payload::ConfigPath(config_path) => { |
| 630 | load_vm_payload_config_from_file(&apk_file, config_path.as_str()) |
| 631 | .with_context(|| format!("Couldn't read config from {}", config_path))? |
| 632 | } |
Alan Stokes | 8f12f2b | 2023-01-09 09:19:20 +0000 | [diff] [blame] | 633 | Payload::PayloadConfig(payload_config) => create_vm_payload_config(payload_config)?, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 634 | }; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 635 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 636 | // For now, the only supported OS is Microdroid |
| 637 | let os_name = vm_payload_config.os.name.as_str(); |
| 638 | if os_name != MICRODROID_OS_NAME { |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 639 | bail!("Unknown OS \"{}\"", os_name); |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 640 | } |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 641 | |
| 642 | // It is safe to construct a filename based on the os_name because we've already checked that it |
| 643 | // is one of the allowed values. |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 644 | let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name)); |
| 645 | let vm_config_file = File::open(vm_config_path)?; |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 646 | let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 647 | |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 648 | if let Some(custom_config) = &config.customConfig { |
| 649 | if let Some(file) = custom_config.customKernelImage.as_ref() { |
| 650 | vm_config.kernel = Some(ParcelFileDescriptor::new(clone_file(file)?)) |
| 651 | } |
| 652 | vm_config.taskProfiles = custom_config.taskProfiles.clone(); |
| 653 | vm_config.gdbPort = custom_config.gdbPort; |
Nikita Ioffe | 5dfddf2 | 2023-06-29 16:11:26 +0100 | [diff] [blame] | 654 | |
| 655 | if let Some(file) = custom_config.vendorImage.as_ref() { |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 656 | add_microdroid_vendor_image(clone_file(file)?, &mut vm_config); |
| 657 | append_kernel_param("androidboot.microdroid.mount_vendor=1", &mut vm_config) |
Nikita Ioffe | 5dfddf2 | 2023-06-29 16:11:26 +0100 | [diff] [blame] | 658 | } |
Inseob Kim | 6ef8097 | 2023-07-20 17:23:36 +0900 | [diff] [blame] | 659 | |
| 660 | vm_config.devices = custom_config.devices.clone(); |
Nikita Ioffe | 26c35ed | 2023-06-05 17:49:08 +0100 | [diff] [blame] | 661 | } |
| 662 | |
Andrew Walbran | cc04590 | 2021-07-27 16:06:17 +0000 | [diff] [blame] | 663 | if config.memoryMib > 0 { |
| 664 | vm_config.memoryMib = config.memoryMib; |
Andrew Walbran | 45bcb0c | 2021-07-14 15:02:06 +0000 | [diff] [blame] | 665 | } |
| 666 | |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 667 | vm_config.name = config.name.clone(); |
Andrew Walbran | 3994f00 | 2022-01-27 17:33:45 +0000 | [diff] [blame] | 668 | vm_config.protectedVm = config.protectedVm; |
David Brazdil | 7d1e5ec | 2023-02-06 17:56:29 +0000 | [diff] [blame] | 669 | vm_config.cpuTopology = config.cpuTopology; |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 670 | |
Shikha Panwar | 22e7045 | 2022-10-10 18:32:55 +0000 | [diff] [blame] | 671 | // Microdroid takes additional init ramdisk & (optionally) storage image |
| 672 | add_microdroid_system_images(config, instance_file, storage_image, &mut vm_config)?; |
| 673 | |
| 674 | // Include Microdroid payload disk (contains apks, idsigs) in vm config |
| 675 | add_microdroid_payload_images( |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 676 | config, |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 677 | debug_config, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 678 | temporary_directory, |
| 679 | apk_file, |
| 680 | idsig_file, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 681 | &vm_payload_config, |
| 682 | &mut vm_config, |
| 683 | )?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 684 | |
Andrew Walbran | cc0db52 | 2021-07-12 17:03:42 +0000 | [diff] [blame] | 685 | Ok(vm_config) |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 686 | } |
| 687 | |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 688 | fn load_vm_payload_config_from_file(apk_file: &File, config_path: &str) -> Result<VmPayloadConfig> { |
| 689 | let mut apk_zip = ZipArchive::new(apk_file)?; |
| 690 | let config_file = apk_zip.by_name(config_path)?; |
| 691 | Ok(serde_json::from_reader(config_file)?) |
| 692 | } |
| 693 | |
Alan Stokes | 8f12f2b | 2023-01-09 09:19:20 +0000 | [diff] [blame] | 694 | fn create_vm_payload_config( |
| 695 | payload_config: &VirtualMachinePayloadConfig, |
| 696 | ) -> Result<VmPayloadConfig> { |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 697 | // There isn't an actual config file. Construct a synthetic VmPayloadConfig from the explicit |
| 698 | // parameters we've been given. Microdroid will do something equivalent inside the VM using the |
| 699 | // payload config that we send it via the metadata file. |
Alan Stokes | 8f12f2b | 2023-01-09 09:19:20 +0000 | [diff] [blame] | 700 | |
| 701 | let payload_binary_name = &payload_config.payloadBinaryName; |
| 702 | if payload_binary_name.contains('/') { |
| 703 | bail!("Payload binary name must not specify a path: {payload_binary_name}"); |
| 704 | } |
| 705 | |
| 706 | let task = Task { type_: TaskType::MicrodroidLauncher, command: payload_binary_name.clone() }; |
| 707 | Ok(VmPayloadConfig { |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 708 | os: OsConfig { name: MICRODROID_OS_NAME.to_owned() }, |
| 709 | task: Some(task), |
| 710 | apexes: vec![], |
| 711 | extra_apks: vec![], |
| 712 | prefer_staged: false, |
Inseob Kim | ab1037d | 2023-02-08 17:03:31 +0900 | [diff] [blame] | 713 | export_tombstones: None, |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 714 | enable_authfs: false, |
Alan Stokes | 8f12f2b | 2023-01-09 09:19:20 +0000 | [diff] [blame] | 715 | }) |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 716 | } |
| 717 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 718 | /// Generates a unique filename to use for a composite disk image. |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 719 | fn make_composite_image_filenames( |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 720 | temporary_directory: &Path, |
| 721 | next_temporary_image_id: &mut u64, |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 722 | ) -> CompositeImageFilenames { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 723 | let id = *next_temporary_image_id; |
| 724 | *next_temporary_image_id += 1; |
Andrew Walbran | 3eca16c | 2021-06-14 11:15:14 +0000 | [diff] [blame] | 725 | CompositeImageFilenames { |
| 726 | composite: temporary_directory.join(format!("composite-{}.img", id)), |
| 727 | header: temporary_directory.join(format!("composite-{}-header.img", id)), |
| 728 | footer: temporary_directory.join(format!("composite-{}-footer.img", id)), |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | /// Filenames for a composite disk image, including header and footer partitions. |
| 733 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 734 | struct CompositeImageFilenames { |
| 735 | /// The composite disk image itself. |
| 736 | composite: PathBuf, |
| 737 | /// The header partition image. |
| 738 | header: PathBuf, |
| 739 | /// The footer partition image. |
| 740 | footer: PathBuf, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 741 | } |
| 742 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 743 | /// Checks whether the caller has a specific permission |
| 744 | fn check_permission(perm: &str) -> binder::Result<()> { |
David Brazdil | 1f53070 | 2022-10-03 12:18:10 +0100 | [diff] [blame] | 745 | let calling_pid = get_calling_pid(); |
| 746 | let calling_uid = get_calling_uid(); |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 747 | // Root can do anything |
| 748 | if calling_uid == 0 { |
| 749 | return Ok(()); |
| 750 | } |
| 751 | let perm_svc: Strong<dyn IPermissionController::IPermissionController> = |
| 752 | binder::get_interface("permission")?; |
| 753 | if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 754 | Ok(()) |
| 755 | } else { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 756 | Err(anyhow!("does not have the {} permission", perm)) |
| 757 | .or_binder_exception(ExceptionCode::SECURITY) |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 758 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 759 | } |
| 760 | |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 761 | /// Check whether the caller of the current Binder method is allowed to manage VMs |
| 762 | fn check_manage_access() -> binder::Result<()> { |
| 763 | check_permission("android.permission.MANAGE_VIRTUAL_MACHINE") |
| 764 | } |
| 765 | |
Inseob Kim | 1119d70 | 2022-05-02 18:01:58 +0900 | [diff] [blame] | 766 | /// Check whether the caller of the current Binder method is allowed to create custom VMs |
| 767 | fn check_use_custom_virtual_machine() -> binder::Result<()> { |
| 768 | check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE") |
| 769 | } |
| 770 | |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 771 | /// Return whether a partition is exempt from selinux label checks, because we know that it does |
| 772 | /// not contain code and is likely to be generated in an app-writable directory. |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 773 | fn is_safe_app_partition(label: &str) -> bool { |
Shikha Panwar | a2ff8c5 | 2022-11-30 19:25:46 +0000 | [diff] [blame] | 774 | // See add_microdroid_system_images & add_microdroid_payload_images in payload.rs. |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 775 | label == "vm-instance" |
Shikha Panwar | a2ff8c5 | 2022-11-30 19:25:46 +0000 | [diff] [blame] | 776 | || label == "encryptedstore" |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 777 | || label == "microdroid-apk-idsig" |
| 778 | || label == "payload-metadata" |
| 779 | || label.starts_with("extra-idsig-") |
| 780 | } |
| 781 | |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 782 | /// Returns whether a partition with the given label is safe for a raw config VM. |
| 783 | fn is_safe_raw_partition(label: &str) -> bool { |
| 784 | label == "vm-instance" |
| 785 | } |
| 786 | |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 787 | /// Check that a file SELinux label is acceptable. |
| 788 | /// |
| 789 | /// We only want to allow code in a VM to be sourced from places that apps, and the |
| 790 | /// system, do not have write access to. |
| 791 | /// |
| 792 | /// Note that sepolicy must also grant read access for these types to both virtualization |
| 793 | /// service and crosvm. |
| 794 | /// |
| 795 | /// App private data files are deliberately excluded, to avoid arbitrary payloads being run on |
| 796 | /// user devices (W^X). |
| 797 | fn check_label_is_allowed(context: &SeContext) -> Result<()> { |
| 798 | match context.selinux_type()? { |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 799 | | "apk_data_file" // APKs of an installed app |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 800 | | "shell_data_file" // test files created via adb shell |
Alan Stokes | fe4bb0c | 2023-03-20 14:15:36 +0000 | [diff] [blame] | 801 | | "staging_data_file" // updated/staged APEX images |
| 802 | | "system_file" // immutable dm-verity protected partition |
| 803 | | "virtualizationservice_data_file" // files created by VS / VirtMgr |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 804 | => Ok(()), |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 805 | _ => bail!("Label {} is not allowed", context), |
Jiyong Park | 029977d | 2021-11-24 21:56:49 +0900 | [diff] [blame] | 806 | } |
| 807 | } |
| 808 | |
Alan Stokes | 185fe11 | 2023-01-10 16:20:55 +0000 | [diff] [blame] | 809 | fn check_label_for_partition(partition: &Partition) -> Result<()> { |
| 810 | let file = partition.image.as_ref().unwrap().as_ref(); |
| 811 | check_label_is_allowed(&getfilecon(file)?) |
| 812 | .with_context(|| format!("Partition {} invalid", &partition.label)) |
| 813 | } |
| 814 | |
| 815 | fn check_label_for_kernel_files(kernel: &Option<File>, initrd: &Option<File>) -> Result<()> { |
| 816 | if let Some(f) = kernel { |
| 817 | check_label_for_file(f, "kernel")?; |
| 818 | } |
| 819 | if let Some(f) = initrd { |
| 820 | check_label_for_file(f, "initrd")?; |
| 821 | } |
| 822 | Ok(()) |
| 823 | } |
| 824 | fn check_label_for_file(file: &File, name: &str) -> Result<()> { |
| 825 | check_label_is_allowed(&getfilecon(file)?).with_context(|| format!("{} file invalid", name)) |
| 826 | } |
| 827 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 828 | /// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM. |
| 829 | #[derive(Debug)] |
| 830 | struct VirtualMachine { |
| 831 | instance: Arc<VmInstance>, |
| 832 | } |
| 833 | |
| 834 | impl VirtualMachine { |
| 835 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
David Brazdil | 4b4c510 | 2022-12-19 22:56:20 +0000 | [diff] [blame] | 836 | BnVirtualMachine::new_binder(VirtualMachine { instance }, BinderFeatures::default()) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 837 | } |
| 838 | } |
| 839 | |
| 840 | impl Interface for VirtualMachine {} |
| 841 | |
| 842 | impl IVirtualMachine for VirtualMachine { |
| 843 | fn getCid(&self) -> binder::Result<i32> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 844 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 845 | // others. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 846 | Ok(self.instance.cid as i32) |
| 847 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 848 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 849 | fn getState(&self) -> binder::Result<VirtualMachineState> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 850 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 851 | // others. |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 852 | Ok(get_state(&self.instance)) |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 853 | } |
| 854 | |
| 855 | fn registerCallback( |
| 856 | &self, |
| 857 | callback: &Strong<dyn IVirtualMachineCallback>, |
| 858 | ) -> binder::Result<()> { |
Jiyong Park | 753553b | 2021-07-12 21:21:09 +0900 | [diff] [blame] | 859 | // Don't check permission. The owner of the VM might have passed this binder object to |
| 860 | // others. |
| 861 | // |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 862 | // TODO: Should this give an error if the VM is already dead? |
| 863 | self.instance.callbacks.add(callback.clone()); |
| 864 | Ok(()) |
| 865 | } |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 866 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 867 | fn start(&self) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 868 | self.instance |
| 869 | .start() |
| 870 | .with_context(|| format!("Error starting VM with CID {}", self.instance.cid)) |
| 871 | .with_log() |
| 872 | .or_service_specific_exception(-1) |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 873 | } |
| 874 | |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 875 | fn stop(&self) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 876 | self.instance |
| 877 | .kill() |
| 878 | .with_context(|| format!("Error stopping VM with CID {}", self.instance.cid)) |
| 879 | .with_log() |
| 880 | .or_service_specific_exception(-1) |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 881 | } |
| 882 | |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame] | 883 | fn onTrimMemory(&self, level: MemoryTrimLevel) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 884 | self.instance |
| 885 | .trim_memory(level) |
| 886 | .with_context(|| format!("Error trimming VM with CID {}", self.instance.cid)) |
| 887 | .with_log() |
| 888 | .or_service_specific_exception(-1) |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame] | 889 | } |
| 890 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 891 | fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 892 | if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 893 | return Err(anyhow!("VM is not running")).or_service_specific_exception(-1); |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 894 | } |
Alan Stokes | 10c4767 | 2022-12-13 17:17:08 +0000 | [diff] [blame] | 895 | let port = port as u32; |
| 896 | if port < 1024 { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 897 | return Err(anyhow!("Can't connect to privileged port {port}")) |
| 898 | .or_service_specific_exception(-1); |
Alan Stokes | 10c4767 | 2022-12-13 17:17:08 +0000 | [diff] [blame] | 899 | } |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 900 | let stream = VsockStream::connect_with_cid_port(self.instance.cid, port) |
| 901 | .context("Failed to connect") |
| 902 | .or_service_specific_exception(-1)?; |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 903 | Ok(vsock_stream_to_pfd(stream)) |
| 904 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 905 | } |
| 906 | |
| 907 | impl Drop for VirtualMachine { |
| 908 | fn drop(&mut self) { |
| 909 | debug!("Dropping {:?}", self); |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 910 | if let Err(e) = self.instance.kill() { |
| 911 | debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e); |
| 912 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 913 | } |
| 914 | } |
| 915 | |
| 916 | /// A set of Binders to be called back in response to various events on the VM, such as when it |
| 917 | /// dies. |
| 918 | #[derive(Debug, Default)] |
| 919 | pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>); |
| 920 | |
| 921 | impl VirtualMachineCallbacks { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 922 | /// Call all registered callbacks to notify that the payload has started. |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 923 | pub fn notify_payload_started(&self, cid: Cid) { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 924 | let callbacks = &*self.0.lock().unwrap(); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 925 | for callback in callbacks { |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 926 | if let Err(e) = callback.onPayloadStarted(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 927 | error!("Error notifying payload start event from VM CID {}: {:?}", cid, e); |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 928 | } |
| 929 | } |
| 930 | } |
| 931 | |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 932 | /// Call all registered callbacks to notify that the payload is ready to serve. |
| 933 | pub fn notify_payload_ready(&self, cid: Cid) { |
| 934 | let callbacks = &*self.0.lock().unwrap(); |
| 935 | for callback in callbacks { |
| 936 | if let Err(e) = callback.onPayloadReady(cid as i32) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 937 | error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 938 | } |
| 939 | } |
| 940 | } |
| 941 | |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 942 | /// Call all registered callbacks to notify that the payload has finished. |
| 943 | pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) { |
| 944 | let callbacks = &*self.0.lock().unwrap(); |
| 945 | for callback in callbacks { |
| 946 | if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 947 | error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e); |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 948 | } |
| 949 | } |
| 950 | } |
| 951 | |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 952 | /// Call all registered callbacks to say that the VM encountered an error. |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 953 | pub fn notify_error(&self, cid: Cid, error_code: ErrorCode, message: &str) { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 954 | let callbacks = &*self.0.lock().unwrap(); |
| 955 | for callback in callbacks { |
| 956 | if let Err(e) = callback.onError(cid as i32, error_code, message) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 957 | error!("Error notifying error event from VM CID {}: {:?}", cid, e); |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 958 | } |
| 959 | } |
| 960 | } |
| 961 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 962 | /// Call all registered callbacks to say that the VM has died. |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 963 | pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 964 | let callbacks = &*self.0.lock().unwrap(); |
| 965 | for callback in callbacks { |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 966 | if let Err(e) = callback.onDied(cid as i32, reason) { |
Alan Stokes | 70ccf16 | 2022-07-08 11:05:03 +0100 | [diff] [blame] | 967 | error!("Error notifying exit of VM CID {}: {:?}", cid, e); |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 968 | } |
| 969 | } |
| 970 | } |
| 971 | |
| 972 | /// Add a new callback to the set. |
| 973 | fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) { |
| 974 | self.0.lock().unwrap().push(callback); |
| 975 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 976 | } |
| 977 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 978 | /// The mutable state of the VirtualizationService. There should only be one instance of this |
| 979 | /// struct. |
Chris Wailes | 641fc4a | 2021-12-01 15:03:21 -0800 | [diff] [blame] | 980 | #[derive(Debug, Default)] |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 981 | struct State { |
Alan Stokes | 3e5eec1 | 2023-09-07 12:10:00 +0100 | [diff] [blame] | 982 | /// The VMs which have been started. When VMs are started a weak reference is added to this |
| 983 | /// list while a strong reference is returned to the caller over Binder. Once all copies of |
| 984 | /// the Binder client are dropped the weak reference here will become invalid, and will be |
| 985 | /// removed from the list opportunistically the next time `add_vm` is called. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 986 | vms: Vec<Weak<VmInstance>>, |
| 987 | } |
| 988 | |
| 989 | impl State { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 990 | /// Get a list of VMs which still have Binder references to them. |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 991 | fn vms(&self) -> Vec<Arc<VmInstance>> { |
| 992 | // Attempt to upgrade the weak pointers to strong pointers. |
| 993 | self.vms.iter().filter_map(Weak::upgrade).collect() |
| 994 | } |
| 995 | |
| 996 | /// Add a new VM to the list. |
| 997 | fn add_vm(&mut self, vm: Weak<VmInstance>) { |
| 998 | // Garbage collect any entries from the stored list which no longer exist. |
| 999 | self.vms.retain(|vm| vm.strong_count() > 0); |
| 1000 | |
| 1001 | // Actually add the new VM. |
| 1002 | self.vms.push(vm); |
| 1003 | } |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 1004 | |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 1005 | /// Get a VM that corresponds to the given cid |
| 1006 | fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> { |
| 1007 | self.vms().into_iter().find(|vm| vm.cid == cid) |
| 1008 | } |
Jiyong Park | d50a024 | 2021-09-16 21:00:14 +0900 | [diff] [blame] | 1009 | } |
| 1010 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1011 | /// Gets the `VirtualMachineState` of the given `VmInstance`. |
| 1012 | fn get_state(instance: &VmInstance) -> VirtualMachineState { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1013 | match &*instance.vm_state.lock().unwrap() { |
| 1014 | VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED, |
| 1015 | VmState::Running { .. } => match instance.payload_state() { |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1016 | PayloadState::Starting => VirtualMachineState::STARTING, |
| 1017 | PayloadState::Started => VirtualMachineState::STARTED, |
| 1018 | PayloadState::Ready => VirtualMachineState::READY, |
| 1019 | PayloadState::Finished => VirtualMachineState::FINISHED, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 1020 | PayloadState::Hangup => VirtualMachineState::DEAD, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 1021 | }, |
| 1022 | VmState::Dead => VirtualMachineState::DEAD, |
| 1023 | VmState::Failed => VirtualMachineState::DEAD, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 1024 | } |
| 1025 | } |
| 1026 | |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 1027 | /// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1028 | pub fn clone_file(file: &ParcelFileDescriptor) -> binder::Result<File> { |
| 1029 | file.as_ref() |
| 1030 | .try_clone() |
| 1031 | .context("Failed to clone File from ParcelFileDescriptor") |
| 1032 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE) |
Andrei Homescu | 11333c6 | 2023-11-09 04:26:39 +0000 | [diff] [blame] | 1033 | .map(File::from) |
David Brazdil | f50c7a6 | 2023-04-19 14:22:42 +0000 | [diff] [blame] | 1034 | } |
| 1035 | |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 1036 | /// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1037 | fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> binder::Result<Option<File>> { |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 1038 | file.as_ref().map(clone_file).transpose() |
| 1039 | } |
| 1040 | |
Andrew Walbran | cbe8b08 | 2021-08-06 15:42:11 +0000 | [diff] [blame] | 1041 | /// Converts a `VsockStream` to a `ParcelFileDescriptor`. |
| 1042 | fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor { |
| 1043 | // SAFETY: ownership is transferred from stream to f |
| 1044 | let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) }; |
| 1045 | ParcelFileDescriptor::new(f) |
| 1046 | } |
| 1047 | |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1048 | /// Parses the platform version requirement string. |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1049 | fn parse_platform_version_req(s: &str) -> binder::Result<VersionReq> { |
| 1050 | VersionReq::parse(s) |
| 1051 | .with_context(|| format!("Invalid platform version requirement {}", s)) |
| 1052 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE) |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 1053 | } |
| 1054 | |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 1055 | /// Create the empty ramdump file |
| 1056 | fn prepare_ramdump_file(temporary_directory: &Path) -> binder::Result<File> { |
| 1057 | // `ramdump_write` is sent to crosvm and will be the backing store for the /dev/hvc1 where |
| 1058 | // VM will emit ramdump to. `ramdump_read` will be sent back to the client (i.e. the VM |
| 1059 | // owner) for readout. |
| 1060 | let ramdump_path = temporary_directory.join("ramdump"); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1061 | let ramdump = File::create(ramdump_path) |
| 1062 | .context("Failed to prepare ramdump file") |
| 1063 | .with_log() |
| 1064 | .or_service_specific_exception(-1)?; |
Jiyong Park | ed18093 | 2023-02-24 19:55:41 +0900 | [diff] [blame] | 1065 | Ok(ramdump) |
| 1066 | } |
| 1067 | |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 1068 | fn is_protected(config: &VirtualMachineConfig) -> bool { |
| 1069 | match config { |
| 1070 | VirtualMachineConfig::RawConfig(config) => config.protectedVm, |
| 1071 | VirtualMachineConfig::AppConfig(config) => config.protectedVm, |
| 1072 | } |
| 1073 | } |
| 1074 | |
| 1075 | fn check_gdb_allowed(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 1076 | if is_protected(config) { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1077 | return Err(anyhow!("Can't use gdb with protected VMs")) |
| 1078 | .or_binder_exception(ExceptionCode::SECURITY); |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 1079 | } |
| 1080 | |
| 1081 | match config { |
| 1082 | VirtualMachineConfig::RawConfig(_) => Ok(()), |
| 1083 | VirtualMachineConfig::AppConfig(config) => { |
| 1084 | if config.debugLevel != DebugLevel::FULL { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1085 | Err(anyhow!("Can't use gdb with non-debuggable VMs")) |
| 1086 | .or_binder_exception(ExceptionCode::SECURITY) |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 1087 | } else { |
| 1088 | Ok(()) |
| 1089 | } |
| 1090 | } |
| 1091 | } |
| 1092 | } |
| 1093 | |
| 1094 | fn extract_gdb_port(config: &VirtualMachineConfig) -> Option<NonZeroU16> { |
| 1095 | match config { |
| 1096 | VirtualMachineConfig::RawConfig(config) => NonZeroU16::new(config.gdbPort as u16), |
Nikita Ioffe | a0eb5ee | 2023-06-26 18:18:21 +0100 | [diff] [blame] | 1097 | VirtualMachineConfig::AppConfig(config) => { |
| 1098 | NonZeroU16::new(config.customConfig.as_ref().map(|c| c.gdbPort).unwrap_or(0) as u16) |
| 1099 | } |
Nikita Ioffe | 5776f08 | 2023-02-10 21:38:26 +0000 | [diff] [blame] | 1100 | } |
| 1101 | } |
| 1102 | |
Nikita Ioffe | 631717e | 2023-09-05 13:38:07 +0100 | [diff] [blame] | 1103 | fn check_no_vendor_modules(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 1104 | let VirtualMachineConfig::AppConfig(config) = config else { return Ok(()) }; |
| 1105 | if let Some(custom_config) = &config.customConfig { |
| 1106 | if custom_config.vendorImage.is_some() || custom_config.customKernelImage.is_some() { |
| 1107 | return Err(anyhow!("vendor modules feature is disabled")) |
| 1108 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
| 1109 | } |
| 1110 | } |
| 1111 | Ok(()) |
| 1112 | } |
| 1113 | |
| 1114 | fn check_config_features(config: &VirtualMachineConfig) -> binder::Result<()> { |
| 1115 | if !cfg!(vendor_modules) { |
| 1116 | check_no_vendor_modules(config)?; |
| 1117 | } |
| 1118 | Ok(()) |
| 1119 | } |
| 1120 | |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 1121 | fn clone_or_prepare_logger_fd( |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 1122 | debug_config: &DebugConfig, |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 1123 | fd: Option<&ParcelFileDescriptor>, |
| 1124 | tag: String, |
| 1125 | ) -> Result<Option<File>, Status> { |
| 1126 | if let Some(fd) = fd { |
| 1127 | return Ok(Some(clone_file(fd)?)); |
| 1128 | } |
| 1129 | |
Jaewan Kim | 61f8614 | 2023-03-28 15:12:52 +0900 | [diff] [blame] | 1130 | if !debug_config.should_prepare_console_output() { |
Jaewan Kim | 66f062e | 2023-02-25 01:07:43 +0900 | [diff] [blame] | 1131 | return Ok(None); |
| 1132 | }; |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 1133 | |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1134 | let (raw_read_fd, raw_write_fd) = |
| 1135 | pipe().context("Failed to create pipe").or_service_specific_exception(-1)?; |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 1136 | |
Andrew Walbran | b58d1b4 | 2023-07-07 13:54:49 +0100 | [diff] [blame] | 1137 | // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open. |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 1138 | let mut reader = BufReader::new(unsafe { File::from_raw_fd(raw_read_fd) }); |
Andrew Walbran | b58d1b4 | 2023-07-07 13:54:49 +0100 | [diff] [blame] | 1139 | // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open. |
Inseob Kim | 0168b46 | 2022-12-27 14:54:35 +0900 | [diff] [blame] | 1140 | let write_fd = unsafe { File::from_raw_fd(raw_write_fd) }; |
| 1141 | |
| 1142 | std::thread::spawn(move || loop { |
| 1143 | let mut buf = vec![]; |
| 1144 | match reader.read_until(b'\n', &mut buf) { |
| 1145 | Ok(0) => { |
| 1146 | // EOF |
| 1147 | return; |
| 1148 | } |
| 1149 | Ok(size) => { |
| 1150 | if buf[size - 1] == b'\n' { |
| 1151 | buf.pop(); |
| 1152 | } |
| 1153 | info!("{}: {}", &tag, &String::from_utf8_lossy(&buf)); |
| 1154 | } |
| 1155 | Err(e) => { |
| 1156 | error!("Could not read console pipe: {:?}", e); |
| 1157 | return; |
| 1158 | } |
| 1159 | }; |
| 1160 | }); |
| 1161 | |
| 1162 | Ok(Some(write_fd)) |
| 1163 | } |
| 1164 | |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1165 | /// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but |
| 1166 | /// it doesn't require that T implements Clone. |
| 1167 | enum BorrowedOrOwned<'a, T> { |
| 1168 | Borrowed(&'a T), |
| 1169 | Owned(T), |
| 1170 | } |
| 1171 | |
| 1172 | impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> { |
| 1173 | fn as_ref(&self) -> &T { |
| 1174 | match self { |
| 1175 | Self::Borrowed(b) => b, |
Chris Wailes | 68c39f8 | 2021-07-27 16:03:44 -0700 | [diff] [blame] | 1176 | Self::Owned(o) => o, |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 1177 | } |
| 1178 | } |
| 1179 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1180 | |
| 1181 | /// Implementation of `IVirtualMachineService`, the entry point of the AIDL service. |
| 1182 | #[derive(Debug, Default)] |
| 1183 | struct VirtualMachineService { |
| 1184 | state: Arc<Mutex<State>>, |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1185 | cid: Cid, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1186 | } |
| 1187 | |
| 1188 | impl Interface for VirtualMachineService {} |
| 1189 | |
| 1190 | impl IVirtualMachineService for VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1191 | fn notifyPayloadStarted(&self) -> binder::Result<()> { |
| 1192 | let cid = self.cid; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1193 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 1194 | info!("VM with CID {} started payload", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1195 | vm.update_payload_state(PayloadState::Started) |
| 1196 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 1197 | vm.callbacks.notify_payload_started(cid); |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 1198 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 1199 | let vm_start_timestamp = vm.vm_metric.lock().unwrap().start_timestamp; |
| 1200 | write_vm_booted_stats(vm.requester_uid as i32, &vm.name, vm_start_timestamp); |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 1201 | Ok(()) |
| 1202 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1203 | error!("notifyPayloadStarted is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1204 | Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1) |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1205 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1206 | } |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1207 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1208 | fn notifyPayloadReady(&self) -> binder::Result<()> { |
| 1209 | let cid = self.cid; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1210 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 1211 | info!("VM with CID {} reported payload is ready", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1212 | vm.update_payload_state(PayloadState::Ready) |
| 1213 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1214 | vm.callbacks.notify_payload_ready(cid); |
| 1215 | Ok(()) |
| 1216 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1217 | error!("notifyPayloadReady is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1218 | Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1) |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 1219 | } |
| 1220 | } |
| 1221 | |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1222 | fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> { |
| 1223 | let cid = self.cid; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1224 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 1225 | info!("VM with CID {} finished payload", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1226 | vm.update_payload_state(PayloadState::Finished) |
| 1227 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1228 | vm.callbacks.notify_payload_finished(cid, exit_code); |
| 1229 | Ok(()) |
| 1230 | } else { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1231 | error!("notifyPayloadFinished is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1232 | Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1) |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1233 | } |
| 1234 | } |
| 1235 | |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 1236 | fn notifyError(&self, error_code: ErrorCode, message: &str) -> binder::Result<()> { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1237 | let cid = self.cid; |
| 1238 | if let Some(vm) = self.state.lock().unwrap().get_vm(cid) { |
David Brazdil | 415097c | 2022-10-21 14:17:05 +0100 | [diff] [blame] | 1239 | info!("VM with CID {} encountered an error", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1240 | vm.update_payload_state(PayloadState::Finished) |
| 1241 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 1242 | vm.callbacks.notify_error(cid, error_code, message); |
| 1243 | Ok(()) |
| 1244 | } else { |
Seungjae Yoo | ec8c160 | 2022-06-20 05:28:00 +0000 | [diff] [blame] | 1245 | error!("notifyError is called from an unknown CID {}", cid); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 1246 | Err(anyhow!("cannot find a VM with CID {}", cid)).or_service_specific_exception(-1) |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 1247 | } |
| 1248 | } |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 1249 | |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 1250 | fn requestAttestation(&self, csr: &[u8]) -> binder::Result<Vec<Certificate>> { |
Alice Wang | a410b64 | 2023-10-18 09:05:15 +0000 | [diff] [blame] | 1251 | GLOBAL_SERVICE.requestAttestation(csr) |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 1252 | } |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1253 | } |
| 1254 | |
| 1255 | impl VirtualMachineService { |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1256 | fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> { |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1257 | BnVirtualMachineService::new_binder( |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 1258 | VirtualMachineService { state, cid }, |
Inseob Kim | 1b95f2e | 2021-08-19 13:17:40 +0900 | [diff] [blame] | 1259 | BinderFeatures::default(), |
| 1260 | ) |
| 1261 | } |
| 1262 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1263 | |
| 1264 | #[cfg(test)] |
| 1265 | mod tests { |
| 1266 | use super::*; |
| 1267 | |
| 1268 | #[test] |
| 1269 | fn test_is_allowed_label_for_partition() -> Result<()> { |
| 1270 | let expected_results = vec![ |
| 1271 | ("u:object_r:system_file:s0", true), |
| 1272 | ("u:object_r:apk_data_file:s0", true), |
| 1273 | ("u:object_r:app_data_file:s0", false), |
| 1274 | ("u:object_r:app_data_file:s0:c512,c768", false), |
| 1275 | ("u:object_r:privapp_data_file:s0:c512,c768", false), |
| 1276 | ("invalid", false), |
| 1277 | ("user:role:apk_data_file:severity:categories", true), |
| 1278 | ("user:role:apk_data_file:severity:categories:extraneous", false), |
| 1279 | ]; |
| 1280 | |
| 1281 | for (label, expected_valid) in expected_results { |
| 1282 | let context = SeContext::new(label)?; |
| 1283 | let result = check_label_is_allowed(&context); |
| 1284 | if expected_valid { |
| 1285 | assert!(result.is_ok(), "Expected label {} to be allowed, got {:?}", label, result); |
| 1286 | } else if result.is_ok() { |
| 1287 | bail!("Expected label {} to be disallowed", label); |
| 1288 | } |
| 1289 | } |
| 1290 | Ok(()) |
| 1291 | } |
Nikita Ioffe | f1ce987 | 2022-12-09 13:31:59 +0000 | [diff] [blame] | 1292 | |
| 1293 | #[test] |
| 1294 | fn test_create_or_update_idsig_file_empty_apk() -> Result<()> { |
| 1295 | let apk = tempfile::tempfile().unwrap(); |
| 1296 | let idsig = tempfile::tempfile().unwrap(); |
| 1297 | |
| 1298 | let ret = create_or_update_idsig_file( |
| 1299 | &ParcelFileDescriptor::new(apk), |
| 1300 | &ParcelFileDescriptor::new(idsig), |
| 1301 | ); |
| 1302 | assert!(ret.is_err(), "should fail"); |
| 1303 | Ok(()) |
| 1304 | } |
| 1305 | |
| 1306 | #[test] |
| 1307 | fn test_create_or_update_idsig_dir_instead_of_file_for_apk() -> Result<()> { |
| 1308 | let tmp_dir = tempfile::TempDir::new().unwrap(); |
| 1309 | let apk = File::open(tmp_dir.path()).unwrap(); |
| 1310 | let idsig = tempfile::tempfile().unwrap(); |
| 1311 | |
| 1312 | let ret = create_or_update_idsig_file( |
| 1313 | &ParcelFileDescriptor::new(apk), |
| 1314 | &ParcelFileDescriptor::new(idsig), |
| 1315 | ); |
| 1316 | assert!(ret.is_err(), "should fail"); |
| 1317 | Ok(()) |
| 1318 | } |
| 1319 | |
| 1320 | /// Verifies that create_or_update_idsig_file won't oom if a fd that corresponds to a directory |
| 1321 | /// on ext4 filesystem is passed. |
| 1322 | /// On ext4 lseek on a directory fd will return (off_t)-1 (see: |
| 1323 | /// https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in |
| 1324 | /// create_or_update_idsig_file ooming while attempting to allocate petabytes of memory. |
| 1325 | #[test] |
| 1326 | fn test_create_or_update_idsig_does_not_crash_dir_on_ext4() -> Result<()> { |
| 1327 | // APEXes are backed by the ext4. |
| 1328 | let apk = File::open("/apex/com.android.virt/").unwrap(); |
| 1329 | let idsig = tempfile::tempfile().unwrap(); |
| 1330 | |
| 1331 | let ret = create_or_update_idsig_file( |
| 1332 | &ParcelFileDescriptor::new(apk), |
| 1333 | &ParcelFileDescriptor::new(idsig), |
| 1334 | ); |
| 1335 | assert!(ret.is_err(), "should fail"); |
| 1336 | Ok(()) |
| 1337 | } |
Jiyong Park | 8d19295 | 2023-06-26 14:29:51 +0900 | [diff] [blame] | 1338 | |
| 1339 | #[test] |
| 1340 | fn test_create_or_update_idsig_does_not_update_if_already_valid() -> Result<()> { |
| 1341 | use std::io::Seek; |
| 1342 | |
| 1343 | // Pick any APK |
| 1344 | let mut apk = File::open("/system/priv-app/Shell/Shell.apk").unwrap(); |
| 1345 | let mut idsig = tempfile::tempfile().unwrap(); |
| 1346 | |
| 1347 | create_or_update_idsig_file( |
| 1348 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 1349 | &ParcelFileDescriptor::new(idsig.try_clone()?), |
| 1350 | )?; |
| 1351 | let modified_orig = idsig.metadata()?.modified()?; |
| 1352 | apk.rewind()?; |
| 1353 | idsig.rewind()?; |
| 1354 | |
| 1355 | // Call the function again |
| 1356 | create_or_update_idsig_file( |
| 1357 | &ParcelFileDescriptor::new(apk.try_clone()?), |
| 1358 | &ParcelFileDescriptor::new(idsig.try_clone()?), |
| 1359 | )?; |
| 1360 | let modified_new = idsig.metadata()?.modified()?; |
| 1361 | assert!(modified_orig == modified_new, "idsig file was updated unnecessarily"); |
| 1362 | Ok(()) |
| 1363 | } |
Nikita Ioffe | aa6858c | 2023-07-04 01:37:41 +0100 | [diff] [blame] | 1364 | |
| 1365 | #[test] |
| 1366 | fn test_append_kernel_param_first_param() { |
| 1367 | let mut vm_config = VirtualMachineRawConfig { ..Default::default() }; |
| 1368 | append_kernel_param("foo=1", &mut vm_config); |
| 1369 | assert_eq!(vm_config.params, Some("foo=1".to_owned())) |
| 1370 | } |
| 1371 | |
| 1372 | #[test] |
| 1373 | fn test_append_kernel_param() { |
| 1374 | let mut vm_config = |
| 1375 | VirtualMachineRawConfig { params: Some("foo=5".to_owned()), ..Default::default() }; |
| 1376 | append_kernel_param("bar=42", &mut vm_config); |
| 1377 | assert_eq!(vm_config.params, Some("foo=5 bar=42".to_owned())) |
| 1378 | } |
Alan Stokes | 53cc5ca | 2022-08-30 14:28:19 +0100 | [diff] [blame] | 1379 | } |