David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 1 | // 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 | |
David Brazdil | 33a3102 | 2023-01-12 16:55:16 +0000 | [diff] [blame] | 17 | use crate::atom::{forward_vm_booted_atom, forward_vm_creation_atom, forward_vm_exited_atom}; |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 18 | use crate::maintenance; |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 19 | use crate::remote_provisioning; |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 20 | use crate::rkpvm::{generate_ecdsa_p256_key_pair, request_attestation}; |
| 21 | use crate::{get_calling_pid, get_calling_uid, REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 22 | use android_os_permissions_aidl::aidl::android::os::IPermissionController; |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 23 | use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon; |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 24 | use android_system_virtualizationmaintenance::aidl::android::system::virtualizationmaintenance; |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 25 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice; |
| 26 | use android_system_virtualizationservice_internal as android_vs_internal; |
| 27 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice; |
Seungjae Yoo | bb7b613 | 2024-06-13 11:07:29 +0900 | [diff] [blame] | 28 | use android_system_vmtethering::aidl::android::system::vmtethering; |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 29 | use android_vs_internal::aidl::android::system::virtualizationservice_internal; |
Alice Wang | d1b11a0 | 2023-04-18 12:30:20 +0000 | [diff] [blame] | 30 | use anyhow::{anyhow, ensure, Context, Result}; |
Jiyong Park | d7bd2f2 | 2023-08-10 20:41:19 +0900 | [diff] [blame] | 31 | use avflog::LogResult; |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 32 | use binder::{ |
| 33 | self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, IntoBinderResult, |
| 34 | LazyServiceGuard, ParcelFileDescriptor, Status, Strong, |
| 35 | }; |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 36 | use lazy_static::lazy_static; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 37 | use libc::VMADDR_CID_HOST; |
| 38 | use log::{error, info, warn}; |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 39 | use nix::unistd::{chown, Uid}; |
| 40 | use openssl::x509::X509; |
Shikha Panwar | 61a74b5 | 2024-02-16 13:17:01 +0000 | [diff] [blame] | 41 | use rand::Fill; |
Alice Wang | bff017f | 2023-11-09 14:43:28 +0000 | [diff] [blame] | 42 | use rkpd_client::get_rkpd_attestation_key; |
David Drysdale | e64de8e | 2024-02-29 11:54:29 +0000 | [diff] [blame] | 43 | use rustutils::{ |
| 44 | system_properties, |
| 45 | users::{multiuser_get_app_id, multiuser_get_user_id}, |
| 46 | }; |
Inseob Kim | c4a774d | 2023-08-30 12:48:43 +0900 | [diff] [blame] | 47 | use serde::Deserialize; |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 48 | use service_vm_comm::Response; |
Inseob Kim | c4a774d | 2023-08-30 12:48:43 +0900 | [diff] [blame] | 49 | use std::collections::{HashMap, HashSet}; |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 50 | use std::fs::{self, create_dir, remove_dir_all, remove_file, set_permissions, File, Permissions}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 51 | use std::io::{Read, Write}; |
| 52 | use std::os::unix::fs::PermissionsExt; |
| 53 | use std::os::unix::raw::{pid_t, uid_t}; |
Inseob Kim | 55438b2 | 2023-08-09 20:16:01 +0900 | [diff] [blame] | 54 | use std::path::{Path, PathBuf}; |
Jeongik Cha | 7add2a4 | 2024-04-02 14:52:39 +0900 | [diff] [blame] | 55 | use std::sync::{Arc, Condvar, Mutex, Weak}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 56 | use tombstoned_client::{DebuggerdDumpType, TombstonedConnection}; |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 57 | use virtualizationcommon::Certificate::Certificate; |
Alan Stokes | 30ccacb | 2024-02-20 14:59:02 +0000 | [diff] [blame] | 58 | use virtualizationmaintenance::{ |
| 59 | IVirtualizationMaintenance::IVirtualizationMaintenance, |
| 60 | IVirtualizationReconciliationCallback::IVirtualizationReconciliationCallback, |
| 61 | }; |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 62 | use virtualizationservice::{ |
| 63 | AssignableDevice::AssignableDevice, VirtualMachineDebugInfo::VirtualMachineDebugInfo, |
| 64 | }; |
| 65 | use virtualizationservice_internal::{ |
| 66 | AtomVmBooted::AtomVmBooted, |
| 67 | AtomVmCreationRequested::AtomVmCreationRequested, |
| 68 | AtomVmExited::AtomVmExited, |
| 69 | IBoundDevice::IBoundDevice, |
| 70 | IGlobalVmContext::{BnGlobalVmContext, IGlobalVmContext}, |
| 71 | IVfioHandler::VfioDev::VfioDev, |
| 72 | IVfioHandler::{BpVfioHandler, IVfioHandler}, |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 73 | IVirtualizationServiceInternal::IVirtualizationServiceInternal, |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 74 | IVmnic::{BpVmnic, IVmnic}, |
Alan Stokes | ac66707 | 2024-02-19 16:26:00 +0000 | [diff] [blame] | 75 | }; |
| 76 | use virtualmachineservice::IVirtualMachineService::VM_TOMBSTONES_SERVICE_PORT; |
Seungjae Yoo | bb7b613 | 2024-06-13 11:07:29 +0900 | [diff] [blame] | 77 | use vmtethering::IVmTethering::{BpVmTethering, IVmTethering}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 78 | use vsock::{VsockListener, VsockStream}; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 79 | |
| 80 | /// The unique ID of a VM used (together with a port number) for vsock communication. |
| 81 | pub type Cid = u32; |
| 82 | |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 83 | /// Directory in which to write disk image files used while running VMs. |
| 84 | pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice"; |
| 85 | |
| 86 | /// The first CID to assign to a guest VM managed by the VirtualizationService. CIDs lower than this |
| 87 | /// are reserved for the host or other usage. |
| 88 | const GUEST_CID_MIN: Cid = 2048; |
| 89 | const GUEST_CID_MAX: Cid = 65535; |
| 90 | |
| 91 | const SYSPROP_LAST_CID: &str = "virtualizationservice.state.last_cid"; |
| 92 | |
| 93 | const CHUNK_RECV_MAX_LEN: usize = 1024; |
| 94 | |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 95 | /// The fake certificate is used for testing only when a client VM requests attestation in test |
| 96 | /// mode, it is a single certificate extracted on an unregistered device for testing. |
| 97 | /// Here is the snapshot of the certificate: |
| 98 | /// |
| 99 | /// ``` |
| 100 | /// Certificate: |
| 101 | /// Data: |
| 102 | /// Version: 3 (0x2) |
| 103 | /// Serial Number: |
| 104 | /// 59:ae:50:98:95:e1:34:25:f1:21:93:c0:4c:e5:24:66 |
| 105 | /// Signature Algorithm: ecdsa-with-SHA256 |
| 106 | /// Issuer: CN = Droid Unregistered Device CA, O = Google Test LLC |
| 107 | /// Validity |
| 108 | /// Not Before: Feb 5 14:39:39 2024 GMT |
| 109 | /// Not After : Feb 14 14:39:39 2024 GMT |
| 110 | /// Subject: CN = 59ae509895e13425f12193c04ce52466, O = TEE |
| 111 | /// Subject Public Key Info: |
| 112 | /// Public Key Algorithm: id-ecPublicKey |
| 113 | /// Public-Key: (256 bit) |
| 114 | /// pub: |
| 115 | /// 04:30:32:cd:95:12:b0:71:8b:b7:14:44:26:58:d5: |
| 116 | /// 82:8c:25:55:2c:6d:ef:98:e3:4f:88:d0:74:82:09: |
| 117 | /// 3e:8d:6c:f0:f2:18:d5:83:0e:0d:f2:ce:c5:15:38: |
| 118 | /// e5:6a:e6:4d:4d:95:15:b7:24:e7:cb:4b:63:42:21: |
| 119 | /// bc:36:c6:0a:d8 |
| 120 | /// ASN1 OID: prime256v1 |
| 121 | /// NIST CURVE: P-256 |
| 122 | /// X509v3 extensions: |
| 123 | /// ... |
| 124 | /// ``` |
| 125 | const FAKE_CERTIFICATE_FOR_TESTING: &[u8] = &[ |
| 126 | 0x30, 0x82, 0x01, 0xee, 0x30, 0x82, 0x01, 0x94, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x10, 0x59, |
| 127 | 0xae, 0x50, 0x98, 0x95, 0xe1, 0x34, 0x25, 0xf1, 0x21, 0x93, 0xc0, 0x4c, 0xe5, 0x24, 0x66, 0x30, |
| 128 | 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x41, 0x31, 0x25, 0x30, |
| 129 | 0x23, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x1c, 0x44, 0x72, 0x6f, 0x69, 0x64, 0x20, 0x55, 0x6e, |
| 130 | 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x65, 0x64, 0x20, 0x44, 0x65, 0x76, 0x69, 0x63, |
| 131 | 0x65, 0x20, 0x43, 0x41, 0x31, 0x18, 0x30, 0x16, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x0f, 0x47, |
| 132 | 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x4c, 0x4c, 0x43, 0x30, 0x1e, |
| 133 | 0x17, 0x0d, 0x32, 0x34, 0x30, 0x32, 0x30, 0x35, 0x31, 0x34, 0x33, 0x39, 0x33, 0x39, 0x5a, 0x17, |
| 134 | 0x0d, 0x32, 0x34, 0x30, 0x32, 0x31, 0x34, 0x31, 0x34, 0x33, 0x39, 0x33, 0x39, 0x5a, 0x30, 0x39, |
| 135 | 0x31, 0x29, 0x30, 0x27, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x20, 0x35, 0x39, 0x61, 0x65, 0x35, |
| 136 | 0x30, 0x39, 0x38, 0x39, 0x35, 0x65, 0x31, 0x33, 0x34, 0x32, 0x35, 0x66, 0x31, 0x32, 0x31, 0x39, |
| 137 | 0x33, 0x63, 0x30, 0x34, 0x63, 0x65, 0x35, 0x32, 0x34, 0x36, 0x36, 0x31, 0x0c, 0x30, 0x0a, 0x06, |
| 138 | 0x03, 0x55, 0x04, 0x0a, 0x13, 0x03, 0x54, 0x45, 0x45, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, |
| 139 | 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, |
| 140 | 0x03, 0x42, 0x00, 0x04, 0x30, 0x32, 0xcd, 0x95, 0x12, 0xb0, 0x71, 0x8b, 0xb7, 0x14, 0x44, 0x26, |
| 141 | 0x58, 0xd5, 0x82, 0x8c, 0x25, 0x55, 0x2c, 0x6d, 0xef, 0x98, 0xe3, 0x4f, 0x88, 0xd0, 0x74, 0x82, |
| 142 | 0x09, 0x3e, 0x8d, 0x6c, 0xf0, 0xf2, 0x18, 0xd5, 0x83, 0x0e, 0x0d, 0xf2, 0xce, 0xc5, 0x15, 0x38, |
| 143 | 0xe5, 0x6a, 0xe6, 0x4d, 0x4d, 0x95, 0x15, 0xb7, 0x24, 0xe7, 0xcb, 0x4b, 0x63, 0x42, 0x21, 0xbc, |
| 144 | 0x36, 0xc6, 0x0a, 0xd8, 0xa3, 0x76, 0x30, 0x74, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, |
| 145 | 0x16, 0x04, 0x14, 0x39, 0x81, 0x41, 0x0a, 0xb9, 0xf3, 0xf4, 0x5b, 0x75, 0x97, 0x4a, 0x46, 0xd6, |
| 146 | 0x30, 0x9e, 0x1d, 0x7a, 0x3b, 0xec, 0xa8, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, |
| 147 | 0x30, 0x16, 0x80, 0x14, 0x82, 0xbd, 0x00, 0xde, 0xcb, 0xc5, 0xe7, 0x72, 0x87, 0x3d, 0x1c, 0x0a, |
| 148 | 0x1e, 0x78, 0x4f, 0xf5, 0xd3, 0xc1, 0x3e, 0xb8, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, |
| 149 | 0x01, 0xff, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, |
| 150 | 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x02, 0x04, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, |
| 151 | 0x04, 0x01, 0xd6, 0x79, 0x02, 0x01, 0x1e, 0x04, 0x03, 0xa1, 0x01, 0x08, 0x30, 0x0a, 0x06, 0x08, |
| 152 | 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x21, 0x00, |
| 153 | 0xae, 0xd8, 0x40, 0x9e, 0x37, 0x3e, 0x5c, 0x9c, 0xe2, 0x93, 0x3d, 0x8c, 0xf7, 0x05, 0x10, 0xe7, |
| 154 | 0xd1, 0x2b, 0x87, 0x8a, 0xee, 0xd6, 0x1e, 0x6c, 0x3b, 0xd2, 0x91, 0x3e, 0xa5, 0xdf, 0x91, 0x20, |
| 155 | 0x02, 0x20, 0x7f, 0x0f, 0x29, 0x54, 0x60, 0x80, 0x07, 0x50, 0x5f, 0x56, 0x6b, 0x9f, 0xe0, 0x94, |
| 156 | 0xb4, 0x3f, 0x3b, 0x0f, 0x61, 0xa0, 0x33, 0x40, 0xe6, 0x1a, 0x42, 0xda, 0x4b, 0xa4, 0xfd, 0x92, |
| 157 | 0xb9, 0x0f, |
| 158 | ]; |
| 159 | |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 160 | lazy_static! { |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 161 | static ref FAKE_PROVISIONED_KEY_BLOB_FOR_TESTING: Mutex<Option<Vec<u8>>> = Mutex::new(None); |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 162 | static ref VFIO_SERVICE: Strong<dyn IVfioHandler> = |
| 163 | wait_for_interface(<BpVfioHandler as IVfioHandler>::get_descriptor()) |
| 164 | .expect("Could not connect to VfioHandler"); |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 165 | static ref NETWORK_SERVICE: Strong<dyn IVmnic> = |
| 166 | wait_for_interface(<BpVmnic as IVmnic>::get_descriptor()) |
| 167 | .expect("Could not connect to Vmnic"); |
Seungjae Yoo | bb7b613 | 2024-06-13 11:07:29 +0900 | [diff] [blame] | 168 | static ref TETHERING_SERVICE: Strong<dyn IVmTethering> = |
| 169 | wait_for_interface(<BpVmTethering as IVmTethering>::get_descriptor()) |
| 170 | .expect("Could not connect to VmTethering"); |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 171 | } |
| 172 | |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 173 | fn is_valid_guest_cid(cid: Cid) -> bool { |
| 174 | (GUEST_CID_MIN..=GUEST_CID_MAX).contains(&cid) |
| 175 | } |
| 176 | |
| 177 | /// Singleton service for allocating globally-unique VM resources, such as the CID, and running |
| 178 | /// singleton servers, like tombstone receiver. |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 179 | #[derive(Clone)] |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 180 | pub struct VirtualizationServiceInternal { |
| 181 | state: Arc<Mutex<GlobalState>>, |
Jeongik Cha | 7add2a4 | 2024-04-02 14:52:39 +0900 | [diff] [blame] | 182 | display_service_set: Arc<Condvar>, |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 183 | } |
| 184 | |
| 185 | impl VirtualizationServiceInternal { |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 186 | pub fn init() -> VirtualizationServiceInternal { |
Jeongik Cha | 7add2a4 | 2024-04-02 14:52:39 +0900 | [diff] [blame] | 187 | let service = VirtualizationServiceInternal { |
| 188 | state: Arc::new(Mutex::new(GlobalState::new())), |
| 189 | display_service_set: Arc::new(Condvar::new()), |
| 190 | }; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 191 | |
| 192 | std::thread::spawn(|| { |
| 193 | if let Err(e) = handle_stream_connection_tombstoned() { |
| 194 | warn!("Error receiving tombstone from guest or writing them. Error: {:?}", e); |
| 195 | } |
| 196 | }); |
| 197 | |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 198 | service |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 199 | } |
| 200 | } |
| 201 | |
| 202 | impl Interface for VirtualizationServiceInternal {} |
| 203 | |
| 204 | impl IVirtualizationServiceInternal for VirtualizationServiceInternal { |
Jeongik Cha | 7add2a4 | 2024-04-02 14:52:39 +0900 | [diff] [blame] | 205 | fn setDisplayService( |
| 206 | &self, |
| 207 | ibinder: &binder::SpIBinder, |
| 208 | ) -> std::result::Result<(), binder::Status> { |
| 209 | check_manage_access()?; |
| 210 | check_use_custom_virtual_machine()?; |
| 211 | let state = &mut *self.state.lock().unwrap(); |
| 212 | state.display_service = Some(ibinder.clone()); |
| 213 | self.display_service_set.notify_all(); |
| 214 | Ok(()) |
| 215 | } |
| 216 | |
Jeongik Cha | eee137d | 2024-04-03 22:13:14 +0900 | [diff] [blame] | 217 | fn clearDisplayService(&self) -> std::result::Result<(), binder::Status> { |
| 218 | check_manage_access()?; |
| 219 | check_use_custom_virtual_machine()?; |
| 220 | let state = &mut *self.state.lock().unwrap(); |
| 221 | state.display_service = None; |
| 222 | self.display_service_set.notify_all(); |
| 223 | Ok(()) |
| 224 | } |
| 225 | |
Jeongik Cha | 7add2a4 | 2024-04-02 14:52:39 +0900 | [diff] [blame] | 226 | fn waitDisplayService(&self) -> std::result::Result<binder::SpIBinder, binder::Status> { |
| 227 | check_manage_access()?; |
| 228 | check_use_custom_virtual_machine()?; |
| 229 | let state = self |
| 230 | .display_service_set |
| 231 | .wait_while(self.state.lock().unwrap(), |state| state.display_service.is_none()) |
| 232 | .unwrap(); |
| 233 | Ok((state.display_service) |
| 234 | .as_ref() |
| 235 | .cloned() |
| 236 | .expect("Display service cannot be None in this context")) |
| 237 | } |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 238 | fn removeMemlockRlimit(&self) -> binder::Result<()> { |
| 239 | let pid = get_calling_pid(); |
| 240 | let lim = libc::rlimit { rlim_cur: libc::RLIM_INFINITY, rlim_max: libc::RLIM_INFINITY }; |
| 241 | |
Andrew Walbran | b58d1b4 | 2023-07-07 13:54:49 +0100 | [diff] [blame] | 242 | // SAFETY: borrowing the new limit struct only |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 243 | let ret = unsafe { libc::prlimit(pid, libc::RLIMIT_MEMLOCK, &lim, std::ptr::null_mut()) }; |
| 244 | |
| 245 | match ret { |
| 246 | 0 => Ok(()), |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 247 | -1 => Err(std::io::Error::last_os_error().into()), |
| 248 | n => Err(anyhow!("Unexpected return value from prlimit(): {n}")), |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 249 | } |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 250 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE) |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 251 | } |
| 252 | |
| 253 | fn allocateGlobalVmContext( |
| 254 | &self, |
| 255 | requester_debug_pid: i32, |
| 256 | ) -> binder::Result<Strong<dyn IGlobalVmContext>> { |
| 257 | check_manage_access()?; |
| 258 | |
| 259 | let requester_uid = get_calling_uid(); |
| 260 | let requester_debug_pid = requester_debug_pid as pid_t; |
| 261 | let state = &mut *self.state.lock().unwrap(); |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 262 | state |
| 263 | .allocate_vm_context(requester_uid, requester_debug_pid) |
| 264 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE) |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 265 | } |
| 266 | |
| 267 | fn atomVmBooted(&self, atom: &AtomVmBooted) -> Result<(), Status> { |
| 268 | forward_vm_booted_atom(atom); |
| 269 | Ok(()) |
| 270 | } |
| 271 | |
| 272 | fn atomVmCreationRequested(&self, atom: &AtomVmCreationRequested) -> Result<(), Status> { |
| 273 | forward_vm_creation_atom(atom); |
| 274 | Ok(()) |
| 275 | } |
| 276 | |
| 277 | fn atomVmExited(&self, atom: &AtomVmExited) -> Result<(), Status> { |
| 278 | forward_vm_exited_atom(atom); |
| 279 | Ok(()) |
| 280 | } |
| 281 | |
| 282 | fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> { |
| 283 | check_debug_access()?; |
| 284 | |
| 285 | let state = &mut *self.state.lock().unwrap(); |
| 286 | let cids = state |
| 287 | .held_contexts |
| 288 | .iter() |
| 289 | .filter_map(|(_, inst)| Weak::upgrade(inst)) |
| 290 | .map(|vm| VirtualMachineDebugInfo { |
| 291 | cid: vm.cid as i32, |
| 292 | temporaryDirectory: vm.get_temp_dir().to_string_lossy().to_string(), |
| 293 | requesterUid: vm.requester_uid as i32, |
Charisee | 96113f3 | 2023-01-26 09:00:42 +0000 | [diff] [blame] | 294 | requesterPid: vm.requester_debug_pid, |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 295 | }) |
| 296 | .collect(); |
| 297 | Ok(cids) |
| 298 | } |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 299 | |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 300 | fn enableTestAttestation(&self) -> binder::Result<()> { |
| 301 | check_manage_access()?; |
| 302 | check_use_custom_virtual_machine()?; |
| 303 | if !cfg!(remote_attestation) { |
| 304 | return Err(Status::new_exception_str( |
| 305 | ExceptionCode::UNSUPPORTED_OPERATION, |
| 306 | Some( |
| 307 | "enableTestAttestation is not supported with the remote_attestation \ |
| 308 | feature disabled", |
| 309 | ), |
| 310 | )) |
| 311 | .with_log(); |
| 312 | } |
| 313 | let res = generate_ecdsa_p256_key_pair() |
| 314 | .context("Failed to generate ECDSA P-256 key pair for testing") |
| 315 | .with_log() |
| 316 | .or_service_specific_exception(-1)?; |
Alice Wang | 5daec07 | 2024-03-15 15:31:17 +0000 | [diff] [blame] | 317 | // Wait until the service VM shuts down, so that the Service VM will be restarted when |
| 318 | // the key generated in the current session will be used for attestation. |
| 319 | // This ensures that different Service VM sessions have the same KEK for the key blob. |
| 320 | service_vm_manager::wait_until_service_vm_shuts_down() |
| 321 | .context("Failed to wait until the service VM shuts down") |
| 322 | .with_log() |
| 323 | .or_service_specific_exception(-1)?; |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 324 | match res { |
| 325 | Response::GenerateEcdsaP256KeyPair(key_pair) => { |
| 326 | FAKE_PROVISIONED_KEY_BLOB_FOR_TESTING |
| 327 | .lock() |
| 328 | .unwrap() |
| 329 | .replace(key_pair.key_blob.to_vec()); |
| 330 | Ok(()) |
| 331 | } |
| 332 | _ => Err(remote_provisioning::to_service_specific_error(res)), |
| 333 | } |
| 334 | .with_log() |
| 335 | } |
| 336 | |
Alice Wang | bff017f | 2023-11-09 14:43:28 +0000 | [diff] [blame] | 337 | fn requestAttestation( |
| 338 | &self, |
| 339 | csr: &[u8], |
| 340 | requester_uid: i32, |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 341 | test_mode: bool, |
Alice Wang | bff017f | 2023-11-09 14:43:28 +0000 | [diff] [blame] | 342 | ) -> binder::Result<Vec<Certificate>> { |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 343 | check_manage_access()?; |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 344 | if !cfg!(remote_attestation) { |
| 345 | return Err(Status::new_exception_str( |
Alice Wang | e9ac2db | 2023-09-08 15:13:13 +0000 | [diff] [blame] | 346 | ExceptionCode::UNSUPPORTED_OPERATION, |
| 347 | Some( |
Alice Wang | a410b64 | 2023-10-18 09:05:15 +0000 | [diff] [blame] | 348 | "requestAttestation is not supported with the remote_attestation feature \ |
| 349 | disabled", |
Alice Wang | e9ac2db | 2023-09-08 15:13:13 +0000 | [diff] [blame] | 350 | ), |
| 351 | )) |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 352 | .with_log(); |
Alice Wang | e9ac2db | 2023-09-08 15:13:13 +0000 | [diff] [blame] | 353 | } |
Alice Wang | 6c6535d | 2024-05-31 06:45:31 +0000 | [diff] [blame] | 354 | if !is_remote_provisioning_hal_declared()? { |
Alice Wang | 0dcab55 | 2024-03-20 14:42:30 +0000 | [diff] [blame] | 355 | return Err(Status::new_exception_str( |
| 356 | ExceptionCode::UNSUPPORTED_OPERATION, |
| 357 | Some("AVF remotely provisioned component service is not declared"), |
| 358 | )) |
| 359 | .with_log(); |
| 360 | } |
Alice Wang | eec580d | 2024-06-07 08:48:06 +0000 | [diff] [blame] | 361 | remote_provisioning::check_remote_attestation_is_supported()?; |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 362 | info!("Received csr. Requestting attestation..."); |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 363 | let (key_blob, certificate_chain) = if test_mode { |
| 364 | check_use_custom_virtual_machine()?; |
| 365 | info!("Using the fake key blob for testing..."); |
| 366 | ( |
| 367 | FAKE_PROVISIONED_KEY_BLOB_FOR_TESTING |
| 368 | .lock() |
| 369 | .unwrap() |
| 370 | .clone() |
| 371 | .ok_or_else(|| anyhow!("No key blob for testing")) |
| 372 | .with_log() |
| 373 | .or_service_specific_exception(-1)?, |
| 374 | FAKE_CERTIFICATE_FOR_TESTING.to_vec(), |
| 375 | ) |
| 376 | } else { |
| 377 | info!("Retrieving the remotely provisioned keys from RKPD..."); |
| 378 | let attestation_key = get_rkpd_attestation_key( |
| 379 | REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME, |
| 380 | requester_uid as u32, |
| 381 | ) |
| 382 | .context("Failed to retrieve the remotely provisioned keys") |
| 383 | .with_log() |
| 384 | .or_service_specific_exception(-1)?; |
| 385 | (attestation_key.keyBlob, attestation_key.encodedCertChain) |
| 386 | }; |
| 387 | let mut certificate_chain = split_x509_certificate_chain(&certificate_chain) |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 388 | .context("Failed to split the remotely provisioned certificate chain") |
| 389 | .with_log() |
| 390 | .or_service_specific_exception(-1)?; |
| 391 | if certificate_chain.is_empty() { |
| 392 | return Err(Status::new_service_specific_error_str( |
| 393 | -1, |
| 394 | Some("The certificate chain should contain at least 1 certificate"), |
| 395 | )) |
| 396 | .with_log(); |
| 397 | } |
Alice Wang | 20b8ebc | 2023-11-17 09:54:47 +0000 | [diff] [blame] | 398 | let certificate = request_attestation( |
| 399 | csr.to_vec(), |
Alice Wang | e64dd18 | 2024-01-17 15:57:55 +0000 | [diff] [blame] | 400 | key_blob, |
Alice Wang | 20b8ebc | 2023-11-17 09:54:47 +0000 | [diff] [blame] | 401 | certificate_chain[0].encodedCertificate.clone(), |
| 402 | ) |
| 403 | .context("Failed to request attestation") |
| 404 | .with_log() |
| 405 | .or_service_specific_exception(-1)?; |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 406 | certificate_chain.insert(0, Certificate { encodedCertificate: certificate }); |
| 407 | |
| 408 | Ok(certificate_chain) |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 409 | } |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 410 | |
Alice Wang | 0362f7f | 2024-03-21 08:16:26 +0000 | [diff] [blame] | 411 | fn isRemoteAttestationSupported(&self) -> binder::Result<bool> { |
Alice Wang | eec580d | 2024-06-07 08:48:06 +0000 | [diff] [blame] | 412 | Ok(is_remote_provisioning_hal_declared()? |
| 413 | && remote_provisioning::is_remote_attestation_supported()) |
Alice Wang | 0362f7f | 2024-03-21 08:16:26 +0000 | [diff] [blame] | 414 | } |
| 415 | |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 416 | fn getAssignableDevices(&self) -> binder::Result<Vec<AssignableDevice>> { |
| 417 | check_use_custom_virtual_machine()?; |
| 418 | |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 419 | Ok(get_assignable_devices()? |
| 420 | .device |
| 421 | .into_iter() |
Jaewan Kim | 0c99c61 | 2024-03-23 00:44:14 +0900 | [diff] [blame] | 422 | .map(|x| AssignableDevice { node: x.sysfs_path, dtbo_label: x.dtbo_label }) |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 423 | .collect::<Vec<_>>()) |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 424 | } |
Inseob Kim | 1ca0f65 | 2023-07-20 17:18:12 +0900 | [diff] [blame] | 425 | |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 426 | fn bindDevicesToVfioDriver( |
| 427 | &self, |
| 428 | devices: &[String], |
| 429 | ) -> binder::Result<Vec<Strong<dyn IBoundDevice>>> { |
Inseob Kim | 1ca0f65 | 2023-07-20 17:18:12 +0900 | [diff] [blame] | 430 | check_use_custom_virtual_machine()?; |
| 431 | |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 432 | let devices = get_assignable_devices()? |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 433 | .device |
| 434 | .into_iter() |
| 435 | .filter_map(|x| { |
| 436 | if devices.contains(&x.sysfs_path) { |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 437 | Some(VfioDev { sysfsPath: x.sysfs_path, dtboLabel: x.dtbo_label }) |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 438 | } else { |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 439 | warn!("device {} is not assignable", x.sysfs_path); |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 440 | None |
| 441 | } |
| 442 | }) |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 443 | .collect::<Vec<VfioDev>>(); |
| 444 | |
| 445 | VFIO_SERVICE.bindDevicesToVfioDriver(devices.as_slice()) |
Inseob Kim | 1ca0f65 | 2023-07-20 17:18:12 +0900 | [diff] [blame] | 446 | } |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 447 | |
| 448 | fn getDtboFile(&self) -> binder::Result<ParcelFileDescriptor> { |
| 449 | check_use_custom_virtual_machine()?; |
| 450 | |
| 451 | let state = &mut *self.state.lock().unwrap(); |
| 452 | let file = state.get_dtbo_file().or_service_specific_exception(-1)?; |
| 453 | Ok(ParcelFileDescriptor::new(file)) |
| 454 | } |
Shikha Panwar | 61a74b5 | 2024-02-16 13:17:01 +0000 | [diff] [blame] | 455 | |
Shikha Panwar | 61a74b5 | 2024-02-16 13:17:01 +0000 | [diff] [blame] | 456 | fn allocateInstanceId(&self) -> binder::Result<[u8; 64]> { |
| 457 | let mut id = [0u8; 64]; |
| 458 | id.try_fill(&mut rand::thread_rng()) |
| 459 | .context("Failed to allocate instance_id") |
| 460 | .or_service_specific_exception(-1)?; |
| 461 | let uid = get_calling_uid(); |
Shikha Panwar | 75e920b | 2024-06-14 06:12:37 +0000 | [diff] [blame] | 462 | info!("Allocated a VM's instance_id: {:?}..., for uid: {:?}", &hex::encode(id)[..8], uid); |
David Drysdale | e64de8e | 2024-02-29 11:54:29 +0000 | [diff] [blame] | 463 | let state = &mut *self.state.lock().unwrap(); |
| 464 | if let Some(sk_state) = &mut state.sk_state { |
| 465 | let user_id = multiuser_get_user_id(uid); |
| 466 | let app_id = multiuser_get_app_id(uid); |
David Drysdale | 1138fa0 | 2024-03-19 13:06:23 +0000 | [diff] [blame] | 467 | info!("Recording possible existence of state for (user_id={user_id}, app_id={app_id})"); |
David Drysdale | e64de8e | 2024-02-29 11:54:29 +0000 | [diff] [blame] | 468 | if let Err(e) = sk_state.add_id(&id, user_id, app_id) { |
| 469 | error!("Failed to record the instance_id: {e:?}"); |
| 470 | } |
| 471 | } |
| 472 | |
Shikha Panwar | 61a74b5 | 2024-02-16 13:17:01 +0000 | [diff] [blame] | 473 | Ok(id) |
| 474 | } |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 475 | |
| 476 | fn removeVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> { |
| 477 | let state = &mut *self.state.lock().unwrap(); |
| 478 | if let Some(sk_state) = &mut state.sk_state { |
Alan Stokes | de40e64 | 2024-06-04 13:36:05 +0100 | [diff] [blame] | 479 | let uid = get_calling_uid(); |
| 480 | info!( |
| 481 | "Removing a VM's instance_id: {:?}, for uid: {:?}", |
| 482 | hex::encode(instance_id), |
| 483 | uid |
| 484 | ); |
| 485 | |
| 486 | let user_id = multiuser_get_user_id(uid); |
| 487 | let app_id = multiuser_get_app_id(uid); |
| 488 | sk_state.delete_id(instance_id, user_id, app_id); |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 489 | } else { |
| 490 | info!("ignoring removeVmInstance() as no ISecretkeeper"); |
| 491 | } |
| 492 | Ok(()) |
| 493 | } |
David Drysdale | 3aa62b3 | 2024-03-25 12:31:48 +0000 | [diff] [blame] | 494 | |
| 495 | fn claimVmInstance(&self, instance_id: &[u8; 64]) -> binder::Result<()> { |
| 496 | let state = &mut *self.state.lock().unwrap(); |
| 497 | if let Some(sk_state) = &mut state.sk_state { |
| 498 | let uid = get_calling_uid(); |
| 499 | info!( |
| 500 | "Claiming a VM's instance_id: {:?}, for uid: {:?}", |
| 501 | hex::encode(instance_id), |
| 502 | uid |
| 503 | ); |
| 504 | |
| 505 | let user_id = multiuser_get_user_id(uid); |
| 506 | let app_id = multiuser_get_app_id(uid); |
| 507 | info!("Recording possible new owner of state for (user_id={user_id}, app_id={app_id})"); |
| 508 | if let Err(e) = sk_state.add_id(instance_id, user_id, app_id) { |
| 509 | error!("Failed to update the instance_id owner: {e:?}"); |
| 510 | } |
| 511 | } else { |
| 512 | info!("ignoring claimVmInstance() as no ISecretkeeper"); |
| 513 | } |
| 514 | Ok(()) |
| 515 | } |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 516 | |
| 517 | fn createTapInterface(&self, iface_name_suffix: &str) -> binder::Result<ParcelFileDescriptor> { |
Seungjae Yoo | a6589bd | 2024-06-11 10:14:07 +0900 | [diff] [blame] | 518 | check_internet_permission()?; |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 519 | check_use_custom_virtual_machine()?; |
| 520 | if !cfg!(network) { |
| 521 | return Err(Status::new_exception_str( |
| 522 | ExceptionCode::UNSUPPORTED_OPERATION, |
| 523 | Some("createTapInterface is not supported with the network feature disabled"), |
| 524 | )) |
| 525 | .with_log(); |
| 526 | } |
Seungjae Yoo | bb7b613 | 2024-06-13 11:07:29 +0900 | [diff] [blame] | 527 | let tap_fd = NETWORK_SERVICE.createTapInterface(iface_name_suffix)?; |
| 528 | |
| 529 | // TODO(340377643): Enabling tethering should be for bridge interface, not TAP interface. |
| 530 | let ret = TETHERING_SERVICE.enableVmTethering(); |
| 531 | if let Err(e) = ret { |
| 532 | if e.exception_code() == ExceptionCode::UNSUPPORTED_OPERATION { |
| 533 | warn!("{}", e.get_description()); |
| 534 | } else { |
| 535 | return Err(e); |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | Ok(tap_fd) |
Seungjae Yoo | 13af0b6 | 2024-05-20 14:15:13 +0900 | [diff] [blame] | 540 | } |
Seungjae Yoo | 3271f17 | 2024-06-11 10:14:07 +0900 | [diff] [blame] | 541 | |
| 542 | fn deleteTapInterface(&self, tap_fd: &ParcelFileDescriptor) -> binder::Result<()> { |
| 543 | check_internet_permission()?; |
| 544 | check_use_custom_virtual_machine()?; |
| 545 | if !cfg!(network) { |
| 546 | return Err(Status::new_exception_str( |
| 547 | ExceptionCode::UNSUPPORTED_OPERATION, |
| 548 | Some("deleteTapInterface is not supported with the network feature disabled"), |
| 549 | )) |
| 550 | .with_log(); |
| 551 | } |
| 552 | NETWORK_SERVICE.deleteTapInterface(tap_fd) |
| 553 | } |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 554 | } |
| 555 | |
| 556 | impl IVirtualizationMaintenance for VirtualizationServiceInternal { |
| 557 | fn appRemoved(&self, user_id: i32, app_id: i32) -> binder::Result<()> { |
| 558 | let state = &mut *self.state.lock().unwrap(); |
| 559 | if let Some(sk_state) = &mut state.sk_state { |
| 560 | info!("packageRemoved(user_id={user_id}, app_id={app_id})"); |
| 561 | sk_state.delete_ids_for_app(user_id, app_id).or_service_specific_exception(-1)?; |
| 562 | } else { |
| 563 | info!("ignoring packageRemoved(user_id={user_id}, app_id={app_id})"); |
| 564 | } |
| 565 | Ok(()) |
| 566 | } |
| 567 | |
| 568 | fn userRemoved(&self, user_id: i32) -> binder::Result<()> { |
| 569 | let state = &mut *self.state.lock().unwrap(); |
| 570 | if let Some(sk_state) = &mut state.sk_state { |
| 571 | info!("userRemoved({user_id})"); |
| 572 | sk_state.delete_ids_for_user(user_id).or_service_specific_exception(-1)?; |
| 573 | } else { |
| 574 | info!("ignoring userRemoved(user_id={user_id})"); |
| 575 | } |
| 576 | Ok(()) |
| 577 | } |
Alan Stokes | 30ccacb | 2024-02-20 14:59:02 +0000 | [diff] [blame] | 578 | |
| 579 | fn performReconciliation( |
| 580 | &self, |
David Drysdale | 1138fa0 | 2024-03-19 13:06:23 +0000 | [diff] [blame] | 581 | callback: &Strong<dyn IVirtualizationReconciliationCallback>, |
Alan Stokes | 30ccacb | 2024-02-20 14:59:02 +0000 | [diff] [blame] | 582 | ) -> binder::Result<()> { |
David Drysdale | 1138fa0 | 2024-03-19 13:06:23 +0000 | [diff] [blame] | 583 | let state = &mut *self.state.lock().unwrap(); |
| 584 | if let Some(sk_state) = &mut state.sk_state { |
| 585 | info!("performReconciliation()"); |
| 586 | sk_state.reconcile(callback).or_service_specific_exception(-1)?; |
| 587 | } else { |
| 588 | info!("ignoring performReconciliation()"); |
| 589 | } |
| 590 | Ok(()) |
Alan Stokes | 30ccacb | 2024-02-20 14:59:02 +0000 | [diff] [blame] | 591 | } |
Inseob Kim | 1ca0f65 | 2023-07-20 17:18:12 +0900 | [diff] [blame] | 592 | } |
| 593 | |
Inseob Kim | c4a774d | 2023-08-30 12:48:43 +0900 | [diff] [blame] | 594 | #[derive(Debug, Deserialize)] |
| 595 | struct Device { |
Jaewan Kim | 35e818d | 2023-10-18 05:36:38 +0000 | [diff] [blame] | 596 | dtbo_label: String, |
Inseob Kim | c4a774d | 2023-08-30 12:48:43 +0900 | [diff] [blame] | 597 | sysfs_path: String, |
| 598 | } |
| 599 | |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 600 | #[derive(Debug, Default, Deserialize)] |
Inseob Kim | c4a774d | 2023-08-30 12:48:43 +0900 | [diff] [blame] | 601 | struct Devices { |
| 602 | device: Vec<Device>, |
| 603 | } |
| 604 | |
Inseob Kim | 7307a89 | 2023-09-14 13:37:58 +0900 | [diff] [blame] | 605 | fn get_assignable_devices() -> binder::Result<Devices> { |
| 606 | let xml_path = Path::new("/vendor/etc/avf/assignable_devices.xml"); |
| 607 | if !xml_path.exists() { |
| 608 | return Ok(Devices { ..Default::default() }); |
| 609 | } |
| 610 | |
| 611 | let xml = fs::read(xml_path) |
| 612 | .context("Failed to read assignable_devices.xml") |
| 613 | .with_log() |
| 614 | .or_service_specific_exception(-1)?; |
| 615 | |
| 616 | let xml = String::from_utf8(xml) |
| 617 | .context("assignable_devices.xml is not a valid UTF-8 file") |
| 618 | .with_log() |
| 619 | .or_service_specific_exception(-1)?; |
| 620 | |
| 621 | let mut devices: Devices = serde_xml_rs::from_str(&xml) |
| 622 | .context("can't parse assignable_devices.xml") |
| 623 | .with_log() |
| 624 | .or_service_specific_exception(-1)?; |
| 625 | |
| 626 | let mut device_set = HashSet::new(); |
| 627 | devices.device.retain(move |device| { |
| 628 | if device_set.contains(&device.sysfs_path) { |
| 629 | warn!("duplicated assignable device {device:?}; ignoring..."); |
| 630 | return false; |
| 631 | } |
| 632 | |
| 633 | if !Path::new(&device.sysfs_path).exists() { |
| 634 | warn!("assignable device {device:?} doesn't exist; ignoring..."); |
| 635 | return false; |
| 636 | } |
| 637 | |
| 638 | device_set.insert(device.sysfs_path.clone()); |
| 639 | true |
| 640 | }); |
| 641 | Ok(devices) |
| 642 | } |
| 643 | |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 644 | fn split_x509_certificate_chain(mut cert_chain: &[u8]) -> Result<Vec<Certificate>> { |
| 645 | let mut out = Vec::new(); |
| 646 | while !cert_chain.is_empty() { |
Alice Wang | fc5a44a | 2023-12-21 12:22:40 +0000 | [diff] [blame] | 647 | let cert = X509::from_der(cert_chain)?; |
| 648 | let end = cert.to_der()?.len(); |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 649 | out.push(Certificate { encodedCertificate: cert_chain[..end].to_vec() }); |
Alice Wang | fc5a44a | 2023-12-21 12:22:40 +0000 | [diff] [blame] | 650 | cert_chain = &cert_chain[end..]; |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 651 | } |
| 652 | Ok(out) |
| 653 | } |
| 654 | |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 655 | #[derive(Debug, Default)] |
| 656 | struct GlobalVmInstance { |
| 657 | /// The unique CID assigned to the VM for vsock communication. |
| 658 | cid: Cid, |
| 659 | /// UID of the client who requested this VM instance. |
| 660 | requester_uid: uid_t, |
| 661 | /// PID of the client who requested this VM instance. |
| 662 | requester_debug_pid: pid_t, |
| 663 | } |
| 664 | |
| 665 | impl GlobalVmInstance { |
| 666 | fn get_temp_dir(&self) -> PathBuf { |
| 667 | let cid = self.cid; |
| 668 | format!("{TEMPORARY_DIRECTORY}/{cid}").into() |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | /// The mutable state of the VirtualizationServiceInternal. There should only be one instance |
| 673 | /// of this struct. |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 674 | struct GlobalState { |
| 675 | /// VM contexts currently allocated to running VMs. A CID is never recycled as long |
| 676 | /// as there is a strong reference held by a GlobalVmContext. |
| 677 | held_contexts: HashMap<Cid, Weak<GlobalVmInstance>>, |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 678 | |
| 679 | /// Cached read-only FD of VM DTBO file. Also serves as a lock for creating the file. |
| 680 | dtbo_file: Mutex<Option<File>>, |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 681 | |
| 682 | /// State relating to secrets held by (optional) Secretkeeper instance on behalf of VMs. |
| 683 | sk_state: Option<maintenance::State>, |
Jeongik Cha | 7add2a4 | 2024-04-02 14:52:39 +0900 | [diff] [blame] | 684 | |
| 685 | display_service: Option<binder::SpIBinder>, |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 686 | } |
| 687 | |
| 688 | impl GlobalState { |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 689 | fn new() -> Self { |
| 690 | Self { |
| 691 | held_contexts: HashMap::new(), |
| 692 | dtbo_file: Mutex::new(None), |
| 693 | sk_state: maintenance::State::new(), |
Jeongik Cha | 7add2a4 | 2024-04-02 14:52:39 +0900 | [diff] [blame] | 694 | display_service: None, |
David Drysdale | 79af266 | 2024-02-19 14:50:31 +0000 | [diff] [blame] | 695 | } |
| 696 | } |
| 697 | |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 698 | /// Get the next available CID, or an error if we have run out. The last CID used is stored in |
| 699 | /// a system property so that restart of virtualizationservice doesn't reuse CID while the host |
| 700 | /// Android is up. |
| 701 | fn get_next_available_cid(&mut self) -> Result<Cid> { |
| 702 | // Start trying to find a CID from the last used CID + 1. This ensures |
| 703 | // that we do not eagerly recycle CIDs. It makes debugging easier but |
| 704 | // also means that retrying to allocate a CID, eg. because it is |
| 705 | // erroneously occupied by a process, will not recycle the same CID. |
| 706 | let last_cid_prop = |
| 707 | system_properties::read(SYSPROP_LAST_CID)?.and_then(|val| match val.parse::<Cid>() { |
| 708 | Ok(num) => { |
| 709 | if is_valid_guest_cid(num) { |
| 710 | Some(num) |
| 711 | } else { |
| 712 | error!("Invalid value '{}' of property '{}'", num, SYSPROP_LAST_CID); |
| 713 | None |
| 714 | } |
| 715 | } |
| 716 | Err(_) => { |
| 717 | error!("Invalid value '{}' of property '{}'", val, SYSPROP_LAST_CID); |
| 718 | None |
| 719 | } |
| 720 | }); |
| 721 | |
| 722 | let first_cid = if let Some(last_cid) = last_cid_prop { |
| 723 | if last_cid == GUEST_CID_MAX { |
| 724 | GUEST_CID_MIN |
| 725 | } else { |
| 726 | last_cid + 1 |
| 727 | } |
| 728 | } else { |
| 729 | GUEST_CID_MIN |
| 730 | }; |
| 731 | |
| 732 | let cid = self |
| 733 | .find_available_cid(first_cid..=GUEST_CID_MAX) |
| 734 | .or_else(|| self.find_available_cid(GUEST_CID_MIN..first_cid)) |
| 735 | .ok_or_else(|| anyhow!("Could not find an available CID."))?; |
| 736 | |
| 737 | system_properties::write(SYSPROP_LAST_CID, &format!("{}", cid))?; |
| 738 | Ok(cid) |
| 739 | } |
| 740 | |
| 741 | fn find_available_cid<I>(&self, mut range: I) -> Option<Cid> |
| 742 | where |
| 743 | I: Iterator<Item = Cid>, |
| 744 | { |
| 745 | range.find(|cid| !self.held_contexts.contains_key(cid)) |
| 746 | } |
| 747 | |
| 748 | fn allocate_vm_context( |
| 749 | &mut self, |
| 750 | requester_uid: uid_t, |
| 751 | requester_debug_pid: pid_t, |
| 752 | ) -> Result<Strong<dyn IGlobalVmContext>> { |
| 753 | // Garbage collect unused VM contexts. |
| 754 | self.held_contexts.retain(|_, instance| instance.strong_count() > 0); |
| 755 | |
| 756 | let cid = self.get_next_available_cid()?; |
| 757 | let instance = Arc::new(GlobalVmInstance { cid, requester_uid, requester_debug_pid }); |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 758 | create_temporary_directory(&instance.get_temp_dir(), Some(requester_uid))?; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 759 | |
| 760 | self.held_contexts.insert(cid, Arc::downgrade(&instance)); |
| 761 | let binder = GlobalVmContext { instance, ..Default::default() }; |
| 762 | Ok(BnGlobalVmContext::new_binder(binder, BinderFeatures::default())) |
| 763 | } |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 764 | |
| 765 | fn get_dtbo_file(&mut self) -> Result<File> { |
| 766 | let mut file = self.dtbo_file.lock().unwrap(); |
| 767 | |
| 768 | let fd = if let Some(ref_fd) = &*file { |
| 769 | ref_fd.try_clone()? |
| 770 | } else { |
| 771 | let path = get_or_create_common_dir()?.join("vm.dtbo"); |
| 772 | if path.exists() { |
| 773 | // All temporary files are deleted when the service is started. |
| 774 | // If the file exists but the FD is not cached, the file is |
| 775 | // likely corrupted. |
| 776 | remove_file(&path).context("Failed to clone cached VM DTBO file descriptor")?; |
| 777 | } |
| 778 | |
| 779 | // Open a write-only file descriptor for vfio_handler. |
| 780 | let write_fd = File::create(&path).context("Failed to create VM DTBO file")?; |
Jakob Vukalovic | d42aa2c | 2023-11-09 16:04:00 +0000 | [diff] [blame] | 781 | VFIO_SERVICE.writeVmDtbo(&ParcelFileDescriptor::new(write_fd))?; |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 782 | |
| 783 | // Open read-only. This FD will be cached and returned to clients. |
| 784 | let read_fd = File::open(&path).context("Failed to open VM DTBO file")?; |
| 785 | let read_fd_clone = |
| 786 | read_fd.try_clone().context("Failed to clone VM DTBO file descriptor")?; |
| 787 | *file = Some(read_fd); |
| 788 | read_fd_clone |
| 789 | }; |
| 790 | |
| 791 | Ok(fd) |
| 792 | } |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 793 | } |
| 794 | |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 795 | fn create_temporary_directory(path: &PathBuf, requester_uid: Option<uid_t>) -> Result<()> { |
| 796 | // Directory may exist if previous attempt to create it had failed. |
| 797 | // Delete it before trying again. |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 798 | if path.as_path().exists() { |
| 799 | remove_temporary_dir(path).unwrap_or_else(|e| { |
| 800 | warn!("Could not delete temporary directory {:?}: {}", path, e); |
| 801 | }); |
| 802 | } |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 803 | // Create directory. |
| 804 | create_dir(path).with_context(|| format!("Could not create temporary directory {:?}", path))?; |
| 805 | // If provided, change ownership to client's UID but system's GID, and permissions 0700. |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 806 | // If the chown() fails, this will leave behind an empty directory that will get removed |
| 807 | // at the next attempt, or if virtualizationservice is restarted. |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 808 | if let Some(uid) = requester_uid { |
| 809 | chown(path, Some(Uid::from_raw(uid)), None).with_context(|| { |
| 810 | format!("Could not set ownership of temporary directory {:?}", path) |
| 811 | })?; |
| 812 | } |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 813 | Ok(()) |
| 814 | } |
| 815 | |
| 816 | /// Removes a directory owned by a different user by first changing its owner back |
| 817 | /// to VirtualizationService. |
| 818 | pub fn remove_temporary_dir(path: &PathBuf) -> Result<()> { |
Alice Wang | d1b11a0 | 2023-04-18 12:30:20 +0000 | [diff] [blame] | 819 | ensure!(path.as_path().is_dir(), "Path {:?} is not a directory", path); |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 820 | chown(path, Some(Uid::current()), None)?; |
| 821 | set_permissions(path, Permissions::from_mode(0o700))?; |
Alice Wang | d1b11a0 | 2023-04-18 12:30:20 +0000 | [diff] [blame] | 822 | remove_dir_all(path)?; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 823 | Ok(()) |
| 824 | } |
| 825 | |
David Brazdil | 2dfefd1 | 2023-11-17 14:07:36 +0000 | [diff] [blame] | 826 | fn get_or_create_common_dir() -> Result<PathBuf> { |
| 827 | let path = Path::new(TEMPORARY_DIRECTORY).join("common"); |
| 828 | if !path.exists() { |
| 829 | create_temporary_directory(&path, None)?; |
| 830 | } |
| 831 | Ok(path) |
| 832 | } |
| 833 | |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 834 | /// Implementation of the AIDL `IGlobalVmContext` interface. |
| 835 | #[derive(Debug, Default)] |
| 836 | struct GlobalVmContext { |
| 837 | /// Strong reference to the context's instance data structure. |
| 838 | instance: Arc<GlobalVmInstance>, |
| 839 | /// Keeps our service process running as long as this VM context exists. |
| 840 | #[allow(dead_code)] |
| 841 | lazy_service_guard: LazyServiceGuard, |
| 842 | } |
| 843 | |
| 844 | impl Interface for GlobalVmContext {} |
| 845 | |
| 846 | impl IGlobalVmContext for GlobalVmContext { |
| 847 | fn getCid(&self) -> binder::Result<i32> { |
| 848 | Ok(self.instance.cid as i32) |
| 849 | } |
| 850 | |
| 851 | fn getTemporaryDirectory(&self) -> binder::Result<String> { |
| 852 | Ok(self.instance.get_temp_dir().to_string_lossy().to_string()) |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | fn handle_stream_connection_tombstoned() -> Result<()> { |
| 857 | // Should not listen for tombstones on a guest VM's port. |
| 858 | assert!(!is_valid_guest_cid(VM_TOMBSTONES_SERVICE_PORT as Cid)); |
| 859 | let listener = |
| 860 | VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as Cid)?; |
| 861 | for incoming_stream in listener.incoming() { |
| 862 | let mut incoming_stream = match incoming_stream { |
| 863 | Err(e) => { |
| 864 | warn!("invalid incoming connection: {:?}", e); |
| 865 | continue; |
| 866 | } |
| 867 | Ok(s) => s, |
| 868 | }; |
| 869 | std::thread::spawn(move || { |
| 870 | if let Err(e) = handle_tombstone(&mut incoming_stream) { |
| 871 | error!("Failed to write tombstone- {:?}", e); |
| 872 | } |
| 873 | }); |
| 874 | } |
| 875 | Ok(()) |
| 876 | } |
| 877 | |
| 878 | fn handle_tombstone(stream: &mut VsockStream) -> Result<()> { |
| 879 | if let Ok(addr) = stream.peer_addr() { |
| 880 | info!("Vsock Stream connected to cid={} for tombstones", addr.cid()); |
| 881 | } |
| 882 | let tb_connection = |
| 883 | TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone) |
| 884 | .context("Failed to connect to tombstoned")?; |
| 885 | let mut text_output = tb_connection |
| 886 | .text_output |
| 887 | .as_ref() |
| 888 | .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?; |
| 889 | let mut num_bytes_read = 0; |
| 890 | loop { |
| 891 | let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN]; |
| 892 | let n = stream |
| 893 | .read(&mut chunk_recv) |
| 894 | .context("Failed to read tombstone data from Vsock stream")?; |
| 895 | if n == 0 { |
| 896 | break; |
| 897 | } |
| 898 | num_bytes_read += n; |
| 899 | text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?; |
| 900 | } |
| 901 | info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read); |
| 902 | tb_connection.notify_completion()?; |
| 903 | Ok(()) |
| 904 | } |
| 905 | |
Alice Wang | 6c6535d | 2024-05-31 06:45:31 +0000 | [diff] [blame] | 906 | /// Returns true if the AVF remotely provisioned component service is declared in the |
| 907 | /// VINTF manifest. |
| 908 | pub(crate) fn is_remote_provisioning_hal_declared() -> binder::Result<bool> { |
Alice Wang | 0dcab55 | 2024-03-20 14:42:30 +0000 | [diff] [blame] | 909 | Ok(binder::is_declared(REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME)?) |
| 910 | } |
| 911 | |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 912 | /// Checks whether the caller has a specific permission |
| 913 | fn check_permission(perm: &str) -> binder::Result<()> { |
| 914 | let calling_pid = get_calling_pid(); |
| 915 | let calling_uid = get_calling_uid(); |
| 916 | // Root can do anything |
| 917 | if calling_uid == 0 { |
| 918 | return Ok(()); |
| 919 | } |
| 920 | let perm_svc: Strong<dyn IPermissionController::IPermissionController> = |
Frederick Mayle | b2a0287 | 2024-05-08 13:35:12 -0700 | [diff] [blame] | 921 | binder::wait_for_interface("permission")?; |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 922 | if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? { |
| 923 | Ok(()) |
| 924 | } else { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 925 | Err(anyhow!("does not have the {} permission", perm)) |
| 926 | .or_binder_exception(ExceptionCode::SECURITY) |
David Brazdil | afc9a9e | 2023-01-12 16:08:10 +0000 | [diff] [blame] | 927 | } |
| 928 | } |
| 929 | |
| 930 | /// Check whether the caller of the current Binder method is allowed to call debug methods. |
| 931 | fn check_debug_access() -> binder::Result<()> { |
| 932 | check_permission("android.permission.DEBUG_VIRTUAL_MACHINE") |
| 933 | } |
| 934 | |
| 935 | /// Check whether the caller of the current Binder method is allowed to manage VMs |
| 936 | fn check_manage_access() -> binder::Result<()> { |
| 937 | check_permission("android.permission.MANAGE_VIRTUAL_MACHINE") |
| 938 | } |
Inseob Kim | 53d0b21 | 2023-07-20 16:58:37 +0900 | [diff] [blame] | 939 | |
| 940 | /// Check whether the caller of the current Binder method is allowed to use custom VMs |
| 941 | fn check_use_custom_virtual_machine() -> binder::Result<()> { |
| 942 | check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE") |
| 943 | } |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 944 | |
Seungjae Yoo | a6589bd | 2024-06-11 10:14:07 +0900 | [diff] [blame] | 945 | /// Check whether the caller of the current Binder method is allowed to create socket and |
| 946 | /// establish connection between the VM and the Internet. |
| 947 | fn check_internet_permission() -> binder::Result<()> { |
| 948 | check_permission("android.permission.INTERNET") |
| 949 | } |
| 950 | |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 951 | #[cfg(test)] |
| 952 | mod tests { |
| 953 | use super::*; |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 954 | |
| 955 | const TEST_RKP_CERT_CHAIN_PATH: &str = "testdata/rkp_cert_chain.der"; |
| 956 | |
| 957 | #[test] |
| 958 | fn splitting_x509_certificate_chain_succeeds() -> Result<()> { |
| 959 | let bytes = fs::read(TEST_RKP_CERT_CHAIN_PATH)?; |
| 960 | let cert_chain = split_x509_certificate_chain(&bytes)?; |
| 961 | |
| 962 | assert_eq!(4, cert_chain.len()); |
| 963 | for cert in cert_chain { |
Alice Wang | fc5a44a | 2023-12-21 12:22:40 +0000 | [diff] [blame] | 964 | let x509_cert = X509::from_der(&cert.encodedCertificate)?; |
| 965 | assert_eq!(x509_cert.to_der()?.len(), cert.encodedCertificate.len()); |
Alice Wang | 4c6c558 | 2023-11-23 15:07:18 +0000 | [diff] [blame] | 966 | } |
| 967 | Ok(()) |
| 968 | } |
| 969 | } |