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