blob: d1f7291b3f21a22ec15d98a9dce53b1fd1f5d79a [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};
David Brazdil2dfefd12023-11-17 14:07:36 +000046use std::fs::{self, create_dir, remove_dir_all, remove_file, 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};
Alice Wang4c6c5582023-11-23 15:07:18 +000055use x509_parser::{traits::FromDer, certificate::X509Certificate};
David Brazdilafc9a9e2023-01-12 16:08:10 +000056
57/// The unique ID of a VM used (together with a port number) for vsock communication.
58pub type Cid = u32;
59
60pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
61
62/// Directory in which to write disk image files used while running VMs.
63pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
64
65/// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this
66/// are reserved for the host or other usage.
67const GUEST_CID_MIN: Cid = 2048;
68const GUEST_CID_MAX: Cid = 65535;
69
70const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid";
71
72const CHUNK_RECV_MAX_LEN: usize = 1024;
73
74fn is_valid_guest_cid(cid: Cid) -> bool {
75 (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid)
76}
77
78/// Singleton service for allocating globally-unique VM resources, such as the CID, and running
79/// singleton servers, like tombstone receiver.
80#[derive(Debug, Default)]
81pub struct VirtualizationServiceInternal {
82 state: Arc<Mutex<GlobalState>>,
83}
84
85impl VirtualizationServiceInternal {
86 pub fn init() -> VirtualizationServiceInternal {
87 let service = VirtualizationServiceInternal::default();
88
89 std::thread::spawn(|| {
90 if let Err(e) = handle_stream_connection_tombstoned() {
91 warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e);
92 }
93 });
94
95 service
96 }
97}
98
99impl Interface for VirtualizationServiceInternal {}
100
101impl IVirtualizationServiceInternal for VirtualizationServiceInternal {
102 fn removeMemlockRlimit(&self) -> binder::Result<()> {
103 let pid = get_calling_pid();
104 let lim = libc::rlimit { rlim_cur: libc::RLIM_INFINITY, rlim_max: libc::RLIM_INFINITY };
105
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100106 // SAFETY: borrowing the new limit struct only
David Brazdilafc9a9e2023-01-12 16:08:10 +0000107 let ret = unsafe { libc::prlimit(pid, libc::RLIMIT_MEMLOCK, &lim, std::ptr::null_mut()) };
108
109 match ret {
110 0 => Ok(()),
Jiyong Park2227eaa2023-08-04 11:59:18 +0900111 -1 => Err(std::io::Error::last_os_error().into()),
112 n => Err(anyhow!("Unexpected return value from prlimit(): {n}")),
David Brazdilafc9a9e2023-01-12 16:08:10 +0000113 }
Jiyong Park2227eaa2023-08-04 11:59:18 +0900114 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000115 }
116
117 fn allocateGlobalVmContext(
118 &self,
119 requester_debug_pid: i32,
120 ) -> binder::Result<Strong<dyn IGlobalVmContext>> {
121 check_manage_access()?;
122
123 let requester_uid = get_calling_uid();
124 let requester_debug_pid = requester_debug_pid as pid_t;
125 let state = &mut *self.state.lock().unwrap();
Jiyong Park2227eaa2023-08-04 11:59:18 +0900126 state
127 .allocate_vm_context(requester_uid, requester_debug_pid)
128 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000129 }
130
131 fn atomVmBooted(&self, atom: &AtomVmBooted) -> Result<(), Status> {
132 forward_vm_booted_atom(atom);
133 Ok(())
134 }
135
136 fn atomVmCreationRequested(&self, atom: &AtomVmCreationRequested) -> Result<(), Status> {
137 forward_vm_creation_atom(atom);
138 Ok(())
139 }
140
141 fn atomVmExited(&self, atom: &AtomVmExited) -> Result<(), Status> {
142 forward_vm_exited_atom(atom);
143 Ok(())
144 }
145
146 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
147 check_debug_access()?;
148
149 let state = &mut *self.state.lock().unwrap();
150 let cids = state
151 .held_contexts
152 .iter()
153 .filter_map(|(_, inst)| Weak::upgrade(inst))
154 .map(|vm| VirtualMachineDebugInfo {
155 cid: vm.cid as i32,
156 temporaryDirectory: vm.get_temp_dir().to_string_lossy().to_string(),
157 requesterUid: vm.requester_uid as i32,
Charisee96113f32023-01-26 09:00:42 +0000158 requesterPid: vm.requester_debug_pid,
David Brazdilafc9a9e2023-01-12 16:08:10 +0000159 })
160 .collect();
161 Ok(cids)
162 }
Alice Wangc2fec932023-02-23 16:24:02 +0000163
Alice Wangbff017f2023-11-09 14:43:28 +0000164 fn requestAttestation(
165 &self,
166 csr: &[u8],
167 requester_uid: i32,
168 ) -> binder::Result<Vec<Certificate>> {
Alice Wangc2fec932023-02-23 16:24:02 +0000169 check_manage_access()?;
Alice Wang4c6c5582023-11-23 15:07:18 +0000170 if !cfg!(remote_attestation) {
171 return Err(Status::new_exception_str(
Alice Wange9ac2db2023-09-08 15:13:13 +0000172 ExceptionCode::UNSUPPORTED_OPERATION,
173 Some(
Alice Wanga410b642023-10-18 09:05:15 +0000174 "requestAttestation is not supported with the remote_attestation feature \
175 disabled",
Alice Wange9ac2db2023-09-08 15:13:13 +0000176 ),
177 ))
Alice Wang4c6c5582023-11-23 15:07:18 +0000178 .with_log();
Alice Wange9ac2db2023-09-08 15:13:13 +0000179 }
Alice Wang4c6c5582023-11-23 15:07:18 +0000180 info!("Received csr. Requestting attestation...");
181 let attestation_key = get_rkpd_attestation_key(
182 REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME,
183 requester_uid as u32,
184 )
185 .context("Failed to retrieve the remotely provisioned keys")
186 .with_log()
187 .or_service_specific_exception(-1)?;
188 let mut certificate_chain = split_x509_certificate_chain(&attestation_key.encodedCertChain)
189 .context("Failed to split the remotely provisioned certificate chain")
190 .with_log()
191 .or_service_specific_exception(-1)?;
192 if certificate_chain.is_empty() {
193 return Err(Status::new_service_specific_error_str(
194 -1,
195 Some("The certificate chain should contain at least 1 certificate"),
196 ))
197 .with_log();
198 }
199 let certificate = request_attestation(csr, &attestation_key.keyBlob)
200 .context("Failed to request attestation")
201 .with_log()
202 .or_service_specific_exception(-1)?;
203 certificate_chain.insert(0, Certificate { encodedCertificate: certificate });
204
205 Ok(certificate_chain)
Alice Wangc2fec932023-02-23 16:24:02 +0000206 }
Inseob Kim53d0b212023-07-20 16:58:37 +0900207
208 fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> {
209 check_use_custom_virtual_machine()?;
210
Inseob Kim7307a892023-09-14 13:37:58 +0900211 Ok(get_assignable_devices()?
212 .device
213 .into_iter()
214 .map(|x| AssignableDevice { node: x.sysfs_path, kind: x.kind })
215 .collect::<Vec<_>>())
Inseob Kim53d0b212023-07-20 16:58:37 +0900216 }
Inseob Kim1ca0f652023-07-20 17:18:12 +0900217
Inseob Kim7307a892023-09-14 13:37:58 +0900218 fn bindDevicesToVfioDriver(&self, devices: &[String]) -> binder::Result<Vec<BoundDevice>> {
Inseob Kim1ca0f652023-07-20 17:18:12 +0900219 check_use_custom_virtual_machine()?;
220
Inseob Kimbdca0472023-07-28 19:20:56 +0900221 let vfio_service: Strong<dyn IVfioHandler> =
222 wait_for_interface(<BpVfioHandler as IVfioHandler>::get_descriptor())?;
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900223 vfio_service.bindDevicesToVfioDriver(devices)?;
224
Inseob Kim7307a892023-09-14 13:37:58 +0900225 Ok(get_assignable_devices()?
226 .device
227 .into_iter()
228 .filter_map(|x| {
229 if devices.contains(&x.sysfs_path) {
Jaewan Kim35e818d2023-10-18 05:36:38 +0000230 Some(BoundDevice { sysfsPath: x.sysfs_path, dtboLabel: x.dtbo_label })
Inseob Kim7307a892023-09-14 13:37:58 +0900231 } else {
232 None
233 }
234 })
235 .collect::<Vec<_>>())
Inseob Kim1ca0f652023-07-20 17:18:12 +0900236 }
David Brazdil2dfefd12023-11-17 14:07:36 +0000237
238 fn getDtboFile(&self) -> binder::Result<ParcelFileDescriptor> {
239 check_use_custom_virtual_machine()?;
240
241 let state = &mut *self.state.lock().unwrap();
242 let file = state.get_dtbo_file().or_service_specific_exception(-1)?;
243 Ok(ParcelFileDescriptor::new(file))
244 }
Inseob Kim1ca0f652023-07-20 17:18:12 +0900245}
246
Inseob Kimc4a774d2023-08-30 12:48:43 +0900247// KEEP IN SYNC WITH assignable_devices.xsd
248#[derive(Debug, Deserialize)]
249struct Device {
250 kind: String,
Jaewan Kim35e818d2023-10-18 05:36:38 +0000251 dtbo_label: String,
Inseob Kimc4a774d2023-08-30 12:48:43 +0900252 sysfs_path: String,
253}
254
Inseob Kim7307a892023-09-14 13:37:58 +0900255#[derive(Debug, Default, Deserialize)]
Inseob Kimc4a774d2023-08-30 12:48:43 +0900256struct Devices {
257 device: Vec<Device>,
258}
259
Inseob Kim7307a892023-09-14 13:37:58 +0900260fn get_assignable_devices() -> binder::Result<Devices> {
261 let xml_path = Path::new("/vendor/etc/avf/assignable_devices.xml");
262 if !xml_path.exists() {
263 return Ok(Devices { ..Default::default() });
264 }
265
266 let xml = fs::read(xml_path)
267 .context("Failed to read assignable_devices.xml")
268 .with_log()
269 .or_service_specific_exception(-1)?;
270
271 let xml = String::from_utf8(xml)
272 .context("assignable_devices.xml is not a valid UTF-8 file")
273 .with_log()
274 .or_service_specific_exception(-1)?;
275
276 let mut devices: Devices = serde_xml_rs::from_str(&xml)
277 .context("can't parse assignable_devices.xml")
278 .with_log()
279 .or_service_specific_exception(-1)?;
280
281 let mut device_set = HashSet::new();
282 devices.device.retain(move |device| {
283 if device_set.contains(&device.sysfs_path) {
284 warn!("duplicated assignable device {device:?}; ignoring...");
285 return false;
286 }
287
288 if !Path::new(&device.sysfs_path).exists() {
289 warn!("assignable device {device:?} doesn't exist; ignoring...");
290 return false;
291 }
292
293 device_set.insert(device.sysfs_path.clone());
294 true
295 });
296 Ok(devices)
297}
298
Alice Wang4c6c5582023-11-23 15:07:18 +0000299fn split_x509_certificate_chain(mut cert_chain: &[u8]) -> Result<Vec<Certificate>> {
300 let mut out = Vec::new();
301 while !cert_chain.is_empty() {
302 let (remaining, _) = X509Certificate::from_der(cert_chain)?;
303 let end = cert_chain.len() - remaining.len();
304 out.push(Certificate { encodedCertificate: cert_chain[..end].to_vec() });
305 cert_chain = remaining;
306 }
307 Ok(out)
308}
309
David Brazdilafc9a9e2023-01-12 16:08:10 +0000310#[derive(Debug, Default)]
311struct GlobalVmInstance {
312 /// The unique CID assigned to the VM for vsock communication.
313 cid: Cid,
314 /// UID of the client who requested this VM instance.
315 requester_uid: uid_t,
316 /// PID of the client who requested this VM instance.
317 requester_debug_pid: pid_t,
318}
319
320impl GlobalVmInstance {
321 fn get_temp_dir(&self) -> PathBuf {
322 let cid = self.cid;
323 format!("{TEMPORARY_DIRECTORY}/{cid}").into()
324 }
325}
326
327/// The mutable state of the VirtualizationServiceInternal. There should only be one instance
328/// of this struct.
329#[derive(Debug, Default)]
330struct GlobalState {
331 /// VM contexts currently allocated to running VMs. A CID is never recycled as long
332 /// as there is a strong reference held by a GlobalVmContext.
333 held_contexts: HashMap<Cid, Weak<GlobalVmInstance>>,
David Brazdil2dfefd12023-11-17 14:07:36 +0000334
335 /// Cached read-only FD of VM DTBO file. Also serves as a lock for creating the file.
336 dtbo_file: Mutex<Option<File>>,
David Brazdilafc9a9e2023-01-12 16:08:10 +0000337}
338
339impl GlobalState {
340 /// Get the next available CID, or an error if we have run out. The last CID used is stored in
341 /// a system property so that restart of virtualizationservice doesn't reuse CID while the host
342 /// Android is up.
343 fn get_next_available_cid(&mut self) -> Result<Cid> {
344 // Start trying to find a CID from the last used CID + 1. This ensures
345 // that we do not eagerly recycle CIDs. It makes debugging easier but
346 // also means that retrying to allocate a CID, eg. because it is
347 // erroneously occupied by a process, will not recycle the same CID.
348 let last_cid_prop =
349 system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() {
350 Ok(num) => {
351 if is_valid_guest_cid(num) {
352 Some(num)
353 } else {
354 error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID);
355 None
356 }
357 }
358 Err(_) => {
359 error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID);
360 None
361 }
362 });
363
364 let first_cid = if let Some(last_cid) = last_cid_prop {
365 if last_cid == GUEST_CID_MAX {
366 GUEST_CID_MIN
367 } else {
368 last_cid + 1
369 }
370 } else {
371 GUEST_CID_MIN
372 };
373
374 let cid = self
375 .find_available_cid(first_cid..=GUEST_CID_MAX)
376 .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid))
377 .ok_or_else(|| anyhow!("Could not find an available CID."))?;
378
379 system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?;
380 Ok(cid)
381 }
382
383 fn find_available_cid<I>(&self, mut range: I) -> Option<Cid>
384 where
385 I: Iterator<Item = Cid>,
386 {
387 range.find(|cid| !self.held_contexts.contains_key(cid))
388 }
389
390 fn allocate_vm_context(
391 &mut self,
392 requester_uid: uid_t,
393 requester_debug_pid: pid_t,
394 ) -> Result<Strong<dyn IGlobalVmContext>> {
395 // Garbage collect unused VM contexts.
396 self.held_contexts.retain(|_, instance| instance.strong_count() > 0);
397
398 let cid = self.get_next_available_cid()?;
399 let instance = Arc::new(GlobalVmInstance { cid, requester_uid, requester_debug_pid });
David Brazdil2dfefd12023-11-17 14:07:36 +0000400 create_temporary_directory(&instance.get_temp_dir(), Some(requester_uid))?;
David Brazdilafc9a9e2023-01-12 16:08:10 +0000401
402 self.held_contexts.insert(cid, Arc::downgrade(&instance));
403 let binder = GlobalVmContext { instance, ..Default::default() };
404 Ok(BnGlobalVmContext::new_binder(binder, BinderFeatures::default()))
405 }
David Brazdil2dfefd12023-11-17 14:07:36 +0000406
407 fn get_dtbo_file(&mut self) -> Result<File> {
408 let mut file = self.dtbo_file.lock().unwrap();
409
410 let fd = if let Some(ref_fd) = &*file {
411 ref_fd.try_clone()?
412 } else {
413 let path = get_or_create_common_dir()?.join("vm.dtbo");
414 if path.exists() {
415 // All temporary files are deleted when the service is started.
416 // If the file exists but the FD is not cached, the file is
417 // likely corrupted.
418 remove_file(&path).context("Failed to clone cached VM DTBO file descriptor")?;
419 }
420
421 // Open a write-only file descriptor for vfio_handler.
422 let write_fd = File::create(&path).context("Failed to create VM DTBO file")?;
423
424 let vfio_service: Strong<dyn IVfioHandler> =
425 wait_for_interface(<BpVfioHandler as IVfioHandler>::get_descriptor())?;
426 vfio_service.writeVmDtbo(&ParcelFileDescriptor::new(write_fd))?;
427
428 // Open read-only. This FD will be cached and returned to clients.
429 let read_fd = File::open(&path).context("Failed to open VM DTBO file")?;
430 let read_fd_clone =
431 read_fd.try_clone().context("Failed to clone VM DTBO file descriptor")?;
432 *file = Some(read_fd);
433 read_fd_clone
434 };
435
436 Ok(fd)
437 }
David Brazdilafc9a9e2023-01-12 16:08:10 +0000438}
439
David Brazdil2dfefd12023-11-17 14:07:36 +0000440fn create_temporary_directory(path: &PathBuf, requester_uid: Option<uid_t>) -> Result<()> {
441 // Directory may exist if previous attempt to create it had failed.
442 // Delete it before trying again.
David Brazdilafc9a9e2023-01-12 16:08:10 +0000443 if path.as_path().exists() {
444 remove_temporary_dir(path).unwrap_or_else(|e| {
445 warn!("Could not delete temporary directory {:?}: {}", path, e);
446 });
447 }
David Brazdil2dfefd12023-11-17 14:07:36 +0000448 // Create directory.
449 create_dir(path).with_context(|| format!("Could not create temporary directory {:?}", path))?;
450 // If provided, change ownership to client's UID but system's GID, and permissions 0700.
David Brazdilafc9a9e2023-01-12 16:08:10 +0000451 // If the chown() fails, this will leave behind an empty directory that will get removed
452 // at the next attempt, or if virtualizationservice is restarted.
David Brazdil2dfefd12023-11-17 14:07:36 +0000453 if let Some(uid) = requester_uid {
454 chown(path, Some(Uid::from_raw(uid)), None).with_context(|| {
455 format!("Could not set ownership of temporary directory {:?}", path)
456 })?;
457 }
David Brazdilafc9a9e2023-01-12 16:08:10 +0000458 Ok(())
459}
460
461/// Removes a directory owned by a different user by first changing its owner back
462/// to VirtualizationService.
463pub fn remove_temporary_dir(path: &PathBuf) -> Result<()> {
Alice Wangd1b11a02023-04-18 12:30:20 +0000464 ensure!(path.as_path().is_dir(), "Path {:?} is not a directory", path);
David Brazdilafc9a9e2023-01-12 16:08:10 +0000465 chown(path, Some(Uid::current()), None)?;
466 set_permissions(path, Permissions::from_mode(0o700))?;
Alice Wangd1b11a02023-04-18 12:30:20 +0000467 remove_dir_all(path)?;
David Brazdilafc9a9e2023-01-12 16:08:10 +0000468 Ok(())
469}
470
David Brazdil2dfefd12023-11-17 14:07:36 +0000471fn get_or_create_common_dir() -> Result<PathBuf> {
472 let path = Path::new(TEMPORARY_DIRECTORY).join("common");
473 if !path.exists() {
474 create_temporary_directory(&path, None)?;
475 }
476 Ok(path)
477}
478
David Brazdilafc9a9e2023-01-12 16:08:10 +0000479/// Implementation of the AIDL `IGlobalVmContext` interface.
480#[derive(Debug, Default)]
481struct GlobalVmContext {
482 /// Strong reference to the context's instance data structure.
483 instance: Arc<GlobalVmInstance>,
484 /// Keeps our service process running as long as this VM context exists.
485 #[allow(dead_code)]
486 lazy_service_guard: LazyServiceGuard,
487}
488
489impl Interface for GlobalVmContext {}
490
491impl IGlobalVmContext for GlobalVmContext {
492 fn getCid(&self) -> binder::Result<i32> {
493 Ok(self.instance.cid as i32)
494 }
495
496 fn getTemporaryDirectory(&self) -> binder::Result<String> {
497 Ok(self.instance.get_temp_dir().to_string_lossy().to_string())
498 }
499}
500
501fn handle_stream_connection_tombstoned() -> Result<()> {
502 // Should not listen for tombstones on a guest VM's port.
503 assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid));
504 let listener =
505 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?;
506 for incoming_stream in listener.incoming() {
507 let mut incoming_stream = match incoming_stream {
508 Err(e) => {
509 warn!("invalid incoming connection: {:?}", e);
510 continue;
511 }
512 Ok(s) => s,
513 };
514 std::thread::spawn(move || {
515 if let Err(e) = handle_tombstone(&mut incoming_stream) {
516 error!("Failed to write tombstone- {:?}", e);
517 }
518 });
519 }
520 Ok(())
521}
522
523fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
524 if let Ok(addr) = stream.peer_addr() {
525 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
526 }
527 let tb_connection =
528 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
529 .context("Failed to connect to tombstoned")?;
530 let mut text_output = tb_connection
531 .text_output
532 .as_ref()
533 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
534 let mut num_bytes_read = 0;
535 loop {
536 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
537 let n = stream
538 .read(&mut chunk_recv)
539 .context("Failed to read tombstone data from Vsock stream")?;
540 if n == 0 {
541 break;
542 }
543 num_bytes_read += n;
544 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
545 }
546 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
547 tb_connection.notify_completion()?;
548 Ok(())
549}
550
551/// Checks whether the caller has a specific permission
552fn check_permission(perm: &str) -> binder::Result<()> {
553 let calling_pid = get_calling_pid();
554 let calling_uid = get_calling_uid();
555 // Root can do anything
556 if calling_uid == 0 {
557 return Ok(());
558 }
559 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
560 binder::get_interface("permission")?;
561 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
562 Ok(())
563 } else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900564 Err(anyhow!("does not have the {} permission", perm))
565 .or_binder_exception(ExceptionCode::SECURITY)
David Brazdilafc9a9e2023-01-12 16:08:10 +0000566 }
567}
568
569/// Check whether the caller of the current Binder method is allowed to call debug methods.
570fn check_debug_access() -> binder::Result<()> {
571 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
572}
573
574/// Check whether the caller of the current Binder method is allowed to manage VMs
575fn check_manage_access() -> binder::Result<()> {
576 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
577}
Inseob Kim53d0b212023-07-20 16:58:37 +0900578
579/// Check whether the caller of the current Binder method is allowed to use custom VMs
580fn check_use_custom_virtual_machine() -> binder::Result<()> {
581 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
582}
Alice Wang4c6c5582023-11-23 15:07:18 +0000583
584#[cfg(test)]
585mod tests {
586 use super::*;
587 use std::fs;
588
589 const TEST_RKP_CERT_CHAIN_PATH: &str = "testdata/rkp_cert_chain.der";
590
591 #[test]
592 fn splitting_x509_certificate_chain_succeeds() -> Result<()> {
593 let bytes = fs::read(TEST_RKP_CERT_CHAIN_PATH)?;
594 let cert_chain = split_x509_certificate_chain(&bytes)?;
595
596 assert_eq!(4, cert_chain.len());
597 for cert in cert_chain {
598 let (remaining, _) = X509Certificate::from_der(&cert.encodedCertificate)?;
599 assert!(remaining.is_empty());
600 }
601 Ok(())
602 }
603}