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 | |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 17 | use android_system_virtualization_payload::aidl::android::system::virtualization::payload:: IVmPayloadService::{ |
| 18 | IVmPayloadService, ENCRYPTEDSTORE_MOUNTPOINT, VM_APK_CONTENTS_PATH, |
| 19 | VM_PAYLOAD_SERVICE_SOCKET_NAME, AttestationResult::AttestationResult, |
| 20 | }; |
| 21 | use anyhow::{bail, ensure, Context, Result}; |
| 22 | use binder::{ |
| 23 | unstable_api::{new_spibinder, AIBinder}, |
| 24 | Strong, |
| 25 | }; |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 26 | use lazy_static::lazy_static; |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 27 | use log::{error, info, Level}; |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 28 | use rpcbinder::{RpcServer, RpcSession}; |
| 29 | use openssl::{ec::EcKey, sha::sha256, ecdsa::EcdsaSig}; |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 30 | use std::convert::Infallible; |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 31 | use std::ffi::{CString, CStr}; |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 32 | use std::fmt::Debug; |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 33 | use std::os::raw::{c_char, c_void}; |
Shikha Panwar | ddc124b | 2022-11-28 19:17:54 +0000 | [diff] [blame] | 34 | use std::path::Path; |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 35 | use std::ptr::{self, NonNull}; |
| 36 | use std::sync::{ |
| 37 | atomic::{AtomicBool, Ordering}, |
| 38 | Mutex, |
| 39 | }; |
| 40 | use vm_payload_status_bindgen::attestation_status_t; |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 41 | |
| 42 | lazy_static! { |
| 43 | static ref VM_APK_CONTENTS_PATH_C: CString = |
| 44 | CString::new(VM_APK_CONTENTS_PATH).expect("CString::new failed"); |
Alan Stokes | 0cbfdf9 | 2022-11-21 17:17:53 +0000 | [diff] [blame] | 45 | static ref PAYLOAD_CONNECTION: Mutex<Option<Strong<dyn IVmPayloadService>>> = Mutex::default(); |
Shikha Panwar | ddc124b | 2022-11-28 19:17:54 +0000 | [diff] [blame] | 46 | static ref VM_ENCRYPTED_STORAGE_PATH_C: CString = |
| 47 | CString::new(ENCRYPTEDSTORE_MOUNTPOINT).expect("CString::new failed"); |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 48 | } |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 49 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 50 | static ALREADY_NOTIFIED: AtomicBool = AtomicBool::new(false); |
| 51 | |
Alan Stokes | 0cbfdf9 | 2022-11-21 17:17:53 +0000 | [diff] [blame] | 52 | /// Return a connection to the payload service in Microdroid Manager. Uses the existing connection |
| 53 | /// if there is one, otherwise attempts to create a new one. |
| 54 | fn get_vm_payload_service() -> Result<Strong<dyn IVmPayloadService>> { |
| 55 | let mut connection = PAYLOAD_CONNECTION.lock().unwrap(); |
| 56 | if let Some(strong) = &*connection { |
| 57 | Ok(strong.clone()) |
| 58 | } else { |
David Brazdil | a2125dd | 2022-12-14 16:37:44 +0000 | [diff] [blame] | 59 | let new_connection: Strong<dyn IVmPayloadService> = RpcSession::new() |
| 60 | .setup_unix_domain_client(VM_PAYLOAD_SERVICE_SOCKET_NAME) |
| 61 | .context(format!("Failed to connect to service: {}", VM_PAYLOAD_SERVICE_SOCKET_NAME))?; |
Alan Stokes | 0cbfdf9 | 2022-11-21 17:17:53 +0000 | [diff] [blame] | 62 | *connection = Some(new_connection.clone()); |
| 63 | Ok(new_connection) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /// 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] | 68 | fn initialize_logging() { |
| 69 | android_logger::init_once( |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 70 | 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] | 71 | ); |
| 72 | } |
| 73 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 74 | /// In many cases clients can't do anything useful if API calls fail, and the failure |
| 75 | /// generally indicates that the VM is exiting or otherwise doomed. So rather than |
| 76 | /// returning a non-actionable error indication we just log the problem and abort |
| 77 | /// the process. |
| 78 | fn unwrap_or_abort<T, E: Debug>(result: Result<T, E>) -> T { |
| 79 | result.unwrap_or_else(|e| { |
| 80 | let msg = format!("{:?}", e); |
| 81 | error!("{msg}"); |
| 82 | panic!("{msg}") |
| 83 | }) |
| 84 | } |
| 85 | |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 86 | /// Notifies the host that the payload is ready. |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 87 | /// Panics on failure. |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 88 | #[no_mangle] |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 89 | pub extern "C" fn AVmPayload_notifyPayloadReady() { |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 90 | initialize_logging(); |
| 91 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 92 | if !ALREADY_NOTIFIED.swap(true, Ordering::Relaxed) { |
| 93 | unwrap_or_abort(try_notify_payload_ready()); |
| 94 | |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 95 | info!("Notified host payload ready successfully"); |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 96 | } |
| 97 | } |
| 98 | |
| 99 | /// Notifies the host that the payload is ready. |
| 100 | /// Returns a `Result` containing error information if failed. |
| 101 | fn try_notify_payload_ready() -> Result<()> { |
Alice Wang | 59a9e56 | 2022-10-04 15:24:10 +0000 | [diff] [blame] | 102 | get_vm_payload_service()?.notifyPayloadReady().context("Cannot notify payload ready") |
Alice Wang | fb46ee1 | 2022-09-30 13:08:52 +0000 | [diff] [blame] | 103 | } |
| 104 | |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 105 | /// Runs a binder RPC server, serving the supplied binder service implementation on the given vsock |
| 106 | /// port. |
| 107 | /// |
| 108 | /// If and when the server is ready for connections (it is listening on the port), `on_ready` is |
| 109 | /// called to allow appropriate action to be taken - e.g. to notify clients that they may now |
| 110 | /// attempt to connect. |
| 111 | /// |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 112 | /// The current thread joins the binder thread pool to handle incoming messages. |
| 113 | /// This function never returns. |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 114 | /// |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 115 | /// Panics on error (including unexpected server exit). |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 116 | /// |
| 117 | /// # Safety |
| 118 | /// |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 119 | /// If present, the `on_ready` callback must be a valid function pointer, which will be called at |
| 120 | /// most once, while this function is executing, with the `param` parameter. |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 121 | #[no_mangle] |
| 122 | pub unsafe extern "C" fn AVmPayload_runVsockRpcServer( |
| 123 | service: *mut AIBinder, |
| 124 | port: u32, |
| 125 | on_ready: Option<unsafe extern "C" fn(param: *mut c_void)>, |
| 126 | param: *mut c_void, |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 127 | ) -> Infallible { |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 128 | initialize_logging(); |
| 129 | |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 130 | // SAFETY: try_run_vsock_server has the same requirements as this function |
| 131 | unwrap_or_abort(unsafe { try_run_vsock_server(service, port, on_ready, param) }) |
| 132 | } |
| 133 | |
| 134 | /// # Safety: Same as `AVmPayload_runVsockRpcServer`. |
| 135 | unsafe fn try_run_vsock_server( |
| 136 | service: *mut AIBinder, |
| 137 | port: u32, |
| 138 | on_ready: Option<unsafe extern "C" fn(param: *mut c_void)>, |
| 139 | param: *mut c_void, |
| 140 | ) -> Result<Infallible> { |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 141 | // SAFETY: AIBinder returned has correct reference count, and the ownership can |
| 142 | // safely be taken by new_spibinder. |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 143 | let service = unsafe { new_spibinder(service) }; |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 144 | if let Some(service) = service { |
David Brazdil | 3238da4 | 2022-11-18 10:04:51 +0000 | [diff] [blame] | 145 | match RpcServer::new_vsock(service, libc::VMADDR_CID_HOST, port) { |
David Brazdil | 671e614 | 2022-11-16 11:47:27 +0000 | [diff] [blame] | 146 | Ok(server) => { |
| 147 | if let Some(on_ready) = on_ready { |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 148 | // SAFETY: We're calling the callback with the parameter specified within the |
| 149 | // allowed lifetime. |
| 150 | unsafe { on_ready(param) }; |
David Brazdil | 671e614 | 2022-11-16 11:47:27 +0000 | [diff] [blame] | 151 | } |
| 152 | server.join(); |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 153 | bail!("RpcServer unexpectedly terminated"); |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 154 | } |
David Brazdil | 671e614 | 2022-11-16 11:47:27 +0000 | [diff] [blame] | 155 | Err(err) => { |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 156 | bail!("Failed to start RpcServer: {:?}", err); |
David Brazdil | 671e614 | 2022-11-16 11:47:27 +0000 | [diff] [blame] | 157 | } |
| 158 | } |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 159 | } else { |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 160 | bail!("Failed to convert the given service from AIBinder to SpIBinder."); |
Alice Wang | 2be64f3 | 2022-10-13 14:37:35 +0000 | [diff] [blame] | 161 | } |
| 162 | } |
| 163 | |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 164 | /// Get a secret that is uniquely bound to this VM instance. |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 165 | /// Panics on failure. |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 166 | /// |
| 167 | /// # Safety |
| 168 | /// |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 169 | /// Behavior is undefined if any of the following conditions are violated: |
| 170 | /// |
| 171 | /// * `identifier` must be [valid] for reads of `identifier_size` bytes. |
| 172 | /// * `secret` must be [valid] for writes of `size` bytes. |
| 173 | /// |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 174 | /// [valid]: ptr#safety |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 175 | #[no_mangle] |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 176 | pub unsafe extern "C" fn AVmPayload_getVmInstanceSecret( |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 177 | identifier: *const u8, |
| 178 | identifier_size: usize, |
| 179 | secret: *mut u8, |
| 180 | size: usize, |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 181 | ) { |
Alan Stokes | f30982b | 2022-11-18 11:50:32 +0000 | [diff] [blame] | 182 | initialize_logging(); |
| 183 | |
Alan Stokes | e0945ad | 2022-11-24 13:29:57 +0000 | [diff] [blame] | 184 | // SAFETY: See the requirements on `identifier` above. |
| 185 | let identifier = unsafe { std::slice::from_raw_parts(identifier, identifier_size) }; |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 186 | 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] | 187 | |
| 188 | // SAFETY: See the requirements on `secret` above; `vm_secret` is known to have length `size`, |
| 189 | // and cannot overlap `secret` because we just allocated it. |
| 190 | unsafe { |
| 191 | ptr::copy_nonoverlapping(vm_secret.as_ptr(), secret, size); |
| 192 | } |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 193 | } |
| 194 | |
| 195 | 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] | 196 | let vm_secret = get_vm_payload_service()? |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 197 | .getVmInstanceSecret(identifier, i32::try_from(size)?) |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 198 | .context("Cannot get VM instance secret")?; |
| 199 | ensure!( |
| 200 | vm_secret.len() == size, |
| 201 | "Returned secret has {} bytes, expected {}", |
| 202 | vm_secret.len(), |
| 203 | size |
| 204 | ); |
| 205 | Ok(vm_secret) |
Andrew Scull | 102067a | 2022-10-07 00:34:40 +0000 | [diff] [blame] | 206 | } |
| 207 | |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 208 | /// Get the VM's attestation chain. |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 209 | /// Panics on failure. |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 210 | /// |
| 211 | /// # Safety |
| 212 | /// |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 213 | /// Behavior is undefined if any of the following conditions are violated: |
| 214 | /// |
Alan Stokes | 88805d5 | 2022-12-16 16:07:33 +0000 | [diff] [blame] | 215 | /// * `data` must be [valid] for writes of `size` bytes, if size > 0. |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 216 | /// |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 217 | /// [valid]: ptr#safety |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 218 | #[no_mangle] |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 219 | 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] | 220 | initialize_logging(); |
| 221 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 222 | let chain = unwrap_or_abort(try_get_dice_attestation_chain()); |
Alan Stokes | 88805d5 | 2022-12-16 16:07:33 +0000 | [diff] [blame] | 223 | if size != 0 { |
| 224 | // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed |
| 225 | // the length of either buffer, and `chain` cannot overlap `data` because we just allocated |
| 226 | // it. We allow data to be null, which is never valid, but only if size == 0 which is |
| 227 | // checked above. |
| 228 | unsafe { ptr::copy_nonoverlapping(chain.as_ptr(), data, std::cmp::min(chain.len(), size)) }; |
| 229 | } |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 230 | chain.len() |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 231 | } |
| 232 | |
| 233 | fn try_get_dice_attestation_chain() -> Result<Vec<u8>> { |
| 234 | get_vm_payload_service()?.getDiceAttestationChain().context("Cannot get attestation chain") |
| 235 | } |
| 236 | |
| 237 | /// Get the VM's attestation CDI. |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 238 | /// Panics on failure. |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 239 | /// |
| 240 | /// # Safety |
| 241 | /// |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 242 | /// Behavior is undefined if any of the following conditions are violated: |
| 243 | /// |
Alan Stokes | 88805d5 | 2022-12-16 16:07:33 +0000 | [diff] [blame] | 244 | /// * `data` must be [valid] for writes of `size` bytes, if size > 0. |
Andrew Scull | 655e98e | 2022-10-10 22:24:58 +0000 | [diff] [blame] | 245 | /// |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 246 | /// [valid]: ptr#safety |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 247 | #[no_mangle] |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 248 | 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] | 249 | initialize_logging(); |
| 250 | |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 251 | let cdi = unwrap_or_abort(try_get_dice_attestation_cdi()); |
Alan Stokes | 88805d5 | 2022-12-16 16:07:33 +0000 | [diff] [blame] | 252 | if size != 0 { |
| 253 | // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed |
| 254 | // the length of either buffer, and `cdi` cannot overlap `data` because we just allocated |
| 255 | // it. We allow data to be null, which is never valid, but only if size == 0 which is |
| 256 | // checked above. |
| 257 | unsafe { ptr::copy_nonoverlapping(cdi.as_ptr(), data, std::cmp::min(cdi.len(), size)) }; |
| 258 | } |
Alan Stokes | 65bbb91 | 2022-11-23 09:39:34 +0000 | [diff] [blame] | 259 | cdi.len() |
| 260 | } |
| 261 | |
| 262 | fn try_get_dice_attestation_cdi() -> Result<Vec<u8>> { |
| 263 | get_vm_payload_service()?.getDiceAttestationCdi().context("Cannot get attestation CDI") |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 264 | } |
| 265 | |
Alice Wang | a410b64 | 2023-10-18 09:05:15 +0000 | [diff] [blame] | 266 | /// Requests the remote attestation of the client VM. |
| 267 | /// |
| 268 | /// The challenge will be included in the certificate chain in the attestation result, |
| 269 | /// serving as proof of the freshness of the result. |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 270 | /// |
| 271 | /// # Safety |
| 272 | /// |
| 273 | /// Behavior is undefined if any of the following conditions are violated: |
| 274 | /// |
Alice Wang | a410b64 | 2023-10-18 09:05:15 +0000 | [diff] [blame] | 275 | /// * `challenge` must be [valid] for reads of `challenge_size` bytes. |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 276 | /// * `res` must be [valid] to write the attestation result. |
| 277 | /// * The region of memory beginning at `challenge` with `challenge_size` bytes must not |
| 278 | /// overlap with the region of memory `res` points to. |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 279 | /// |
| 280 | /// [valid]: ptr#safety |
| 281 | #[no_mangle] |
Alice Wang | a410b64 | 2023-10-18 09:05:15 +0000 | [diff] [blame] | 282 | pub unsafe extern "C" fn AVmPayload_requestAttestation( |
| 283 | challenge: *const u8, |
| 284 | challenge_size: usize, |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 285 | res: &mut *mut AttestationResult, |
| 286 | ) -> attestation_status_t { |
| 287 | initialize_logging(); |
| 288 | const MAX_CHALLENGE_SIZE: usize = 64; |
| 289 | if challenge_size > MAX_CHALLENGE_SIZE { |
| 290 | return attestation_status_t::ATTESTATION_ERROR_INVALID_CHALLENGE; |
| 291 | } |
| 292 | let challenge = if challenge_size == 0 { |
| 293 | &[] |
| 294 | } else { |
| 295 | // SAFETY: The caller guarantees that `challenge` is valid for reads of |
| 296 | // `challenge_size` bytes and `challenge_size` is not zero. |
| 297 | unsafe { std::slice::from_raw_parts(challenge, challenge_size) } |
| 298 | }; |
| 299 | let attestation_res = unwrap_or_abort(try_request_attestation(challenge)); |
| 300 | *res = Box::into_raw(Box::new(attestation_res)); |
| 301 | attestation_status_t::ATTESTATION_OK |
| 302 | } |
| 303 | |
| 304 | fn try_request_attestation(public_key: &[u8]) -> Result<AttestationResult> { |
| 305 | get_vm_payload_service()? |
| 306 | .requestAttestation(public_key) |
| 307 | .context("Failed to request attestation") |
| 308 | } |
| 309 | |
| 310 | /// Converts the return value from `AVmPayload_requestAttestation` to a text string |
| 311 | /// representing the error code. |
| 312 | #[no_mangle] |
| 313 | pub extern "C" fn AVmAttestationResult_resultToString( |
| 314 | status: attestation_status_t, |
| 315 | ) -> *const c_char { |
| 316 | let message = match status { |
| 317 | attestation_status_t::ATTESTATION_OK => { |
| 318 | CStr::from_bytes_with_nul(b"The remote attestation completes successfully.\0").unwrap() |
| 319 | } |
| 320 | attestation_status_t::ATTESTATION_ERROR_INVALID_CHALLENGE => { |
| 321 | CStr::from_bytes_with_nul(b"The challenge size is not between 0 and 64.\0").unwrap() |
| 322 | } |
| 323 | _ => CStr::from_bytes_with_nul( |
| 324 | b"The remote attestation has failed due to an unspecified cause.\0", |
| 325 | ) |
| 326 | .unwrap(), |
| 327 | }; |
| 328 | message.as_ptr() |
| 329 | } |
| 330 | |
| 331 | /// Reads the DER-encoded ECPrivateKey structure specified in [RFC 5915 s3] for the |
| 332 | /// EC P-256 private key from the provided attestation result. |
| 333 | /// |
| 334 | /// # Safety |
| 335 | /// |
| 336 | /// Behavior is undefined if any of the following conditions are violated: |
| 337 | /// |
| 338 | /// * `data` must be [valid] for writes of `size` bytes, if size > 0. |
| 339 | /// * The region of memory beginning at `data` with `size` bytes must not overlap with the |
| 340 | /// region of memory `res` points to. |
| 341 | /// |
| 342 | /// [valid]: ptr#safety |
| 343 | /// [RFC 5915 s3]: https://datatracker.ietf.org/doc/html/rfc5915#section-3 |
| 344 | #[no_mangle] |
| 345 | pub unsafe extern "C" fn AVmAttestationResult_getPrivateKey( |
| 346 | res: &AttestationResult, |
| 347 | data: *mut u8, |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 348 | size: usize, |
| 349 | ) -> usize { |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 350 | let private_key = &res.privateKey; |
| 351 | if size != 0 { |
| 352 | let data = NonNull::new(data).expect("data must not be null when size > 0"); |
| 353 | // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed |
| 354 | // the length of either buffer, and the caller ensures that `private_key` cannot overlap |
| 355 | // `data`. We allow data to be null, which is never valid, but only if size == 0 |
| 356 | // which is checked above. |
| 357 | unsafe { |
| 358 | ptr::copy_nonoverlapping( |
| 359 | private_key.as_ptr(), |
| 360 | data.as_ptr(), |
| 361 | std::cmp::min(private_key.len(), size), |
| 362 | ) |
| 363 | }; |
| 364 | } |
| 365 | private_key.len() |
| 366 | } |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 367 | |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 368 | /// Signs the given message using ECDSA P-256, the message is first hashed with SHA-256 and |
| 369 | /// then it is signed with the attested EC P-256 private key in the attestation result. |
| 370 | /// |
| 371 | /// # Safety |
| 372 | /// |
| 373 | /// Behavior is undefined if any of the following conditions are violated: |
| 374 | /// |
| 375 | /// * `message` must be [valid] for reads of `message_size` bytes. |
| 376 | /// * `data` must be [valid] for writes of `size` bytes, if size > 0. |
| 377 | /// * The region of memory beginning at `data` with `size` bytes must not overlap with the |
| 378 | /// region of memory `res` or `message` point to. |
| 379 | /// |
| 380 | /// |
| 381 | /// [valid]: ptr#safety |
| 382 | #[no_mangle] |
| 383 | pub unsafe extern "C" fn AVmAttestationResult_sign( |
| 384 | res: &AttestationResult, |
| 385 | message: *const u8, |
| 386 | message_size: usize, |
| 387 | data: *mut u8, |
| 388 | size: usize, |
| 389 | ) -> usize { |
| 390 | if message_size == 0 { |
| 391 | panic!("Message to be signed must not be empty.") |
| 392 | } |
| 393 | // SAFETY: See the requirements on `message` above. |
| 394 | let message = unsafe { std::slice::from_raw_parts(message, message_size) }; |
| 395 | let signature = unwrap_or_abort(try_ecdsa_sign(message, &res.privateKey)); |
| 396 | if size != 0 { |
| 397 | let data = NonNull::new(data).expect("data must not be null when size > 0"); |
| 398 | // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed |
| 399 | // the length of either buffer, and the caller ensures that `signature` cannot overlap |
| 400 | // `data`. We allow data to be null, which is never valid, but only if size == 0 |
| 401 | // which is checked above. |
| 402 | unsafe { |
| 403 | ptr::copy_nonoverlapping( |
| 404 | signature.as_ptr(), |
| 405 | data.as_ptr(), |
| 406 | std::cmp::min(signature.len(), size), |
| 407 | ) |
| 408 | }; |
| 409 | } |
| 410 | signature.len() |
| 411 | } |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 412 | |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 413 | fn try_ecdsa_sign(message: &[u8], der_encoded_ec_private_key: &[u8]) -> Result<Vec<u8>> { |
| 414 | let private_key = EcKey::private_key_from_der(der_encoded_ec_private_key)?; |
| 415 | let digest = sha256(message); |
| 416 | let sig = EcdsaSig::sign(&digest, &private_key)?; |
| 417 | Ok(sig.to_der()?) |
| 418 | } |
| 419 | |
| 420 | /// Gets the number of certificates in the certificate chain. |
| 421 | #[no_mangle] |
| 422 | pub extern "C" fn AVmAttestationResult_getCertificateCount(res: &AttestationResult) -> usize { |
| 423 | res.certificateChain.len() |
| 424 | } |
| 425 | |
| 426 | /// Retrieves the certificate at the given `index` from the certificate chain in the provided |
| 427 | /// attestation result. |
| 428 | /// |
| 429 | /// # Safety |
| 430 | /// |
| 431 | /// Behavior is undefined if any of the following conditions are violated: |
| 432 | /// |
| 433 | /// * `data` must be [valid] for writes of `size` bytes, if size > 0. |
| 434 | /// * `index` must be within the range of [0, number of certificates). The number of certificates |
| 435 | /// can be obtained with `AVmAttestationResult_getCertificateCount`. |
| 436 | /// * The region of memory beginning at `data` with `size` bytes must not overlap with the |
| 437 | /// region of memory `res` points to. |
| 438 | /// |
| 439 | /// [valid]: ptr#safety |
| 440 | #[no_mangle] |
| 441 | pub unsafe extern "C" fn AVmAttestationResult_getCertificateAt( |
| 442 | res: &AttestationResult, |
| 443 | index: usize, |
| 444 | data: *mut u8, |
| 445 | size: usize, |
| 446 | ) -> usize { |
| 447 | let certificate = |
| 448 | &res.certificateChain.get(index).expect("The index is out of bounds.").encodedCertificate; |
| 449 | if size != 0 { |
| 450 | let data = NonNull::new(data).expect("data must not be null when size > 0"); |
| 451 | // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed |
| 452 | // the length of either buffer, and the caller ensures that `certificate` cannot overlap |
| 453 | // `data`. We allow data to be null, which is never valid, but only if size == 0 |
| 454 | // which is checked above. |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 455 | unsafe { |
| 456 | ptr::copy_nonoverlapping( |
| 457 | certificate.as_ptr(), |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 458 | data.as_ptr(), |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 459 | std::cmp::min(certificate.len(), size), |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 460 | ) |
| 461 | }; |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 462 | } |
| 463 | certificate.len() |
| 464 | } |
| 465 | |
Alice Wang | 4e3015d | 2023-10-10 09:35:37 +0000 | [diff] [blame] | 466 | /// Frees all the data owned by given attestation result and result itself. |
| 467 | /// |
| 468 | /// # Safety |
| 469 | /// |
| 470 | /// Behavior is undefined if any of the following conditions are violated: |
| 471 | /// |
| 472 | /// * `res` must point to a valid `AttestationResult` and has not been freed before. |
| 473 | #[no_mangle] |
| 474 | pub unsafe extern "C" fn AVmAttestationResult_free(res: *mut AttestationResult) { |
| 475 | if !res.is_null() { |
| 476 | // SAFETY: The result is only freed once is ensured by the caller. |
| 477 | let res = unsafe { Box::from_raw(res) }; |
| 478 | drop(res) |
| 479 | } |
Alice Wang | c2fec93 | 2023-02-23 16:24:02 +0000 | [diff] [blame] | 480 | } |
| 481 | |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 482 | /// Gets the path to the APK contents. |
| 483 | #[no_mangle] |
| 484 | pub extern "C" fn AVmPayload_getApkContentsPath() -> *const c_char { |
Shikha Panwar | ddc124b | 2022-11-28 19:17:54 +0000 | [diff] [blame] | 485 | VM_APK_CONTENTS_PATH_C.as_ptr() |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 486 | } |
| 487 | |
Alan Stokes | 78d2470 | 2022-11-21 15:28:31 +0000 | [diff] [blame] | 488 | /// Gets the path to the VM's encrypted storage. |
| 489 | #[no_mangle] |
| 490 | pub extern "C" fn AVmPayload_getEncryptedStoragePath() -> *const c_char { |
Shikha Panwar | ddc124b | 2022-11-28 19:17:54 +0000 | [diff] [blame] | 491 | if Path::new(ENCRYPTEDSTORE_MOUNTPOINT).exists() { |
| 492 | VM_ENCRYPTED_STORAGE_PATH_C.as_ptr() |
| 493 | } else { |
| 494 | ptr::null() |
| 495 | } |
Alan Stokes | 78d2470 | 2022-11-21 15:28:31 +0000 | [diff] [blame] | 496 | } |