blob: 938225ebbc599449c74e58574d689bc39d78cf27 [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
Alice Wangbff017f2023-11-09 14:43:28 +000017use crate::{get_calling_pid, get_calling_uid, REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME};
David Brazdil33a31022023-01-12 16:55:16 +000018use crate::atom::{forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_atom};
Alice Wanga410b642023-10-18 09:05:15 +000019use crate::rkpvm::request_attestation;
David Brazdilafc9a9e2023-01-12 16:08:10 +000020use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Alice Wang4e3015d2023-10-10 09:35:37 +000021use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::Certificate::Certificate;
Alice Wangc2fec932023-02-23 16:24:02 +000022use android_system_virtualizationservice::{
Inseob Kim53d0b212023-07-20 16:58:37 +090023 aidl::android::system::virtualizationservice::AssignableDevice::AssignableDevice,
Alice Wangc2fec932023-02-23 16:24:02 +000024 aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo,
25 binder::ParcelFileDescriptor,
26};
David Brazdilafc9a9e2023-01-12 16:08:10 +000027use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::{
28 AtomVmBooted::AtomVmBooted,
29 AtomVmCreationRequested::AtomVmCreationRequested,
30 AtomVmExited::AtomVmExited,
31 IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext},
Inseob Kim7307a892023-09-14 13:37:58 +090032 IVirtualizationServiceInternal::BoundDevice::BoundDevice,
David Brazdilafc9a9e2023-01-12 16:08:10 +000033 IVirtualizationServiceInternal::IVirtualizationServiceInternal,
Inseob Kimbdca0472023-07-28 19:20:56 +090034 IVfioHandler::{BpVfioHandler, IVfioHandler},
David Brazdilafc9a9e2023-01-12 16:08:10 +000035};
36use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::VM_TOMBSTONES_SERVICE_PORT;
Alice Wangd1b11a02023-04-18 12:30:20 +000037use anyhow::{anyhow, ensure, Context, Result};
Jiyong Parkd7bd2f22023-08-10 20:41:19 +090038use avflog::LogResult;
Jiyong Park2227eaa2023-08-04 11:59:18 +090039use binder::{self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, LazyServiceGuard, Status, Strong, IntoBinderResult};
David Brazdilafc9a9e2023-01-12 16:08:10 +000040use libc::VMADDR_CID_HOST;
41use log::{error, info, warn};
Alice Wangbff017f2023-11-09 14:43:28 +000042use rkpd_client::get_rkpd_attestation_key;
David Brazdilafc9a9e2023-01-12 16:08:10 +000043use rustutils::system_properties;
Inseob Kimc4a774d2023-08-30 12:48:43 +090044use serde::Deserialize;
45use std::collections::{HashMap, HashSet};
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +090046use std::fs::{self, create_dir, remove_dir_all, set_permissions, File, Permissions};
David Brazdilafc9a9e2023-01-12 16:08:10 +000047use std::io::{Read, Write};
48use std::os::unix::fs::PermissionsExt;
49use std::os::unix::raw::{pid_t, uid_t};
Inseob Kim55438b22023-08-09 20:16:01 +090050use std::path::{Path, PathBuf};
David Brazdilafc9a9e2023-01-12 16:08:10 +000051use std::sync::{Arc, Mutex, Weak};
52use tombstoned_client::{DebuggerdDumpType, TombstonedConnection};
53use vsock::{VsockListener, VsockStream};
Inseob Kimbdca0472023-07-28 19:20:56 +090054use nix::unistd::{chown, Uid};
David Brazdilafc9a9e2023-01-12 16:08:10 +000055
56/// The unique ID of a VM used (together with a port number) for vsock communication.
57pub type Cid = u32;
58
59pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
60
61/// Directory in which to write disk image files used while running VMs.
62pub 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.
66const GUEST_CID_MIN: Cid = 2048;
67const GUEST_CID_MAX: Cid = 65535;
68
69const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
70
71const CHUNK_RECV_MAX_LEN: usize = 1024;
72
73fn 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)]
80pub struct VirtualizationServiceInternal {
81 state: Arc<Mutex<GlobalState>>,
82}
83
84impl 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
98impl Interface for VirtualizationServiceInternal {}
99
100impl 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 Walbranb58d1b42023-07-07 13:54:49 +0100105 // SAFETY: borrowing the new limit struct only
David Brazdilafc9a9e2023-01-12 16:08:10 +0000106 let ret = unsafe { libc::prlimit(pid, libc::RLIMIT_MEMLOCK, &lim, std::ptr::null_mut()) };
107
108 match ret {
109 0 => Ok(()),
Jiyong Park2227eaa2023-08-04 11:59:18 +0900110 -1 => Err(std::io::Error::last_os_error().into()),
111 n => Err(anyhow!("Unexpected return value from prlimit(): {n}")),
David Brazdilafc9a9e2023-01-12 16:08:10 +0000112 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900113 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000114 }
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 Park2227eaa2023-08-04 11:59:18 +0900125 state
126 .allocate_vm_context(requester_uid, requester_debug_pid)
127 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000128 }
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,
Charisee96113f32023-01-26 09:00:42 +0000157 requesterPid: vm.requester_debug_pid,
David Brazdilafc9a9e2023-01-12 16:08:10 +0000158 })
159 .collect();
160 Ok(cids)
161 }
Alice Wangc2fec932023-02-23 16:24:02 +0000162
Alice Wangbff017f2023-11-09 14:43:28 +0000163 fn requestAttestation(
164 &self,
165 csr: &[u8],
166 requester_uid: i32,
167 ) -> binder::Result<Vec<Certificate>> {
Alice Wangc2fec932023-02-23 16:24:02 +0000168 check_manage_access()?;
Alice Wanga410b642023-10-18 09:05:15 +0000169 info!("Received csr. Requestting attestation...");
Alice Wange9ac2db2023-09-08 15:13:13 +0000170 if cfg!(remote_attestation) {
Alice Wangbff017f2023-11-09 14:43:28 +0000171 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 Wanga410b642023-10-18 09:05:15 +0000179 .context("Failed to request attestation")
Alice Wange9ac2db2023-09-08 15:13:13 +0000180 .with_log()
Alice Wangbff017f2023-11-09 14:43:28 +0000181 .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 Wange9ac2db2023-09-08 15:13:13 +0000188 } else {
189 Err(Status::new_exception_str(
190 ExceptionCode::UNSUPPORTED_OPERATION,
191 Some(
Alice Wanga410b642023-10-18 09:05:15 +0000192 "requestAttestation is not supported with the remote_attestation feature \
193 disabled",
Alice Wange9ac2db2023-09-08 15:13:13 +0000194 ),
195 ))
Jiyong Park2227eaa2023-08-04 11:59:18 +0900196 .with_log()
Alice Wange9ac2db2023-09-08 15:13:13 +0000197 }
Alice Wangc2fec932023-02-23 16:24:02 +0000198 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900199
200 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
201 check_use_custom_virtual_machine()?;
202
Inseob Kim7307a892023-09-14 13:37:58 +0900203 Ok(get_assignable_devices()?
204 .device
205 .into_iter()
206 .map(|x| AssignableDevice { node: x.sysfs_path, kind: x.kind })
207 .collect::<Vec<_>>())
Inseob Kim53d0b212023-07-20 16:58:37 +0900208 }
Inseob Kim1ca0f652023-07-20 17:18:12 +0900209
Inseob Kim7307a892023-09-14 13:37:58 +0900210 fn bindDevicesToVfioDriver(&self, devices: &[String]) -> binder::Result<Vec<BoundDevice>> {
Inseob Kim1ca0f652023-07-20 17:18:12 +0900211 check_use_custom_virtual_machine()?;
212
Inseob Kimbdca0472023-07-28 19:20:56 +0900213 let vfio_service: Strong<dyn IVfioHandler> =
214 wait_for_interface(<BpVfioHandler as IVfioHandler>::get_descriptor())?;
Inseob Kimf36347b2023-08-03 12:52:48 +0900215
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900216 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 Kim7307a892023-09-14 13:37:58 +0900227 Ok(get_assignable_devices()?
228 .device
229 .into_iter()
230 .filter_map(|x| {
231 if devices.contains(&x.sysfs_path) {
Jaewan Kim35e818d2023-10-18 05:36:38 +0000232 Some(BoundDevice { sysfsPath: x.sysfs_path, dtboLabel: x.dtbo_label })
Inseob Kim7307a892023-09-14 13:37:58 +0900233 } else {
234 None
235 }
236 })
237 .collect::<Vec<_>>())
Inseob Kim1ca0f652023-07-20 17:18:12 +0900238 }
239}
240
Inseob Kimc4a774d2023-08-30 12:48:43 +0900241// KEEP IN SYNC WITH assignable_devices.xsd
242#[derive(Debug, Deserialize)]
243struct Device {
244 kind: String,
Jaewan Kim35e818d2023-10-18 05:36:38 +0000245 dtbo_label: String,
Inseob Kimc4a774d2023-08-30 12:48:43 +0900246 sysfs_path: String,
247}
248
Inseob Kim7307a892023-09-14 13:37:58 +0900249#[derive(Debug, Default, Deserialize)]
Inseob Kimc4a774d2023-08-30 12:48:43 +0900250struct Devices {
251 device: Vec<Device>,
252}
253
Inseob Kim7307a892023-09-14 13:37:58 +0900254fn 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 Brazdilafc9a9e2023-01-12 16:08:10 +0000293#[derive(Debug, Default)]
294struct 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
303impl 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)]
313struct 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
319impl 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
388fn 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.
405pub fn remove_temporary_dir(path: &PathBuf) -> Result<()> {
Alice Wangd1b11a02023-04-18 12:30:20 +0000406 ensure!(path.as_path().is_dir(), "Path {:?} is not a directory", path);
David Brazdilafc9a9e2023-01-12 16:08:10 +0000407 chown(path, Some(Uid::current()), None)?;
408 set_permissions(path, Permissions::from_mode(0o700))?;
Alice Wangd1b11a02023-04-18 12:30:20 +0000409 remove_dir_all(path)?;
David Brazdilafc9a9e2023-01-12 16:08:10 +0000410 Ok(())
411}
412
413/// Implementation of the AIDL `IGlobalVmContext` interface.
414#[derive(Debug, Default)]
415struct 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
423impl Interface for GlobalVmContext {}
424
425impl 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
435fn 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
457fn 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
486fn 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 Park2227eaa2023-08-04 11:59:18 +0900498 Err(anyhow!("does not have the {} permission", perm))
499 .or_binder_exception(ExceptionCode::SECURITY)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000500 }
501}
502
503/// Check whether the caller of the current Binder method is allowed to call debug methods.
504fn 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
509fn check_manage_access() -> binder::Result<()> {
510 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
511}
Inseob Kim53d0b212023-07-20 16:58:37 +0900512
513/// Check whether the caller of the current Binder method is allowed to use custom VMs
514fn check_use_custom_virtual_machine() -> binder::Result<()> {
515 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
516}