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