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