Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 1 | // Copyright 2022, 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 | |
Alice Wang | 59a9e56 | 2022-10-04 15:24:10 +0000 | [diff] [blame] | 15 | //! This module handles the interaction with virtual machine payload service. |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 16 | |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 17 | // We're implementing unsafe functions, but we still want warnings on unsafe usage within them. |
| 18 | #![warn(unsafe_op_in_unsafe_fn)] |
| 19 | |
Alice Wang | 13a2b1b | 2022-10-07 07:57:08 +0000 | [diff] [blame] | 20 | use android_system_virtualization_payload::aidl::android::system::virtualization::payload::IVmPayloadService::{ |
Alice Wang | 43c884b | 2022-10-24 09:42:40 +0000 | [diff] [blame] | 21 | IVmPayloadService, VM_PAYLOAD_SERVICE_SOCKET_NAME, VM_APK_CONTENTS_PATH}; |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 22 | use anyhow::{ensure, bail, Context, Result}; |
Alice Wang | 43c884b | 2022-10-24 09:42:40 +0000 | [diff] [blame] | 23 | use binder::{Strong, unstable_api::{AIBinder, new_spibinder}}; |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 24 | use lazy_static::lazy_static; |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 25 | use log::{error, info, Level}; |
David Brazdil | 671e614 | 2022-11-16 11:47:27 +0000 | [diff] [blame] | 26 | use rpcbinder::{get_unix_domain_rpc_interface, RpcServer}; |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 27 | use std::convert::Infallible; |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 28 | use std::ffi::CString; |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 29 | use std::fmt::Debug; |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 30 | use std::os::raw::{c_char, c_void}; |
Alan Stokes | 78d2470 | 2022-11-21 15:28:31 +0000 | [diff] [blame] | 31 | use std::ptr; |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 32 | use std::sync::{Mutex, atomic::{AtomicBool, Ordering}}; |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 33 | |
| 34 | lazy_static! { |
| 35 | static ref VM_APK_CONTENTS_PATH_C: CString = |
| 36 | CString::new(VM_APK_CONTENTS_PATH).expect("CString::new failed"); |
Alan Stokes | 0cbfdf9 | 2022-11-21 17:17:53 +0000 | [diff] [blame] | 37 | static ref PAYLOAD_CONNECTION: Mutex<Option<Strong<dyn IVmPayloadService>>> = Mutex::default(); |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 38 | } |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 39 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 40 | static ALREADY_NOTIFIED: AtomicBool = AtomicBool::new(false); |
| 41 | |
Alan Stokes | 0cbfdf9 | 2022-11-21 17:17:53 +0000 | [diff] [blame] | 42 | /// Return a connection to the payload service in Microdroid Manager. Uses the existing connection |
| 43 | /// if there is one, otherwise attempts to create a new one. |
| 44 | fn get_vm_payload_service() -> Result<Strong<dyn IVmPayloadService>> { |
| 45 | let mut connection = PAYLOAD_CONNECTION.lock().unwrap(); |
| 46 | if let Some(strong) = &*connection { |
| 47 | Ok(strong.clone()) |
| 48 | } else { |
| 49 | let new_connection: Strong<dyn IVmPayloadService> = get_unix_domain_rpc_interface( |
| 50 | VM_PAYLOAD_SERVICE_SOCKET_NAME, |
| 51 | ) |
| 52 | .context(format!("Failed to connect to service: {}", VM_PAYLOAD_SERVICE_SOCKET_NAME))?; |
| 53 | *connection = Some(new_connection.clone()); |
| 54 | Ok(new_connection) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// Make sure our logging goes to logcat. It is harmless to call this more than once. |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 59 | fn initialize_logging() { |
| 60 | android_logger::init_once( |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 61 | android_logger::Config::default().with_tag("vm_payload").with_min_level(Level::Info), |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 62 | ); |
| 63 | } |
| 64 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 65 | /// In many cases clients can't do anything useful if API calls fail, and the failure |
| 66 | /// generally indicates that the VM is exiting or otherwise doomed. So rather than |
| 67 | /// returning a non-actionable error indication we just log the problem and abort |
| 68 | /// the process. |
| 69 | fn unwrap_or_abort<T, E: Debug>(result: Result<T, E>) -> T { |
| 70 | result.unwrap_or_else(|e| { |
| 71 | let msg = format!("{:?}", e); |
| 72 | error!("{msg}"); |
| 73 | panic!("{msg}") |
| 74 | }) |
| 75 | } |
| 76 | |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 77 | /// Notifies the host that the payload is ready. |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 78 | /// Panics on failure. |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 79 | #[no_mangle] |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 80 | pub extern "C" fn AVmPayload_notifyPayloadReady() { |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 81 | initialize_logging(); |
| 82 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 83 | if !ALREADY_NOTIFIED.swap(true, Ordering::Relaxed) { |
| 84 | unwrap_or_abort(try_notify_payload_ready()); |
| 85 | |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 86 | info!("Notified host payload ready successfully"); |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 87 | } |
| 88 | } |
| 89 | |
| 90 | /// Notifies the host that the payload is ready. |
| 91 | /// Returns a `Result` containing error information if failed. |
| 92 | fn try_notify_payload_ready() -> Result<()> { |
Alice Wang | 59a9e56 | 2022-10-04 15:24:10 +0000 | [diff] [blame] | 93 | get_vm_payload_service()?.notifyPayloadReady().context("Cannot notify payload ready") |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 94 | } |
| 95 | |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 96 | /// Runs a binder RPC server, serving the supplied binder service implementation on the given vsock |
| 97 | /// port. |
| 98 | /// |
| 99 | /// If and when the server is ready for connections (it is listening on the port), `on_ready` is |
| 100 | /// called to allow appropriate action to be taken - e.g. to notify clients that they may now |
| 101 | /// attempt to connect. |
| 102 | /// |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 103 | /// The current thread joins the binder thread pool to handle incoming messages. |
| 104 | /// This function never returns. |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 105 | /// |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 106 | /// Panics on error (including unexpected server exit). |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 107 | /// |
| 108 | /// # Safety |
| 109 | /// |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 110 | /// If present, the `on_ready` callback must be a valid function pointer, which will be called at |
| 111 | /// most once, while this function is executing, with the `param` parameter. |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 112 | #[no_mangle] |
| 113 | pub unsafe extern "C" fn AVmPayload_runVsockRpcServer( |
| 114 | service: *mut AIBinder, |
| 115 | port: u32, |
| 116 | on_ready: Option<unsafe extern "C" fn(param: *mut c_void)>, |
| 117 | param: *mut c_void, |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 118 | ) -> Infallible { |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 119 | initialize_logging(); |
| 120 | |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 121 | // SAFETY: try_run_vsock_server has the same requirements as this function |
| 122 | unwrap_or_abort(unsafe { try_run_vsock_server(service, port, on_ready, param) }) |
| 123 | } |
| 124 | |
| 125 | /// # Safety: Same as `AVmPayload_runVsockRpcServer`. |
| 126 | unsafe fn try_run_vsock_server( |
| 127 | service: *mut AIBinder, |
| 128 | port: u32, |
| 129 | on_ready: Option<unsafe extern "C" fn(param: *mut c_void)>, |
| 130 | param: *mut c_void, |
| 131 | ) -> Result<Infallible> { |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 132 | // SAFETY: AIBinder returned has correct reference count, and the ownership can |
| 133 | // safely be taken by new_spibinder. |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 134 | let service = unsafe { new_spibinder(service) }; |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 135 | if let Some(service) = service { |
David Brazdil | 671e614 | 2022-11-16 11:47:27 +0000 | [diff] [blame] | 136 | match RpcServer::new_vsock(service, port) { |
| 137 | Ok(server) => { |
| 138 | if let Some(on_ready) = on_ready { |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 139 | // SAFETY: We're calling the callback with the parameter specified within the |
| 140 | // allowed lifetime. |
| 141 | unsafe { on_ready(param) }; |
David Brazdil | 671e614 | 2022-11-16 11:47:27 +0000 | [diff] [blame] | 142 | } |
| 143 | server.join(); |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 144 | bail!("RpcServer unexpectedly terminated"); |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 145 | } |
David Brazdil | 671e614 | 2022-11-16 11:47:27 +0000 | [diff] [blame] | 146 | Err(err) => { |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 147 | bail!("Failed to start RpcServer: {:?}", err); |
David Brazdil | 671e614 | 2022-11-16 11:47:27 +0000 | [diff] [blame] | 148 | } |
| 149 | } |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 150 | } else { |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 151 | bail!("Failed to convert the given service from AIBinder to SpIBinder."); |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 152 | } |
| 153 | } |
| 154 | |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 155 | /// Get a secret that is uniquely bound to this VM instance. |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 156 | /// Panics on failure. |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 157 | /// |
| 158 | /// # Safety |
| 159 | /// |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 160 | /// Behavior is undefined if any of the following conditions are violated: |
| 161 | /// |
| 162 | /// * `identifier` must be [valid] for reads of `identifier_size` bytes. |
| 163 | /// * `secret` must be [valid] for writes of `size` bytes. |
| 164 | /// |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 165 | /// [valid]: ptr#safety |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 166 | #[no_mangle] |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 167 | pub unsafe extern "C" fn AVmPayload_getVmInstanceSecret( |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 168 | identifier: *const u8, |
| 169 | identifier_size: usize, |
| 170 | secret: *mut u8, |
| 171 | size: usize, |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 172 | ) { |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 173 | initialize_logging(); |
| 174 | |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 175 | // SAFETY: See the requirements on `identifier` above. |
| 176 | let identifier = unsafe { std::slice::from_raw_parts(identifier, identifier_size) }; |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 177 | let vm_secret = unwrap_or_abort(try_get_vm_instance_secret(identifier, size)); |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 178 | |
| 179 | // SAFETY: See the requirements on `secret` above; `vm_secret` is known to have length `size`, |
| 180 | // and cannot overlap `secret` because we just allocated it. |
| 181 | unsafe { |
| 182 | ptr::copy_nonoverlapping(vm_secret.as_ptr(), secret, size); |
| 183 | } |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 184 | } |
| 185 | |
| 186 | fn try_get_vm_instance_secret(identifier: &[u8], size: usize) -> Result<Vec<u8>> { |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 187 | let vm_secret = get_vm_payload_service()? |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 188 | .getVmInstanceSecret(identifier, i32::try_from(size)?) |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 189 | .context("Cannot get VM instance secret")?; |
| 190 | ensure!( |
| 191 | vm_secret.len() == size, |
| 192 | "Returned secret has {} bytes, expected {}", |
| 193 | vm_secret.len(), |
| 194 | size |
| 195 | ); |
| 196 | Ok(vm_secret) |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 197 | } |
| 198 | |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 199 | /// Get the VM's attestation chain. |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 200 | /// Panics on failure. |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 201 | /// |
| 202 | /// # Safety |
| 203 | /// |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 204 | /// Behavior is undefined if any of the following conditions are violated: |
| 205 | /// |
| 206 | /// * `data` must be [valid] for writes of `size` bytes. |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 207 | /// |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 208 | /// [valid]: ptr#safety |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 209 | #[no_mangle] |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 210 | pub unsafe extern "C" fn AVmPayload_getDiceAttestationChain(data: *mut u8, size: usize) -> usize { |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 211 | initialize_logging(); |
| 212 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 213 | let chain = unwrap_or_abort(try_get_dice_attestation_chain()); |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 214 | // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed |
| 215 | // the length of either buffer, and `chain` cannot overlap `data` because we just allocated it. |
| 216 | unsafe { ptr::copy_nonoverlapping(chain.as_ptr(), data, std::cmp::min(chain.len(), size)) }; |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 217 | chain.len() |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 218 | } |
| 219 | |
| 220 | fn try_get_dice_attestation_chain() -> Result<Vec<u8>> { |
| 221 | get_vm_payload_service()?.getDiceAttestationChain().context("Cannot get attestation chain") |
| 222 | } |
| 223 | |
| 224 | /// Get the VM's attestation CDI. |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 225 | /// Panics on failure. |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 226 | /// |
| 227 | /// # Safety |
| 228 | /// |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 229 | /// Behavior is undefined if any of the following conditions are violated: |
| 230 | /// |
| 231 | /// * `data` must be [valid] for writes of `size` bytes. |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 232 | /// |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 233 | /// [valid]: ptr#safety |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 234 | #[no_mangle] |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 235 | pub unsafe extern "C" fn AVmPayload_getDiceAttestationCdi(data: *mut u8, size: usize) -> usize { |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 236 | initialize_logging(); |
| 237 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 238 | let cdi = unwrap_or_abort(try_get_dice_attestation_cdi()); |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 239 | // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed |
| 240 | // the length of either buffer, and `cdi` cannot overlap `data` because we just allocated it. |
| 241 | unsafe { ptr::copy_nonoverlapping(cdi.as_ptr(), data, std::cmp::min(cdi.len(), size)) }; |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 242 | cdi.len() |
| 243 | } |
| 244 | |
| 245 | fn try_get_dice_attestation_cdi() -> Result<Vec<u8>> { |
| 246 | get_vm_payload_service()?.getDiceAttestationCdi().context("Cannot get attestation CDI") |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 247 | } |
| 248 | |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 249 | /// Gets the path to the APK contents. |
| 250 | #[no_mangle] |
| 251 | pub extern "C" fn AVmPayload_getApkContentsPath() -> *const c_char { |
| 252 | (*VM_APK_CONTENTS_PATH_C).as_ptr() |
| 253 | } |
| 254 | |
Alan Stokes | 78d2470 | 2022-11-21 15:28:31 +0000 | [diff] [blame] | 255 | /// Gets the path to the VM's encrypted storage. |
| 256 | #[no_mangle] |
| 257 | pub extern "C" fn AVmPayload_getEncryptedStoragePath() -> *const c_char { |
| 258 | // TODO(b/254454578): Return a real path if storage is present |
| 259 | ptr::null() |
| 260 | } |