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