David Brazdil | afc9a9e | 2023-01-12 16:08:10 +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 | |
| 15 | //! Implementation of the AIDL interface of the VirtualizationService. |
| 16 | |
Alice Wang | bff017f | 2023-11-09 14:43:28 +0000 | [diff] [blame] | 17 | use crate::{get_calling_pid, get_calling_uid, REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME}; |
David Brazdil | 33a3102 | 2023-01-12 16:55:16 +0000 | [diff] [blame] | 18 | use crate::atom::{forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_atom}; |
Alice Wang | a410b64 | 2023-10-18 09:05:15 +0000 | [diff] [blame] | 19 | use crate::rkpvm::request_attestation; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 20 | use android_os_permissions_aidl::aidl::android::os::IPermissionController; |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 21 | use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::Certificate::Certificate; |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 22 | use android_system_virtualizationservice::{ |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 23 | aidl::android::system::virtualizationservice::AssignableDevice::AssignableDevice, |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 24 | aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo, |
| 25 | binder::ParcelFileDescriptor, |
| 26 | }; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 27 | use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{ |
| 28 | AtomVmBooted::AtomVmBooted, |
| 29 | AtomVmCreationRequested::AtomVmCreationRequested, |
| 30 | AtomVmExited::AtomVmExited, |
| 31 | IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext}, |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 32 | IVirtualizationServiceInternal::BoundDevice::BoundDevice, |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 33 | IVirtualizationServiceInternal::IVirtualizationServiceInternal, |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 34 | IVfioHandler::{BpVfioHandler, IVfioHandler}, |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 35 | }; |
| 36 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::VM_TOMBSTONES_SERVICE_PORT; |
Alice Wang | d1b11a0 | 2023-04-18 12:30:20 +0000 | [diff] [blame] | 37 | use anyhow::{anyhow, ensure, Context, Result}; |
Jiyong Park | d7bd2f2 | 2023-08-10 20:41:19 +0900 | [diff] [blame] | 38 | use avflog::LogResult; |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 39 | use binder::{self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, Status, Strong, IntoBinderResult}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 40 | use libc::VMADDR_CID_HOST; |
| 41 | use log::{error, info, warn}; |
Alice Wang | bff017f | 2023-11-09 14:43:28 +0000 | [diff] [blame] | 42 | use rkpd_client::get_rkpd_attestation_key; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 43 | use rustutils::system_properties; |
Inseob Kim | c4a774d | 2023-08-30 12:48:43 +0900 | [diff] [blame] | 44 | use serde::Deserialize; |
| 45 | use std::collections::{HashMap, HashSet}; |
Seungjae Yoo | 9d3c20a | 2023-09-07 15:36:44 +0900 | [diff] [blame] | 46 | use std::fs::{self, create_dir, remove_dir_all, set_permissions, File, Permissions}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 47 | use std::io::{Read, Write}; |
| 48 | use std::os::unix::fs::PermissionsExt; |
| 49 | use std::os::unix::raw::{pid_t, uid_t}; |
Inseob Kim | 55438b2 | 2023-08-09 20:16:01 +0900 | [diff] [blame] | 50 | use std::path::{Path, PathBuf}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 51 | use std::sync::{Arc, Mutex, Weak}; |
| 52 | use tombstoned_client::{DebuggerdDumpType, TombstonedConnection}; |
| 53 | use vsock::{VsockListener, VsockStream}; |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 54 | use nix::unistd::{chown, Uid}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 55 | |
| 56 | /// The unique ID of a VM used (together with a port number) for vsock communication. |
| 57 | pub type Cid = u32; |
| 58 | |
| 59 | pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice"; |
| 60 | |
| 61 | /// Directory in which to write disk image files used while running VMs. |
| 62 | pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice"; |
| 63 | |
| 64 | /// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this |
| 65 | /// are reserved for the host or other usage. |
| 66 | const GUEST_CID_MIN: Cid = 2048; |
| 67 | const GUEST_CID_MAX: Cid = 65535; |
| 68 | |
| 69 | const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid"; |
| 70 | |
| 71 | const CHUNK_RECV_MAX_LEN: usize = 1024; |
| 72 | |
| 73 | fn is_valid_guest_cid(cid: Cid) -> bool { |
| 74 | (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid) |
| 75 | } |
| 76 | |
| 77 | /// Singleton service for allocating globally-unique VM resources, such as the CID, and running |
| 78 | /// singleton servers, like tombstone receiver. |
| 79 | #[derive(Debug, Default)] |
| 80 | pub struct VirtualizationServiceInternal { |
| 81 | state: Arc<Mutex<GlobalState>>, |
| 82 | } |
| 83 | |
| 84 | impl VirtualizationServiceInternal { |
| 85 | pub fn init() -> VirtualizationServiceInternal { |
| 86 | let service = VirtualizationServiceInternal::default(); |
| 87 | |
| 88 | std::thread::spawn(|| { |
| 89 | if let Err(e) = handle_stream_connection_tombstoned() { |
| 90 | warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e); |
| 91 | } |
| 92 | }); |
| 93 | |
| 94 | service |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | impl Interface for VirtualizationServiceInternal {} |
| 99 | |
| 100 | impl IVirtualizationServiceInternal for VirtualizationServiceInternal { |
| 101 | fn removeMemlockRlimit(&self) -> binder::Result<()> { |
| 102 | let pid = get_calling_pid(); |
| 103 | let lim = libc::rlimit { rlim_cur: libc::RLIM_INFINITY, rlim_max: libc::RLIM_INFINITY }; |
| 104 | |
Andrew Walbran | b58d1b4 | 2023-07-07 13:54:49 +0100 | [diff] [blame] | 105 | // SAFETY: borrowing the new limit struct only |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 106 | let ret = unsafe { libc::prlimit(pid, libc::RLIMIT_MEMLOCK, &lim, std::ptr::null_mut()) }; |
| 107 | |
| 108 | match ret { |
| 109 | 0 => Ok(()), |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 110 | -1 => Err(std::io::Error::last_os_error().into()), |
| 111 | n => Err(anyhow!("Unexpected return value from prlimit(): {n}")), |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 112 | } |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 113 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE) |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 114 | } |
| 115 | |
| 116 | fn allocateGlobalVmContext( |
| 117 | &self, |
| 118 | requester_debug_pid: i32, |
| 119 | ) -> binder::Result<Strong<dyn IGlobalVmContext>> { |
| 120 | check_manage_access()?; |
| 121 | |
| 122 | let requester_uid = get_calling_uid(); |
| 123 | let requester_debug_pid = requester_debug_pid as pid_t; |
| 124 | let state = &mut *self.state.lock().unwrap(); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 125 | state |
| 126 | .allocate_vm_context(requester_uid, requester_debug_pid) |
| 127 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE) |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 128 | } |
| 129 | |
| 130 | fn atomVmBooted(&self, atom: &AtomVmBooted) -> Result<(), Status> { |
| 131 | forward_vm_booted_atom(atom); |
| 132 | Ok(()) |
| 133 | } |
| 134 | |
| 135 | fn atomVmCreationRequested(&self, atom: &AtomVmCreationRequested) -> Result<(), Status> { |
| 136 | forward_vm_creation_atom(atom); |
| 137 | Ok(()) |
| 138 | } |
| 139 | |
| 140 | fn atomVmExited(&self, atom: &AtomVmExited) -> Result<(), Status> { |
| 141 | forward_vm_exited_atom(atom); |
| 142 | Ok(()) |
| 143 | } |
| 144 | |
| 145 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
| 146 | check_debug_access()?; |
| 147 | |
| 148 | let state = &mut *self.state.lock().unwrap(); |
| 149 | let cids = state |
| 150 | .held_contexts |
| 151 | .iter() |
| 152 | .filter_map(|(_, inst)| Weak::upgrade(inst)) |
| 153 | .map(|vm| VirtualMachineDebugInfo { |
| 154 | cid: vm.cid as i32, |
| 155 | temporaryDirectory: vm.get_temp_dir().to_string_lossy().to_string(), |
| 156 | requesterUid: vm.requester_uid as i32, |
Charisee | 96113f3 | 2023-01-26 09:00:42 +0000 | [diff] [blame] | 157 | requesterPid: vm.requester_debug_pid, |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 158 | }) |
| 159 | .collect(); |
| 160 | Ok(cids) |
| 161 | } |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 162 | |
Alice Wang | bff017f | 2023-11-09 14:43:28 +0000 | [diff] [blame] | 163 | fn requestAttestation( |
| 164 | &self, |
| 165 | csr: &[u8], |
| 166 | requester_uid: i32, |
| 167 | ) -> binder::Result<Vec<Certificate>> { |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 168 | check_manage_access()?; |
Alice Wang | a410b64 | 2023-10-18 09:05:15 +0000 | [diff] [blame] | 169 | info!("Received csr. Requestting attestation..."); |
Alice Wang | e9ac2db | 2023-09-08 15:13:13 +0000 | [diff] [blame] | 170 | if cfg!(remote_attestation) { |
Alice Wang | bff017f | 2023-11-09 14:43:28 +0000 | [diff] [blame] | 171 | let attestation_key = get_rkpd_attestation_key( |
| 172 | REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME, |
| 173 | requester_uid as u32, |
| 174 | ) |
| 175 | .context("Failed to retrieve the remotely provisioned keys") |
| 176 | .with_log() |
| 177 | .or_service_specific_exception(-1)?; |
| 178 | let certificate = request_attestation(csr, &attestation_key.keyBlob) |
Alice Wang | a410b64 | 2023-10-18 09:05:15 +0000 | [diff] [blame] | 179 | .context("Failed to request attestation") |
Alice Wang | e9ac2db | 2023-09-08 15:13:13 +0000 | [diff] [blame] | 180 | .with_log() |
Alice Wang | bff017f | 2023-11-09 14:43:28 +0000 | [diff] [blame] | 181 | .or_service_specific_exception(-1)?; |
| 182 | // TODO(b/309780089): Parse the remotely provisioned certificate chain into |
| 183 | // individual certificates. |
| 184 | let mut certificate_chain = |
| 185 | vec![Certificate { encodedCertificate: attestation_key.encodedCertChain }]; |
| 186 | certificate_chain.push(Certificate { encodedCertificate: certificate }); |
| 187 | Ok(certificate_chain) |
Alice Wang | e9ac2db | 2023-09-08 15:13:13 +0000 | [diff] [blame] | 188 | } else { |
| 189 | Err(Status::new_exception_str( |
| 190 | ExceptionCode::UNSUPPORTED_OPERATION, |
| 191 | Some( |
Alice Wang | a410b64 | 2023-10-18 09:05:15 +0000 | [diff] [blame] | 192 | "requestAttestation is not supported with the remote_attestation feature \ |
| 193 | disabled", |
Alice Wang | e9ac2db | 2023-09-08 15:13:13 +0000 | [diff] [blame] | 194 | ), |
| 195 | )) |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 196 | .with_log() |
Alice Wang | e9ac2db | 2023-09-08 15:13:13 +0000 | [diff] [blame] | 197 | } |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 198 | } |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 199 | |
| 200 | fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> { |
| 201 | check_use_custom_virtual_machine()?; |
| 202 | |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 203 | Ok(get_assignable_devices()? |
| 204 | .device |
| 205 | .into_iter() |
| 206 | .map(|x| AssignableDevice { node: x.sysfs_path, kind: x.kind }) |
| 207 | .collect::<Vec<_>>()) |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 208 | } |
Inseob Kim | 1ca0f65 | 2023-07-20 17:18:12 +0900 | [diff] [blame] | 209 | |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 210 | fn bindDevicesToVfioDriver(&self, devices: &[String]) -> binder::Result<Vec<BoundDevice>> { |
Inseob Kim | 1ca0f65 | 2023-07-20 17:18:12 +0900 | [diff] [blame] | 211 | check_use_custom_virtual_machine()?; |
| 212 | |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 213 | let vfio_service: Strong<dyn IVfioHandler> = |
| 214 | wait_for_interface(<BpVfioHandler as IVfioHandler>::get_descriptor())?; |
Inseob Kim | f36347b | 2023-08-03 12:52:48 +0900 | [diff] [blame] | 215 | |
Seungjae Yoo | 9d3c20a | 2023-09-07 15:36:44 +0900 | [diff] [blame] | 216 | vfio_service.bindDevicesToVfioDriver(devices)?; |
| 217 | |
| 218 | let dtbo_path = Path::new(TEMPORARY_DIRECTORY).join("common").join("dtbo"); |
| 219 | if !dtbo_path.exists() { |
| 220 | // open a writable file descriptor for vfio_handler |
| 221 | let dtbo = File::create(&dtbo_path) |
| 222 | .context("Failed to create VM DTBO file") |
| 223 | .or_service_specific_exception(-1)?; |
| 224 | vfio_service.writeVmDtbo(&ParcelFileDescriptor::new(dtbo))?; |
| 225 | } |
| 226 | |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 227 | Ok(get_assignable_devices()? |
| 228 | .device |
| 229 | .into_iter() |
| 230 | .filter_map(|x| { |
| 231 | if devices.contains(&x.sysfs_path) { |
Jaewan Kim | 35e818d | 2023-10-18 05:36:38 +0000 | [diff] [blame] | 232 | Some(BoundDevice { sysfsPath: x.sysfs_path, dtboLabel: x.dtbo_label }) |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 233 | } else { |
| 234 | None |
| 235 | } |
| 236 | }) |
| 237 | .collect::<Vec<_>>()) |
Inseob Kim | 1ca0f65 | 2023-07-20 17:18:12 +0900 | [diff] [blame] | 238 | } |
| 239 | } |
| 240 | |
Inseob Kim | c4a774d | 2023-08-30 12:48:43 +0900 | [diff] [blame] | 241 | // KEEP IN SYNC WITH assignable_devices.xsd |
| 242 | #[derive(Debug, Deserialize)] |
| 243 | struct Device { |
| 244 | kind: String, |
Jaewan Kim | 35e818d | 2023-10-18 05:36:38 +0000 | [diff] [blame] | 245 | dtbo_label: String, |
Inseob Kim | c4a774d | 2023-08-30 12:48:43 +0900 | [diff] [blame] | 246 | sysfs_path: String, |
| 247 | } |
| 248 | |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 249 | #[derive(Debug, Default, Deserialize)] |
Inseob Kim | c4a774d | 2023-08-30 12:48:43 +0900 | [diff] [blame] | 250 | struct Devices { |
| 251 | device: Vec<Device>, |
| 252 | } |
| 253 | |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 254 | fn get_assignable_devices() -> binder::Result<Devices> { |
| 255 | let xml_path = Path::new("/vendor/etc/avf/assignable_devices.xml"); |
| 256 | if !xml_path.exists() { |
| 257 | return Ok(Devices { ..Default::default() }); |
| 258 | } |
| 259 | |
| 260 | let xml = fs::read(xml_path) |
| 261 | .context("Failed to read assignable_devices.xml") |
| 262 | .with_log() |
| 263 | .or_service_specific_exception(-1)?; |
| 264 | |
| 265 | let xml = String::from_utf8(xml) |
| 266 | .context("assignable_devices.xml is not a valid UTF-8 file") |
| 267 | .with_log() |
| 268 | .or_service_specific_exception(-1)?; |
| 269 | |
| 270 | let mut devices: Devices = serde_xml_rs::from_str(&xml) |
| 271 | .context("can't parse assignable_devices.xml") |
| 272 | .with_log() |
| 273 | .or_service_specific_exception(-1)?; |
| 274 | |
| 275 | let mut device_set = HashSet::new(); |
| 276 | devices.device.retain(move |device| { |
| 277 | if device_set.contains(&device.sysfs_path) { |
| 278 | warn!("duplicated assignable device {device:?}; ignoring..."); |
| 279 | return false; |
| 280 | } |
| 281 | |
| 282 | if !Path::new(&device.sysfs_path).exists() { |
| 283 | warn!("assignable device {device:?} doesn't exist; ignoring..."); |
| 284 | return false; |
| 285 | } |
| 286 | |
| 287 | device_set.insert(device.sysfs_path.clone()); |
| 288 | true |
| 289 | }); |
| 290 | Ok(devices) |
| 291 | } |
| 292 | |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 293 | #[derive(Debug, Default)] |
| 294 | struct GlobalVmInstance { |
| 295 | /// The unique CID assigned to the VM for vsock communication. |
| 296 | cid: Cid, |
| 297 | /// UID of the client who requested this VM instance. |
| 298 | requester_uid: uid_t, |
| 299 | /// PID of the client who requested this VM instance. |
| 300 | requester_debug_pid: pid_t, |
| 301 | } |
| 302 | |
| 303 | impl GlobalVmInstance { |
| 304 | fn get_temp_dir(&self) -> PathBuf { |
| 305 | let cid = self.cid; |
| 306 | format!("{TEMPORARY_DIRECTORY}/{cid}").into() |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | /// The mutable state of the VirtualizationServiceInternal. There should only be one instance |
| 311 | /// of this struct. |
| 312 | #[derive(Debug, Default)] |
| 313 | struct GlobalState { |
| 314 | /// VM contexts currently allocated to running VMs. A CID is never recycled as long |
| 315 | /// as there is a strong reference held by a GlobalVmContext. |
| 316 | held_contexts: HashMap<Cid, Weak<GlobalVmInstance>>, |
| 317 | } |
| 318 | |
| 319 | impl GlobalState { |
| 320 | /// Get the next available CID, or an error if we have run out. The last CID used is stored in |
| 321 | /// a system property so that restart of virtualizationservice doesn't reuse CID while the host |
| 322 | /// Android is up. |
| 323 | fn get_next_available_cid(&mut self) -> Result<Cid> { |
| 324 | // Start trying to find a CID from the last used CID + 1. This ensures |
| 325 | // that we do not eagerly recycle CIDs. It makes debugging easier but |
| 326 | // also means that retrying to allocate a CID, eg. because it is |
| 327 | // erroneously occupied by a process, will not recycle the same CID. |
| 328 | let last_cid_prop = |
| 329 | system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() { |
| 330 | Ok(num) => { |
| 331 | if is_valid_guest_cid(num) { |
| 332 | Some(num) |
| 333 | } else { |
| 334 | error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID); |
| 335 | None |
| 336 | } |
| 337 | } |
| 338 | Err(_) => { |
| 339 | error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID); |
| 340 | None |
| 341 | } |
| 342 | }); |
| 343 | |
| 344 | let first_cid = if let Some(last_cid) = last_cid_prop { |
| 345 | if last_cid == GUEST_CID_MAX { |
| 346 | GUEST_CID_MIN |
| 347 | } else { |
| 348 | last_cid + 1 |
| 349 | } |
| 350 | } else { |
| 351 | GUEST_CID_MIN |
| 352 | }; |
| 353 | |
| 354 | let cid = self |
| 355 | .find_available_cid(first_cid..=GUEST_CID_MAX) |
| 356 | .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid)) |
| 357 | .ok_or_else(|| anyhow!("Could not find an available CID."))?; |
| 358 | |
| 359 | system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?; |
| 360 | Ok(cid) |
| 361 | } |
| 362 | |
| 363 | fn find_available_cid<I>(&self, mut range: I) -> Option<Cid> |
| 364 | where |
| 365 | I: Iterator<Item = Cid>, |
| 366 | { |
| 367 | range.find(|cid| !self.held_contexts.contains_key(cid)) |
| 368 | } |
| 369 | |
| 370 | fn allocate_vm_context( |
| 371 | &mut self, |
| 372 | requester_uid: uid_t, |
| 373 | requester_debug_pid: pid_t, |
| 374 | ) -> Result<Strong<dyn IGlobalVmContext>> { |
| 375 | // Garbage collect unused VM contexts. |
| 376 | self.held_contexts.retain(|_, instance| instance.strong_count() > 0); |
| 377 | |
| 378 | let cid = self.get_next_available_cid()?; |
| 379 | let instance = Arc::new(GlobalVmInstance { cid, requester_uid, requester_debug_pid }); |
| 380 | create_temporary_directory(&instance.get_temp_dir(), requester_uid)?; |
| 381 | |
| 382 | self.held_contexts.insert(cid, Arc::downgrade(&instance)); |
| 383 | let binder = GlobalVmContext { instance, ..Default::default() }; |
| 384 | Ok(BnGlobalVmContext::new_binder(binder, BinderFeatures::default())) |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | fn create_temporary_directory(path: &PathBuf, requester_uid: uid_t) -> Result<()> { |
| 389 | if path.as_path().exists() { |
| 390 | remove_temporary_dir(path).unwrap_or_else(|e| { |
| 391 | warn!("Could not delete temporary directory {:?}: {}", path, e); |
| 392 | }); |
| 393 | } |
| 394 | // Create a directory that is owned by client's UID but system's GID, and permissions 0700. |
| 395 | // If the chown() fails, this will leave behind an empty directory that will get removed |
| 396 | // at the next attempt, or if virtualizationservice is restarted. |
| 397 | create_dir(path).with_context(|| format!("Could not create temporary directory {:?}", path))?; |
| 398 | chown(path, Some(Uid::from_raw(requester_uid)), None) |
| 399 | .with_context(|| format!("Could not set ownership of temporary directory {:?}", path))?; |
| 400 | Ok(()) |
| 401 | } |
| 402 | |
| 403 | /// Removes a directory owned by a different user by first changing its owner back |
| 404 | /// to VirtualizationService. |
| 405 | pub fn remove_temporary_dir(path: &PathBuf) -> Result<()> { |
Alice Wang | d1b11a0 | 2023-04-18 12:30:20 +0000 | [diff] [blame] | 406 | ensure!(path.as_path().is_dir(), "Path {:?} is not a directory", path); |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 407 | chown(path, Some(Uid::current()), None)?; |
| 408 | set_permissions(path, Permissions::from_mode(0o700))?; |
Alice Wang | d1b11a0 | 2023-04-18 12:30:20 +0000 | [diff] [blame] | 409 | remove_dir_all(path)?; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 410 | Ok(()) |
| 411 | } |
| 412 | |
| 413 | /// Implementation of the AIDL `IGlobalVmContext` interface. |
| 414 | #[derive(Debug, Default)] |
| 415 | struct GlobalVmContext { |
| 416 | /// Strong reference to the context's instance data structure. |
| 417 | instance: Arc<GlobalVmInstance>, |
| 418 | /// Keeps our service process running as long as this VM context exists. |
| 419 | #[allow(dead_code)] |
| 420 | lazy_service_guard: LazyServiceGuard, |
| 421 | } |
| 422 | |
| 423 | impl Interface for GlobalVmContext {} |
| 424 | |
| 425 | impl IGlobalVmContext for GlobalVmContext { |
| 426 | fn getCid(&self) -> binder::Result<i32> { |
| 427 | Ok(self.instance.cid as i32) |
| 428 | } |
| 429 | |
| 430 | fn getTemporaryDirectory(&self) -> binder::Result<String> { |
| 431 | Ok(self.instance.get_temp_dir().to_string_lossy().to_string()) |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | fn handle_stream_connection_tombstoned() -> Result<()> { |
| 436 | // Should not listen for tombstones on a guest VM's port. |
| 437 | assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid)); |
| 438 | let listener = |
| 439 | VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?; |
| 440 | for incoming_stream in listener.incoming() { |
| 441 | let mut incoming_stream = match incoming_stream { |
| 442 | Err(e) => { |
| 443 | warn!("invalid incoming connection: {:?}", e); |
| 444 | continue; |
| 445 | } |
| 446 | Ok(s) => s, |
| 447 | }; |
| 448 | std::thread::spawn(move || { |
| 449 | if let Err(e) = handle_tombstone(&mut incoming_stream) { |
| 450 | error!("Failed to write tombstone- {:?}", e); |
| 451 | } |
| 452 | }); |
| 453 | } |
| 454 | Ok(()) |
| 455 | } |
| 456 | |
| 457 | fn handle_tombstone(stream: &mut VsockStream) -> Result<()> { |
| 458 | if let Ok(addr) = stream.peer_addr() { |
| 459 | info!("Vsock Stream connected to cid={} for tombstones", addr.cid()); |
| 460 | } |
| 461 | let tb_connection = |
| 462 | TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone) |
| 463 | .context("Failed to connect to tombstoned")?; |
| 464 | let mut text_output = tb_connection |
| 465 | .text_output |
| 466 | .as_ref() |
| 467 | .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?; |
| 468 | let mut num_bytes_read = 0; |
| 469 | loop { |
| 470 | let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN]; |
| 471 | let n = stream |
| 472 | .read(&mut chunk_recv) |
| 473 | .context("Failed to read tombstone data from Vsock stream")?; |
| 474 | if n == 0 { |
| 475 | break; |
| 476 | } |
| 477 | num_bytes_read += n; |
| 478 | text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?; |
| 479 | } |
| 480 | info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read); |
| 481 | tb_connection.notify_completion()?; |
| 482 | Ok(()) |
| 483 | } |
| 484 | |
| 485 | /// Checks whether the caller has a specific permission |
| 486 | fn check_permission(perm: &str) -> binder::Result<()> { |
| 487 | let calling_pid = get_calling_pid(); |
| 488 | let calling_uid = get_calling_uid(); |
| 489 | // Root can do anything |
| 490 | if calling_uid == 0 { |
| 491 | return Ok(()); |
| 492 | } |
| 493 | let perm_svc: Strong<dyn IPermissionController::IPermissionController> = |
| 494 | binder::get_interface("permission")?; |
| 495 | if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? { |
| 496 | Ok(()) |
| 497 | } else { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 498 | Err(anyhow!("does not have the {} permission", perm)) |
| 499 | .or_binder_exception(ExceptionCode::SECURITY) |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 500 | } |
| 501 | } |
| 502 | |
| 503 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
| 504 | fn check_debug_access() -> binder::Result<()> { |
| 505 | check_permission("android.permission.DEBUG_VIRTUAL_MACHINE") |
| 506 | } |
| 507 | |
| 508 | /// Check whether the caller of the current Binder method is allowed to manage VMs |
| 509 | fn check_manage_access() -> binder::Result<()> { |
| 510 | check_permission("android.permission.MANAGE_VIRTUAL_MACHINE") |
| 511 | } |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 512 | |
| 513 | /// Check whether the caller of the current Binder method is allowed to use custom VMs |
| 514 | fn check_use_custom_virtual_machine() -> binder::Result<()> { |
| 515 | check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE") |
| 516 | } |