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