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