blob: 645a82b117584197bf1f53081de2b225b2df7b85 [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},
31 IVirtualizationServiceInternal::IVirtualizationServiceInternal,
Inseob Kimbdca0472023-07-28 19:20:56 +090032 IVfioHandler::{BpVfioHandler, IVfioHandler},
David Brazdilafc9a9e2023-01-12 16:08:10 +000033};
34use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::VM_TOMBSTONES_SERVICE_PORT;
Alice Wangd1b11a02023-04-18 12:30:20 +000035use anyhow::{anyhow, ensure, Context, Result};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090036use avflog::LogResult;
Jiyong Park2227eaa2023-08-04 11:59:18 +090037use binder::{self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, Status, Strong, IntoBinderResult};
David Brazdilafc9a9e2023-01-12 16:08:10 +000038use libc::VMADDR_CID_HOST;
39use log::{error, info, warn};
40use rustutils::system_properties;
Inseob Kimc4a774d2023-08-30 12:48:43 +090041use serde::Deserialize;
42use std::collections::{HashMap, HashSet};
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +090043use std::fs::{self, create_dir, remove_dir_all, set_permissions, File, Permissions};
David Brazdilafc9a9e2023-01-12 16:08:10 +000044use std::io::{Read, Write};
45use std::os::unix::fs::PermissionsExt;
46use std::os::unix::raw::{pid_t, uid_t};
Inseob Kim55438b22023-08-09 20:16:01 +090047use std::path::{Path, PathBuf};
David Brazdilafc9a9e2023-01-12 16:08:10 +000048use std::sync::{Arc, Mutex, Weak};
49use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
50use vsock::{VsockListener, VsockStream};
Inseob Kimbdca0472023-07-28 19:20:56 +090051use nix::unistd::{chown, Uid};
David Brazdilafc9a9e2023-01-12 16:08:10 +000052
53/// The unique ID of a VM used (together with a port number) for vsock communication.
54pub type Cid = u32;
55
56pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
57
58/// Directory in which to write disk image files used while running VMs.
59pub 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.
63const GUEST_CID_MIN: Cid = 2048;
64const GUEST_CID_MAX: Cid = 65535;
65
66const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
67
68const CHUNK_RECV_MAX_LEN: usize = 1024;
69
70fn 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)]
77pub struct VirtualizationServiceInternal {
78 state: Arc<Mutex<GlobalState>>,
79}
80
81impl 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
95impl Interface for VirtualizationServiceInternal {}
96
97impl 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 Walbranb58d1b42023-07-07 13:54:49 +0100102 // SAFETY: borrowing the new limit struct only
David Brazdilafc9a9e2023-01-12 16:08:10 +0000103 let ret = unsafe { libc::prlimit(pid, libc::RLIMIT_MEMLOCK, &lim, std::ptr::null_mut()) };
104
105 match ret {
106 0 => Ok(()),
Jiyong Park2227eaa2023-08-04 11:59:18 +0900107 -1 => Err(std::io::Error::last_os_error().into()),
108 n => Err(anyhow!("Unexpected return value from prlimit(): {n}")),
David Brazdilafc9a9e2023-01-12 16:08:10 +0000109 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900110 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000111 }
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 Park2227eaa2023-08-04 11:59:18 +0900122 state
123 .allocate_vm_context(requester_uid, requester_debug_pid)
124 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000125 }
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,
Charisee96113f32023-01-26 09:00:42 +0000154 requesterPid: vm.requester_debug_pid,
David Brazdilafc9a9e2023-01-12 16:08:10 +0000155 })
156 .collect();
157 Ok(cids)
158 }
Alice Wangc2fec932023-02-23 16:24:02 +0000159
Alice Wangc206b9b2023-08-28 14:13:51 +0000160 fn requestCertificate(&self, csr: &[u8]) -> binder::Result<Vec<u8>> {
Alice Wangc2fec932023-02-23 16:24:02 +0000161 check_manage_access()?;
162 info!("Received csr. Getting certificate...");
Alice Wange9ac2db2023-09-08 15:13:13 +0000163 if cfg!(remote_attestation) {
164 request_certificate(csr)
165 .context("Failed to get certificate")
166 .with_log()
167 .or_service_specific_exception(-1)
168 } else {
169 Err(Status::new_exception_str(
170 ExceptionCode::UNSUPPORTED_OPERATION,
171 Some(
172 "requestCertificate is not supported with the remote_attestation feature disabled",
173 ),
174 ))
Jiyong Park2227eaa2023-08-04 11:59:18 +0900175 .with_log()
Alice Wange9ac2db2023-09-08 15:13:13 +0000176 }
Alice Wangc2fec932023-02-23 16:24:02 +0000177 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900178
179 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
180 check_use_custom_virtual_machine()?;
181
Inseob Kimc4a774d2023-08-30 12:48:43 +0900182 let mut ret = Vec::new();
183 let xml_path = Path::new("/vendor/etc/avf/assignable_devices.xml");
184 if !xml_path.exists() {
185 return Ok(ret);
Inseob Kim55438b22023-08-09 20:16:01 +0900186 }
Inseob Kimc4a774d2023-08-30 12:48:43 +0900187
188 let xml = fs::read(xml_path)
189 .context("Failed to read assignable_devices.xml")
190 .with_log()
191 .or_service_specific_exception(-1)?;
192
193 let xml = String::from_utf8(xml)
194 .context("assignable_devices.xml is not a valid UTF-8 file")
195 .with_log()
196 .or_service_specific_exception(-1)?;
197
198 let devices: Devices = serde_xml_rs::from_str(&xml)
199 .context("can't parse assignable_devices.xml")
200 .with_log()
201 .or_service_specific_exception(-1)?;
202
203 let mut device_set = HashSet::new();
204
205 for device in devices.device.into_iter() {
206 if device_set.contains(&device.sysfs_path) {
207 warn!("duplicated assignable device {device:?}; ignoring...")
208 } else if Path::new(&device.sysfs_path).exists() {
209 device_set.insert(device.sysfs_path.clone());
210 ret.push(AssignableDevice { kind: device.kind, node: device.sysfs_path });
211 } else {
212 warn!("assignable device {device:?} doesn't exist; ignoring...");
213 }
214 }
215
216 Ok(ret)
Inseob Kim53d0b212023-07-20 16:58:37 +0900217 }
Inseob Kim1ca0f652023-07-20 17:18:12 +0900218
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900219 fn bindDevicesToVfioDriver(&self, devices: &[String]) -> binder::Result<()> {
Inseob Kim1ca0f652023-07-20 17:18:12 +0900220 check_use_custom_virtual_machine()?;
221
Inseob Kimbdca0472023-07-28 19:20:56 +0900222 let vfio_service: Strong<dyn IVfioHandler> =
223 wait_for_interface(<BpVfioHandler as IVfioHandler>::get_descriptor())?;
Inseob Kimf36347b2023-08-03 12:52:48 +0900224
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900225 vfio_service.bindDevicesToVfioDriver(devices)?;
226
227 let dtbo_path = Path::new(TEMPORARY_DIRECTORY).join("common").join("dtbo");
228 if !dtbo_path.exists() {
229 // open a writable file descriptor for vfio_handler
230 let dtbo = File::create(&dtbo_path)
231 .context("Failed to create VM DTBO file")
232 .or_service_specific_exception(-1)?;
233 vfio_service.writeVmDtbo(&ParcelFileDescriptor::new(dtbo))?;
234 }
235
Inseob Kimf36347b2023-08-03 12:52:48 +0900236 Ok(())
Inseob Kim1ca0f652023-07-20 17:18:12 +0900237 }
238}
239
Inseob Kimc4a774d2023-08-30 12:48:43 +0900240// KEEP IN SYNC WITH assignable_devices.xsd
241#[derive(Debug, Deserialize)]
242struct Device {
243 kind: String,
244 sysfs_path: String,
245}
246
247#[derive(Debug, Deserialize)]
248struct Devices {
249 device: Vec<Device>,
250}
251
David Brazdilafc9a9e2023-01-12 16:08:10 +0000252#[derive(Debug, Default)]
253struct GlobalVmInstance {
254 /// The unique CID assigned to the VM for vsock communication.
255 cid: Cid,
256 /// UID of the client who requested this VM instance.
257 requester_uid: uid_t,
258 /// PID of the client who requested this VM instance.
259 requester_debug_pid: pid_t,
260}
261
262impl GlobalVmInstance {
263 fn get_temp_dir(&self) -> PathBuf {
264 let cid = self.cid;
265 format!("{TEMPORARY_DIRECTORY}/{cid}").into()
266 }
267}
268
269/// The mutable state of the VirtualizationServiceInternal. There should only be one instance
270/// of this struct.
271#[derive(Debug, Default)]
272struct GlobalState {
273 /// VM contexts currently allocated to running VMs. A CID is never recycled as long
274 /// as there is a strong reference held by a GlobalVmContext.
275 held_contexts: HashMap<Cid, Weak<GlobalVmInstance>>,
276}
277
278impl GlobalState {
279 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
280 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
281 /// Android is up.
282 fn get_next_available_cid(&mut self) -> Result<Cid> {
283 // Start trying to find a CID from the last used CID + 1. This ensures
284 // that we do not eagerly recycle CIDs. It makes debugging easier but
285 // also means that retrying to allocate a CID, eg. because it is
286 // erroneously occupied by a process, will not recycle the same CID.
287 let last_cid_prop =
288 system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() {
289 Ok(num) => {
290 if is_valid_guest_cid(num) {
291 Some(num)
292 } else {
293 error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID);
294 None
295 }
296 }
297 Err(_) => {
298 error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID);
299 None
300 }
301 });
302
303 let first_cid = if let Some(last_cid) = last_cid_prop {
304 if last_cid == GUEST_CID_MAX {
305 GUEST_CID_MIN
306 } else {
307 last_cid + 1
308 }
309 } else {
310 GUEST_CID_MIN
311 };
312
313 let cid = self
314 .find_available_cid(first_cid..=GUEST_CID_MAX)
315 .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid))
316 .ok_or_else(|| anyhow!("Could not find an available CID."))?;
317
318 system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
319 Ok(cid)
320 }
321
322 fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
323 where
324 I: Iterator<Item = Cid>,
325 {
326 range.find(|cid| !self.held_contexts.contains_key(cid))
327 }
328
329 fn allocate_vm_context(
330 &mut self,
331 requester_uid: uid_t,
332 requester_debug_pid: pid_t,
333 ) -> Result<Strong<dyn IGlobalVmContext>> {
334 // Garbage collect unused VM contexts.
335 self.held_contexts.retain(|_, instance| instance.strong_count() > 0);
336
337 let cid = self.get_next_available_cid()?;
338 let instance = Arc::new(GlobalVmInstance { cid, requester_uid, requester_debug_pid });
339 create_temporary_directory(&instance.get_temp_dir(), requester_uid)?;
340
341 self.held_contexts.insert(cid, Arc::downgrade(&instance));
342 let binder = GlobalVmContext { instance, ..Default::default() };
343 Ok(BnGlobalVmContext::new_binder(binder, BinderFeatures::default()))
344 }
345}
346
347fn create_temporary_directory(path: &PathBuf, requester_uid: uid_t) -> Result<()> {
348 if path.as_path().exists() {
349 remove_temporary_dir(path).unwrap_or_else(|e| {
350 warn!("Could not delete temporary directory {:?}: {}", path, e);
351 });
352 }
353 // Create a directory that is owned by client's UID but system's GID, and permissions 0700.
354 // If the chown() fails, this will leave behind an empty directory that will get removed
355 // at the next attempt, or if virtualizationservice is restarted.
356 create_dir(path).with_context(|| format!("Could not create temporary directory {:?}", path))?;
357 chown(path, Some(Uid::from_raw(requester_uid)), None)
358 .with_context(|| format!("Could not set ownership of temporary directory {:?}", path))?;
359 Ok(())
360}
361
362/// Removes a directory owned by a different user by first changing its owner back
363/// to VirtualizationService.
364pub fn remove_temporary_dir(path: &PathBuf) -> Result<()> {
Alice Wangd1b11a02023-04-18 12:30:20 +0000365 ensure!(path.as_path().is_dir(), "Path {:?} is not a directory", path);
David Brazdilafc9a9e2023-01-12 16:08:10 +0000366 chown(path, Some(Uid::current()), None)?;
367 set_permissions(path, Permissions::from_mode(0o700))?;
Alice Wangd1b11a02023-04-18 12:30:20 +0000368 remove_dir_all(path)?;
David Brazdilafc9a9e2023-01-12 16:08:10 +0000369 Ok(())
370}
371
372/// Implementation of the AIDL `IGlobalVmContext` interface.
373#[derive(Debug, Default)]
374struct GlobalVmContext {
375 /// Strong reference to the context's instance data structure.
376 instance: Arc<GlobalVmInstance>,
377 /// Keeps our service process running as long as this VM context exists.
378 #[allow(dead_code)]
379 lazy_service_guard: LazyServiceGuard,
380}
381
382impl Interface for GlobalVmContext {}
383
384impl IGlobalVmContext for GlobalVmContext {
385 fn getCid(&self) -> binder::Result<i32> {
386 Ok(self.instance.cid as i32)
387 }
388
389 fn getTemporaryDirectory(&self) -> binder::Result<String> {
390 Ok(self.instance.get_temp_dir().to_string_lossy().to_string())
391 }
392}
393
394fn handle_stream_connection_tombstoned() -> Result<()> {
395 // Should not listen for tombstones on a guest VM's port.
396 assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
397 let listener =
398 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?;
399 for incoming_stream in listener.incoming() {
400 let mut incoming_stream = match incoming_stream {
401 Err(e) => {
402 warn!("invalid incoming connection: {:?}", e);
403 continue;
404 }
405 Ok(s) => s,
406 };
407 std::thread::spawn(move || {
408 if let Err(e) = handle_tombstone(&mut incoming_stream) {
409 error!("Failed to write tombstone- {:?}", e);
410 }
411 });
412 }
413 Ok(())
414}
415
416fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
417 if let Ok(addr) = stream.peer_addr() {
418 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
419 }
420 let tb_connection =
421 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
422 .context("Failed to connect to tombstoned")?;
423 let mut text_output = tb_connection
424 .text_output
425 .as_ref()
426 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
427 let mut num_bytes_read = 0;
428 loop {
429 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
430 let n = stream
431 .read(&mut chunk_recv)
432 .context("Failed to read tombstone data from Vsock stream")?;
433 if n == 0 {
434 break;
435 }
436 num_bytes_read += n;
437 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
438 }
439 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
440 tb_connection.notify_completion()?;
441 Ok(())
442}
443
444/// Checks whether the caller has a specific permission
445fn check_permission(perm: &str) -> binder::Result<()> {
446 let calling_pid = get_calling_pid();
447 let calling_uid = get_calling_uid();
448 // Root can do anything
449 if calling_uid == 0 {
450 return Ok(());
451 }
452 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
453 binder::get_interface("permission")?;
454 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
455 Ok(())
456 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900457 Err(anyhow!("does not have the {} permission", perm))
458 .or_binder_exception(ExceptionCode::SECURITY)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000459 }
460}
461
462/// Check whether the caller of the current Binder method is allowed to call debug methods.
463fn check_debug_access() -> binder::Result<()> {
464 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
465}
466
467/// Check whether the caller of the current Binder method is allowed to manage VMs
468fn check_manage_access() -> binder::Result<()> {
469 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
470}
Inseob Kim53d0b212023-07-20 16:58:37 +0900471
472/// Check whether the caller of the current Binder method is allowed to use custom VMs
473fn check_use_custom_virtual_machine() -> binder::Result<()> {
474 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
475}