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