blob: b2513d94034dfcc910a98fbe08febf7c1a8589d5 [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 Kim6ef80972023-07-20 17:23:36 +090041use std::collections::HashMap;
Inseob Kimbdca0472023-07-28 19:20:56 +090042use std::fs::{create_dir, remove_dir_all, set_permissions, Permissions};
David Brazdilafc9a9e2023-01-12 16:08:10 +000043use std::io::{Read, Write};
44use std::os::unix::fs::PermissionsExt;
45use std::os::unix::raw::{pid_t, uid_t};
Inseob Kim55438b22023-08-09 20:16:01 +090046use std::path::{Path, PathBuf};
David Brazdilafc9a9e2023-01-12 16:08:10 +000047use std::sync::{Arc, Mutex, Weak};
48use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
49use vsock::{VsockListener, VsockStream};
Inseob Kimbdca0472023-07-28 19:20:56 +090050use nix::unistd::{chown, Uid};
David Brazdilafc9a9e2023-01-12 16:08:10 +000051
52/// The unique ID of a VM used (together with a port number) for vsock communication.
53pub type Cid = u32;
54
55pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
56
57/// Directory in which to write disk image files used while running VMs.
58pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
59
60/// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this
61/// are reserved for the host or other usage.
62const GUEST_CID_MIN: Cid = 2048;
63const GUEST_CID_MAX: Cid = 65535;
64
65const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
66
67const CHUNK_RECV_MAX_LEN: usize = 1024;
68
69fn is_valid_guest_cid(cid: Cid) -> bool {
70 (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
71}
72
73/// Singleton service for allocating globally-unique VM resources, such as the CID, and running
74/// singleton servers, like tombstone receiver.
75#[derive(Debug, Default)]
76pub struct VirtualizationServiceInternal {
77 state: Arc<Mutex<GlobalState>>,
78}
79
80impl VirtualizationServiceInternal {
81 pub fn init() -> VirtualizationServiceInternal {
82 let service = VirtualizationServiceInternal::default();
83
84 std::thread::spawn(|| {
85 if let Err(e) = handle_stream_connection_tombstoned() {
86 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
87 }
88 });
89
90 service
91 }
92}
93
94impl Interface for VirtualizationServiceInternal {}
95
96impl IVirtualizationServiceInternal for VirtualizationServiceInternal {
97 fn removeMemlockRlimit(&self) -> binder::Result<()> {
98 let pid = get_calling_pid();
99 let lim = libc::rlimit { rlim_cur: libc::RLIM_INFINITY, rlim_max: libc::RLIM_INFINITY };
100
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100101 // SAFETY: borrowing the new limit struct only
David Brazdilafc9a9e2023-01-12 16:08:10 +0000102 let ret = unsafe { libc::prlimit(pid, libc::RLIMIT_MEMLOCK, &lim, std::ptr::null_mut()) };
103
104 match ret {
105 0 => Ok(()),
Jiyong Park2227eaa2023-08-04 11:59:18 +0900106 -1 => Err(std::io::Error::last_os_error().into()),
107 n => Err(anyhow!("Unexpected return value from prlimit(): {n}")),
David Brazdilafc9a9e2023-01-12 16:08:10 +0000108 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900109 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000110 }
111
112 fn allocateGlobalVmContext(
113 &self,
114 requester_debug_pid: i32,
115 ) -> binder::Result<Strong<dyn IGlobalVmContext>> {
116 check_manage_access()?;
117
118 let requester_uid = get_calling_uid();
119 let requester_debug_pid = requester_debug_pid as pid_t;
120 let state = &mut *self.state.lock().unwrap();
Jiyong Park2227eaa2023-08-04 11:59:18 +0900121 state
122 .allocate_vm_context(requester_uid, requester_debug_pid)
123 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000124 }
125
126 fn atomVmBooted(&self, atom: &AtomVmBooted) -> Result<(), Status> {
127 forward_vm_booted_atom(atom);
128 Ok(())
129 }
130
131 fn atomVmCreationRequested(&self, atom: &AtomVmCreationRequested) -> Result<(), Status> {
132 forward_vm_creation_atom(atom);
133 Ok(())
134 }
135
136 fn atomVmExited(&self, atom: &AtomVmExited) -> Result<(), Status> {
137 forward_vm_exited_atom(atom);
138 Ok(())
139 }
140
141 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
142 check_debug_access()?;
143
144 let state = &mut *self.state.lock().unwrap();
145 let cids = state
146 .held_contexts
147 .iter()
148 .filter_map(|(_, inst)| Weak::upgrade(inst))
149 .map(|vm| VirtualMachineDebugInfo {
150 cid: vm.cid as i32,
151 temporaryDirectory: vm.get_temp_dir().to_string_lossy().to_string(),
152 requesterUid: vm.requester_uid as i32,
Charisee96113f32023-01-26 09:00:42 +0000153 requesterPid: vm.requester_debug_pid,
David Brazdilafc9a9e2023-01-12 16:08:10 +0000154 })
155 .collect();
156 Ok(cids)
157 }
Alice Wangc2fec932023-02-23 16:24:02 +0000158
159 fn requestCertificate(
160 &self,
161 csr: &[u8],
162 instance_img_fd: &ParcelFileDescriptor,
163 ) -> binder::Result<Vec<u8>> {
164 check_manage_access()?;
165 info!("Received csr. Getting certificate...");
Jiyong Park2227eaa2023-08-04 11:59:18 +0900166 request_certificate(csr, instance_img_fd)
167 .context("Failed to get certificate")
168 .with_log()
169 .or_service_specific_exception(-1)
Alice Wangc2fec932023-02-23 16:24:02 +0000170 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900171
172 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
173 check_use_custom_virtual_machine()?;
174
175 // TODO(b/291191362): read VM DTBO to find assignable devices.
Inseob Kim55438b22023-08-09 20:16:01 +0900176 let mut devices = Vec::new();
177 let eh_path = "/sys/bus/platform/devices/16d00000.eh";
178 if Path::new(eh_path).exists() {
179 devices.push(AssignableDevice { kind: "eh".to_owned(), node: eh_path.to_owned() });
180 }
181 Ok(devices)
Inseob Kim53d0b212023-07-20 16:58:37 +0900182 }
Inseob Kim1ca0f652023-07-20 17:18:12 +0900183
Inseob Kimf36347b2023-08-03 12:52:48 +0900184 fn bindDevicesToVfioDriver(
185 &self,
186 devices: &[String],
187 dtbo: &ParcelFileDescriptor,
188 ) -> binder::Result<()> {
Inseob Kim1ca0f652023-07-20 17:18:12 +0900189 check_use_custom_virtual_machine()?;
190
Inseob Kimbdca0472023-07-28 19:20:56 +0900191 let vfio_service: Strong<dyn IVfioHandler> =
192 wait_for_interface(<BpVfioHandler as IVfioHandler>::get_descriptor())?;
Inseob Kimf36347b2023-08-03 12:52:48 +0900193
194 vfio_service.bindDevicesToVfioDriver(devices, dtbo)?;
195 Ok(())
Inseob Kim1ca0f652023-07-20 17:18:12 +0900196 }
197}
198
David Brazdilafc9a9e2023-01-12 16:08:10 +0000199#[derive(Debug, Default)]
200struct GlobalVmInstance {
201 /// The unique CID assigned to the VM for vsock communication.
202 cid: Cid,
203 /// UID of the client who requested this VM instance.
204 requester_uid: uid_t,
205 /// PID of the client who requested this VM instance.
206 requester_debug_pid: pid_t,
207}
208
209impl GlobalVmInstance {
210 fn get_temp_dir(&self) -> PathBuf {
211 let cid = self.cid;
212 format!("{TEMPORARY_DIRECTORY}/{cid}").into()
213 }
214}
215
216/// The mutable state of the VirtualizationServiceInternal. There should only be one instance
217/// of this struct.
218#[derive(Debug, Default)]
219struct GlobalState {
220 /// VM contexts currently allocated to running VMs. A CID is never recycled as long
221 /// as there is a strong reference held by a GlobalVmContext.
222 held_contexts: HashMap<Cid, Weak<GlobalVmInstance>>,
223}
224
225impl GlobalState {
226 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
227 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
228 /// Android is up.
229 fn get_next_available_cid(&mut self) -> Result<Cid> {
230 // Start trying to find a CID from the last used CID + 1. This ensures
231 // that we do not eagerly recycle CIDs. It makes debugging easier but
232 // also means that retrying to allocate a CID, eg. because it is
233 // erroneously occupied by a process, will not recycle the same CID.
234 let last_cid_prop =
235 system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() {
236 Ok(num) => {
237 if is_valid_guest_cid(num) {
238 Some(num)
239 } else {
240 error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID);
241 None
242 }
243 }
244 Err(_) => {
245 error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID);
246 None
247 }
248 });
249
250 let first_cid = if let Some(last_cid) = last_cid_prop {
251 if last_cid == GUEST_CID_MAX {
252 GUEST_CID_MIN
253 } else {
254 last_cid + 1
255 }
256 } else {
257 GUEST_CID_MIN
258 };
259
260 let cid = self
261 .find_available_cid(first_cid..=GUEST_CID_MAX)
262 .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid))
263 .ok_or_else(|| anyhow!("Could not find an available CID."))?;
264
265 system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
266 Ok(cid)
267 }
268
269 fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
270 where
271 I: Iterator<Item = Cid>,
272 {
273 range.find(|cid| !self.held_contexts.contains_key(cid))
274 }
275
276 fn allocate_vm_context(
277 &mut self,
278 requester_uid: uid_t,
279 requester_debug_pid: pid_t,
280 ) -> Result<Strong<dyn IGlobalVmContext>> {
281 // Garbage collect unused VM contexts.
282 self.held_contexts.retain(|_, instance| instance.strong_count() > 0);
283
284 let cid = self.get_next_available_cid()?;
285 let instance = Arc::new(GlobalVmInstance { cid, requester_uid, requester_debug_pid });
286 create_temporary_directory(&instance.get_temp_dir(), requester_uid)?;
287
288 self.held_contexts.insert(cid, Arc::downgrade(&instance));
289 let binder = GlobalVmContext { instance, ..Default::default() };
290 Ok(BnGlobalVmContext::new_binder(binder, BinderFeatures::default()))
291 }
292}
293
294fn create_temporary_directory(path: &PathBuf, requester_uid: uid_t) -> Result<()> {
295 if path.as_path().exists() {
296 remove_temporary_dir(path).unwrap_or_else(|e| {
297 warn!("Could not delete temporary directory {:?}: {}", path, e);
298 });
299 }
300 // Create a directory that is owned by client's UID but system's GID, and permissions 0700.
301 // If the chown() fails, this will leave behind an empty directory that will get removed
302 // at the next attempt, or if virtualizationservice is restarted.
303 create_dir(path).with_context(|| format!("Could not create temporary directory {:?}", path))?;
304 chown(path, Some(Uid::from_raw(requester_uid)), None)
305 .with_context(|| format!("Could not set ownership of temporary directory {:?}", path))?;
306 Ok(())
307}
308
309/// Removes a directory owned by a different user by first changing its owner back
310/// to VirtualizationService.
311pub fn remove_temporary_dir(path: &PathBuf) -> Result<()> {
Alice Wangd1b11a02023-04-18 12:30:20 +0000312 ensure!(path.as_path().is_dir(), "Path {:?} is not a directory", path);
David Brazdilafc9a9e2023-01-12 16:08:10 +0000313 chown(path, Some(Uid::current()), None)?;
314 set_permissions(path, Permissions::from_mode(0o700))?;
Alice Wangd1b11a02023-04-18 12:30:20 +0000315 remove_dir_all(path)?;
David Brazdilafc9a9e2023-01-12 16:08:10 +0000316 Ok(())
317}
318
319/// Implementation of the AIDL `IGlobalVmContext` interface.
320#[derive(Debug, Default)]
321struct GlobalVmContext {
322 /// Strong reference to the context's instance data structure.
323 instance: Arc<GlobalVmInstance>,
324 /// Keeps our service process running as long as this VM context exists.
325 #[allow(dead_code)]
326 lazy_service_guard: LazyServiceGuard,
327}
328
329impl Interface for GlobalVmContext {}
330
331impl IGlobalVmContext for GlobalVmContext {
332 fn getCid(&self) -> binder::Result<i32> {
333 Ok(self.instance.cid as i32)
334 }
335
336 fn getTemporaryDirectory(&self) -> binder::Result<String> {
337 Ok(self.instance.get_temp_dir().to_string_lossy().to_string())
338 }
339}
340
341fn handle_stream_connection_tombstoned() -> Result<()> {
342 // Should not listen for tombstones on a guest VM's port.
343 assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
344 let listener =
345 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?;
346 for incoming_stream in listener.incoming() {
347 let mut incoming_stream = match incoming_stream {
348 Err(e) => {
349 warn!("invalid incoming connection: {:?}", e);
350 continue;
351 }
352 Ok(s) => s,
353 };
354 std::thread::spawn(move || {
355 if let Err(e) = handle_tombstone(&mut incoming_stream) {
356 error!("Failed to write tombstone- {:?}", e);
357 }
358 });
359 }
360 Ok(())
361}
362
363fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
364 if let Ok(addr) = stream.peer_addr() {
365 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
366 }
367 let tb_connection =
368 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
369 .context("Failed to connect to tombstoned")?;
370 let mut text_output = tb_connection
371 .text_output
372 .as_ref()
373 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
374 let mut num_bytes_read = 0;
375 loop {
376 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
377 let n = stream
378 .read(&mut chunk_recv)
379 .context("Failed to read tombstone data from Vsock stream")?;
380 if n == 0 {
381 break;
382 }
383 num_bytes_read += n;
384 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
385 }
386 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
387 tb_connection.notify_completion()?;
388 Ok(())
389}
390
391/// Checks whether the caller has a specific permission
392fn check_permission(perm: &str) -> binder::Result<()> {
393 let calling_pid = get_calling_pid();
394 let calling_uid = get_calling_uid();
395 // Root can do anything
396 if calling_uid == 0 {
397 return Ok(());
398 }
399 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
400 binder::get_interface("permission")?;
401 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
402 Ok(())
403 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900404 Err(anyhow!("does not have the {} permission", perm))
405 .or_binder_exception(ExceptionCode::SECURITY)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000406 }
407}
408
409/// Check whether the caller of the current Binder method is allowed to call debug methods.
410fn check_debug_access() -> binder::Result<()> {
411 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
412}
413
414/// Check whether the caller of the current Binder method is allowed to manage VMs
415fn check_manage_access() -> binder::Result<()> {
416 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
417}
Inseob Kim53d0b212023-07-20 16:58:37 +0900418
419/// Check whether the caller of the current Binder method is allowed to use custom VMs
420fn check_use_custom_virtual_machine() -> binder::Result<()> {
421 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
422}