blob: 79780593c07e017851dc0a09424b2d93ed557210 [file] [log] [blame]
Alice Wangfb46ee12022-09-30 13:08:52 +00001// 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 Wang59a9e562022-10-04 15:24:10 +000015//! This module handles the interaction with virtual machine payload service.
Alice Wangfb46ee12022-09-30 13:08:52 +000016
Alice Wang4e3015d2023-10-10 09:35:37 +000017use 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};
21use anyhow::{bail, ensure, Context, Result};
22use binder::{
23 unstable_api::{new_spibinder, AIBinder},
Alice Wang677a5b82023-11-09 08:21:59 +000024 Strong, ExceptionCode,
Alice Wang4e3015d2023-10-10 09:35:37 +000025};
Alice Wang6bbb6da2022-10-26 12:44:06 +000026use lazy_static::lazy_static;
Jeff Vander Stoep57da1572024-01-31 10:52:16 +010027use log::{error, info, LevelFilter};
Alice Wang4e3015d2023-10-10 09:35:37 +000028use rpcbinder::{RpcServer, RpcSession};
29use openssl::{ec::EcKey, sha::sha256, ecdsa::EcdsaSig};
Alan Stokese0945ad2022-11-24 13:29:57 +000030use std::convert::Infallible;
Alice Wang4e3015d2023-10-10 09:35:37 +000031use std::ffi::{CString, CStr};
Alan Stokes65bbb912022-11-23 09:39:34 +000032use std::fmt::Debug;
Alice Wang6bbb6da2022-10-26 12:44:06 +000033use std::os::raw::{c_char, c_void};
Shikha Panwarddc124b2022-11-28 19:17:54 +000034use std::path::Path;
Alice Wang4e3015d2023-10-10 09:35:37 +000035use std::ptr::{self, NonNull};
36use std::sync::{
37 atomic::{AtomicBool, Ordering},
38 Mutex,
39};
40use vm_payload_status_bindgen::attestation_status_t;
Alice Wang6bbb6da2022-10-26 12:44:06 +000041
42lazy_static! {
43 static ref VM_APK_CONTENTS_PATH_C: CString =
44 CString::new(VM_APK_CONTENTS_PATH).expect("CString::new failed");
Alan Stokes0cbfdf92022-11-21 17:17:53 +000045 static ref PAYLOAD_CONNECTION: Mutex<Option<Strong<dyn IVmPayloadService>>> = Mutex::default();
Shikha Panwarddc124b2022-11-28 19:17:54 +000046 static ref VM_ENCRYPTED_STORAGE_PATH_C: CString =
47 CString::new(ENCRYPTEDSTORE_MOUNTPOINT).expect("CString::new failed");
Alice Wang6bbb6da2022-10-26 12:44:06 +000048}
Alice Wangfb46ee12022-09-30 13:08:52 +000049
Alan Stokes65bbb912022-11-23 09:39:34 +000050static ALREADY_NOTIFIED: AtomicBool = AtomicBool::new(false);
51
Alan Stokes0cbfdf92022-11-21 17:17:53 +000052/// 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.
54fn 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 Brazdila2125dd2022-12-14 16:37:44 +000059 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 Stokes0cbfdf92022-11-21 17:17:53 +000062 *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 Stokesf30982b2022-11-18 11:50:32 +000068fn initialize_logging() {
69 android_logger::init_once(
Jeff Vander Stoep57da1572024-01-31 10:52:16 +010070 android_logger::Config::default().with_tag("vm_payload").with_max_level(LevelFilter::Info),
Alan Stokesf30982b2022-11-18 11:50:32 +000071 );
72}
73
Alan Stokes65bbb912022-11-23 09:39:34 +000074/// 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.
78fn 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 Wangfb46ee12022-09-30 13:08:52 +000086/// Notifies the host that the payload is ready.
Alan Stokes65bbb912022-11-23 09:39:34 +000087/// Panics on failure.
Alice Wangfb46ee12022-09-30 13:08:52 +000088#[no_mangle]
Alan Stokes65bbb912022-11-23 09:39:34 +000089pub extern "C" fn AVmPayload_notifyPayloadReady() {
Alan Stokesf30982b2022-11-18 11:50:32 +000090 initialize_logging();
91
Alan Stokes65bbb912022-11-23 09:39:34 +000092 if !ALREADY_NOTIFIED.swap(true, Ordering::Relaxed) {
93 unwrap_or_abort(try_notify_payload_ready());
94
Alice Wangfb46ee12022-09-30 13:08:52 +000095 info!("Notified host payload ready successfully");
Alice Wangfb46ee12022-09-30 13:08:52 +000096 }
97}
98
99/// Notifies the host that the payload is ready.
100/// Returns a `Result` containing error information if failed.
101fn try_notify_payload_ready() -> Result<()> {
Alice Wang59a9e562022-10-04 15:24:10 +0000102 get_vm_payload_service()?.notifyPayloadReady().context("Cannot notify payload ready")
Alice Wangfb46ee12022-09-30 13:08:52 +0000103}
104
Alice Wang2be64f32022-10-13 14:37:35 +0000105/// 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 Stokese0945ad2022-11-24 13:29:57 +0000112/// The current thread joins the binder thread pool to handle incoming messages.
113/// This function never returns.
Alice Wang2be64f32022-10-13 14:37:35 +0000114///
Alan Stokese0945ad2022-11-24 13:29:57 +0000115/// Panics on error (including unexpected server exit).
Alice Wang2be64f32022-10-13 14:37:35 +0000116///
117/// # Safety
118///
Alan Stokese0945ad2022-11-24 13:29:57 +0000119/// 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 Wang2be64f32022-10-13 14:37:35 +0000121#[no_mangle]
122pub 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 Stokese0945ad2022-11-24 13:29:57 +0000127) -> Infallible {
Alan Stokesf30982b2022-11-18 11:50:32 +0000128 initialize_logging();
129
Alan Stokese0945ad2022-11-24 13:29:57 +0000130 // 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`.
135unsafe 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 Wang2be64f32022-10-13 14:37:35 +0000141 // SAFETY: AIBinder returned has correct reference count, and the ownership can
142 // safely be taken by new_spibinder.
Alan Stokese0945ad2022-11-24 13:29:57 +0000143 let service = unsafe { new_spibinder(service) };
Alice Wang2be64f32022-10-13 14:37:35 +0000144 if let Some(service) = service {
David Brazdil3238da42022-11-18 10:04:51 +0000145 match RpcServer::new_vsock(service, libc::VMADDR_CID_HOST, port) {
David Brazdil671e6142022-11-16 11:47:27 +0000146 Ok(server) => {
147 if let Some(on_ready) = on_ready {
Alan Stokese0945ad2022-11-24 13:29:57 +0000148 // SAFETY: We're calling the callback with the parameter specified within the
149 // allowed lifetime.
150 unsafe { on_ready(param) };
David Brazdil671e6142022-11-16 11:47:27 +0000151 }
152 server.join();
Alan Stokese0945ad2022-11-24 13:29:57 +0000153 bail!("RpcServer unexpectedly terminated");
Alice Wang2be64f32022-10-13 14:37:35 +0000154 }
David Brazdil671e6142022-11-16 11:47:27 +0000155 Err(err) => {
Alan Stokese0945ad2022-11-24 13:29:57 +0000156 bail!("Failed to start RpcServer: {:?}", err);
David Brazdil671e6142022-11-16 11:47:27 +0000157 }
158 }
Alice Wang2be64f32022-10-13 14:37:35 +0000159 } else {
Alan Stokese0945ad2022-11-24 13:29:57 +0000160 bail!("Failed to convert the given service from AIBinder to SpIBinder.");
Alice Wang2be64f32022-10-13 14:37:35 +0000161 }
162}
163
Andrew Scull102067a2022-10-07 00:34:40 +0000164/// Get a secret that is uniquely bound to this VM instance.
Alan Stokes65bbb912022-11-23 09:39:34 +0000165/// Panics on failure.
Andrew Scull102067a2022-10-07 00:34:40 +0000166///
167/// # Safety
168///
Andrew Scull655e98e2022-10-10 22:24:58 +0000169/// 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 Stokes65bbb912022-11-23 09:39:34 +0000174/// [valid]: ptr#safety
Andrew Scull102067a2022-10-07 00:34:40 +0000175#[no_mangle]
Andrew Scull655e98e2022-10-10 22:24:58 +0000176pub unsafe extern "C" fn AVmPayload_getVmInstanceSecret(
Andrew Scull102067a2022-10-07 00:34:40 +0000177 identifier: *const u8,
178 identifier_size: usize,
179 secret: *mut u8,
180 size: usize,
Alan Stokes65bbb912022-11-23 09:39:34 +0000181) {
Alan Stokesf30982b2022-11-18 11:50:32 +0000182 initialize_logging();
183
Alan Stokese0945ad2022-11-24 13:29:57 +0000184 // SAFETY: See the requirements on `identifier` above.
185 let identifier = unsafe { std::slice::from_raw_parts(identifier, identifier_size) };
Alan Stokes65bbb912022-11-23 09:39:34 +0000186 let vm_secret = unwrap_or_abort(try_get_vm_instance_secret(identifier, size));
Alan Stokese0945ad2022-11-24 13:29:57 +0000187
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 Scull102067a2022-10-07 00:34:40 +0000193}
194
195fn try_get_vm_instance_secret(identifier: &[u8], size: usize) -> Result<Vec<u8>> {
Alan Stokes65bbb912022-11-23 09:39:34 +0000196 let vm_secret = get_vm_payload_service()?
Andrew Scull102067a2022-10-07 00:34:40 +0000197 .getVmInstanceSecret(identifier, i32::try_from(size)?)
Alan Stokes65bbb912022-11-23 09:39:34 +0000198 .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 Scull102067a2022-10-07 00:34:40 +0000206}
207
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000208/// Get the VM's attestation chain.
Alan Stokes65bbb912022-11-23 09:39:34 +0000209/// Panics on failure.
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000210///
211/// # Safety
212///
Andrew Scull655e98e2022-10-10 22:24:58 +0000213/// Behavior is undefined if any of the following conditions are violated:
214///
Alan Stokes88805d52022-12-16 16:07:33 +0000215/// * `data` must be [valid] for writes of `size` bytes, if size > 0.
Andrew Scull655e98e2022-10-10 22:24:58 +0000216///
Alan Stokes65bbb912022-11-23 09:39:34 +0000217/// [valid]: ptr#safety
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000218#[no_mangle]
Alan Stokes65bbb912022-11-23 09:39:34 +0000219pub unsafe extern "C" fn AVmPayload_getDiceAttestationChain(data: *mut u8, size: usize) -> usize {
Alan Stokesf30982b2022-11-18 11:50:32 +0000220 initialize_logging();
221
Alan Stokes65bbb912022-11-23 09:39:34 +0000222 let chain = unwrap_or_abort(try_get_dice_attestation_chain());
Alan Stokes88805d52022-12-16 16:07:33 +0000223 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 Stokes65bbb912022-11-23 09:39:34 +0000230 chain.len()
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000231}
232
233fn 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 Stokes65bbb912022-11-23 09:39:34 +0000238/// Panics on failure.
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000239///
240/// # Safety
241///
Andrew Scull655e98e2022-10-10 22:24:58 +0000242/// Behavior is undefined if any of the following conditions are violated:
243///
Alan Stokes88805d52022-12-16 16:07:33 +0000244/// * `data` must be [valid] for writes of `size` bytes, if size > 0.
Andrew Scull655e98e2022-10-10 22:24:58 +0000245///
Alan Stokes65bbb912022-11-23 09:39:34 +0000246/// [valid]: ptr#safety
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000247#[no_mangle]
Alan Stokes65bbb912022-11-23 09:39:34 +0000248pub unsafe extern "C" fn AVmPayload_getDiceAttestationCdi(data: *mut u8, size: usize) -> usize {
Alan Stokesf30982b2022-11-18 11:50:32 +0000249 initialize_logging();
250
Alan Stokes65bbb912022-11-23 09:39:34 +0000251 let cdi = unwrap_or_abort(try_get_dice_attestation_cdi());
Alan Stokes88805d52022-12-16 16:07:33 +0000252 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 Stokes65bbb912022-11-23 09:39:34 +0000259 cdi.len()
260}
261
262fn try_get_dice_attestation_cdi() -> Result<Vec<u8>> {
263 get_vm_payload_service()?.getDiceAttestationCdi().context("Cannot get attestation CDI")
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000264}
265
Alice Wanga410b642023-10-18 09:05:15 +0000266/// 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 Wangc2fec932023-02-23 16:24:02 +0000270///
271/// # Safety
272///
273/// Behavior is undefined if any of the following conditions are violated:
274///
Alice Wanga410b642023-10-18 09:05:15 +0000275/// * `challenge` must be [valid] for reads of `challenge_size` bytes.
Alice Wang4e3015d2023-10-10 09:35:37 +0000276/// * `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 Wangc2fec932023-02-23 16:24:02 +0000279///
280/// [valid]: ptr#safety
281#[no_mangle]
Alice Wanga410b642023-10-18 09:05:15 +0000282pub unsafe extern "C" fn AVmPayload_requestAttestation(
283 challenge: *const u8,
284 challenge_size: usize,
Alice Wang4e3015d2023-10-10 09:35:37 +0000285 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 };
Alice Wang677a5b82023-11-09 08:21:59 +0000299 let service = unwrap_or_abort(get_vm_payload_service());
300 match service.requestAttestation(challenge) {
301 Ok(attestation_res) => {
302 *res = Box::into_raw(Box::new(attestation_res));
303 attestation_status_t::ATTESTATION_OK
304 }
305 Err(e) => {
306 error!("Remote attestation failed: {e:?}");
307 binder_status_to_attestation_status(e)
308 }
309 }
Alice Wang4e3015d2023-10-10 09:35:37 +0000310}
311
Alice Wang677a5b82023-11-09 08:21:59 +0000312fn binder_status_to_attestation_status(status: binder::Status) -> attestation_status_t {
313 match status.exception_code() {
314 ExceptionCode::UNSUPPORTED_OPERATION => attestation_status_t::ATTESTATION_ERROR_UNSUPPORTED,
315 _ => attestation_status_t::ATTESTATION_ERROR_ATTESTATION_FAILED,
316 }
Alice Wang4e3015d2023-10-10 09:35:37 +0000317}
318
319/// Converts the return value from `AVmPayload_requestAttestation` to a text string
320/// representing the error code.
321#[no_mangle]
322pub extern "C" fn AVmAttestationResult_resultToString(
323 status: attestation_status_t,
324) -> *const c_char {
325 let message = match status {
326 attestation_status_t::ATTESTATION_OK => {
327 CStr::from_bytes_with_nul(b"The remote attestation completes successfully.\0").unwrap()
328 }
329 attestation_status_t::ATTESTATION_ERROR_INVALID_CHALLENGE => {
330 CStr::from_bytes_with_nul(b"The challenge size is not between 0 and 64.\0").unwrap()
331 }
Alice Wang677a5b82023-11-09 08:21:59 +0000332 attestation_status_t::ATTESTATION_ERROR_ATTESTATION_FAILED => {
333 CStr::from_bytes_with_nul(b"Failed to attest the VM. Please retry at a later time.\0")
334 .unwrap()
335 }
336 attestation_status_t::ATTESTATION_ERROR_UNSUPPORTED => CStr::from_bytes_with_nul(
337 b"Remote attestation is not supported in the current environment.\0",
Alice Wang4e3015d2023-10-10 09:35:37 +0000338 )
339 .unwrap(),
340 };
341 message.as_ptr()
342}
343
344/// Reads the DER-encoded ECPrivateKey structure specified in [RFC 5915 s3] for the
345/// EC P-256 private key from the provided attestation result.
346///
347/// # Safety
348///
349/// Behavior is undefined if any of the following conditions are violated:
350///
351/// * `data` must be [valid] for writes of `size` bytes, if size > 0.
352/// * The region of memory beginning at `data` with `size` bytes must not overlap with the
353/// region of memory `res` points to.
354///
355/// [valid]: ptr#safety
356/// [RFC 5915 s3]: https://datatracker.ietf.org/doc/html/rfc5915#section-3
357#[no_mangle]
358pub unsafe extern "C" fn AVmAttestationResult_getPrivateKey(
359 res: &AttestationResult,
360 data: *mut u8,
Alice Wangc2fec932023-02-23 16:24:02 +0000361 size: usize,
362) -> usize {
Alice Wang4e3015d2023-10-10 09:35:37 +0000363 let private_key = &res.privateKey;
364 if size != 0 {
365 let data = NonNull::new(data).expect("data must not be null when size > 0");
366 // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
367 // the length of either buffer, and the caller ensures that `private_key` cannot overlap
368 // `data`. We allow data to be null, which is never valid, but only if size == 0
369 // which is checked above.
370 unsafe {
371 ptr::copy_nonoverlapping(
372 private_key.as_ptr(),
373 data.as_ptr(),
374 std::cmp::min(private_key.len(), size),
375 )
376 };
377 }
378 private_key.len()
379}
Alice Wangc2fec932023-02-23 16:24:02 +0000380
Alice Wang4e3015d2023-10-10 09:35:37 +0000381/// Signs the given message using ECDSA P-256, the message is first hashed with SHA-256 and
382/// then it is signed with the attested EC P-256 private key in the attestation result.
383///
384/// # Safety
385///
386/// Behavior is undefined if any of the following conditions are violated:
387///
388/// * `message` must be [valid] for reads of `message_size` bytes.
389/// * `data` must be [valid] for writes of `size` bytes, if size > 0.
390/// * The region of memory beginning at `data` with `size` bytes must not overlap with the
391/// region of memory `res` or `message` point to.
392///
393///
394/// [valid]: ptr#safety
395#[no_mangle]
396pub unsafe extern "C" fn AVmAttestationResult_sign(
397 res: &AttestationResult,
398 message: *const u8,
399 message_size: usize,
400 data: *mut u8,
401 size: usize,
402) -> usize {
403 if message_size == 0 {
404 panic!("Message to be signed must not be empty.")
405 }
406 // SAFETY: See the requirements on `message` above.
407 let message = unsafe { std::slice::from_raw_parts(message, message_size) };
408 let signature = unwrap_or_abort(try_ecdsa_sign(message, &res.privateKey));
409 if size != 0 {
410 let data = NonNull::new(data).expect("data must not be null when size > 0");
411 // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
412 // the length of either buffer, and the caller ensures that `signature` cannot overlap
413 // `data`. We allow data to be null, which is never valid, but only if size == 0
414 // which is checked above.
415 unsafe {
416 ptr::copy_nonoverlapping(
417 signature.as_ptr(),
418 data.as_ptr(),
419 std::cmp::min(signature.len(), size),
420 )
421 };
422 }
423 signature.len()
424}
Alice Wangc2fec932023-02-23 16:24:02 +0000425
Alice Wang4e3015d2023-10-10 09:35:37 +0000426fn try_ecdsa_sign(message: &[u8], der_encoded_ec_private_key: &[u8]) -> Result<Vec<u8>> {
427 let private_key = EcKey::private_key_from_der(der_encoded_ec_private_key)?;
428 let digest = sha256(message);
429 let sig = EcdsaSig::sign(&digest, &private_key)?;
430 Ok(sig.to_der()?)
431}
432
433/// Gets the number of certificates in the certificate chain.
434#[no_mangle]
435pub extern "C" fn AVmAttestationResult_getCertificateCount(res: &AttestationResult) -> usize {
436 res.certificateChain.len()
437}
438
439/// Retrieves the certificate at the given `index` from the certificate chain in the provided
440/// attestation result.
441///
442/// # Safety
443///
444/// Behavior is undefined if any of the following conditions are violated:
445///
446/// * `data` must be [valid] for writes of `size` bytes, if size > 0.
447/// * `index` must be within the range of [0, number of certificates). The number of certificates
448/// can be obtained with `AVmAttestationResult_getCertificateCount`.
449/// * The region of memory beginning at `data` with `size` bytes must not overlap with the
450/// region of memory `res` points to.
451///
452/// [valid]: ptr#safety
453#[no_mangle]
454pub unsafe extern "C" fn AVmAttestationResult_getCertificateAt(
455 res: &AttestationResult,
456 index: usize,
457 data: *mut u8,
458 size: usize,
459) -> usize {
460 let certificate =
461 &res.certificateChain.get(index).expect("The index is out of bounds.").encodedCertificate;
462 if size != 0 {
463 let data = NonNull::new(data).expect("data must not be null when size > 0");
464 // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
465 // the length of either buffer, and the caller ensures that `certificate` cannot overlap
466 // `data`. We allow data to be null, which is never valid, but only if size == 0
467 // which is checked above.
Alice Wangc2fec932023-02-23 16:24:02 +0000468 unsafe {
469 ptr::copy_nonoverlapping(
470 certificate.as_ptr(),
Alice Wang4e3015d2023-10-10 09:35:37 +0000471 data.as_ptr(),
Alice Wangc2fec932023-02-23 16:24:02 +0000472 std::cmp::min(certificate.len(), size),
Alice Wang4e3015d2023-10-10 09:35:37 +0000473 )
474 };
Alice Wangc2fec932023-02-23 16:24:02 +0000475 }
476 certificate.len()
477}
478
Alice Wang4e3015d2023-10-10 09:35:37 +0000479/// Frees all the data owned by given attestation result and result itself.
480///
481/// # Safety
482///
483/// Behavior is undefined if any of the following conditions are violated:
484///
485/// * `res` must point to a valid `AttestationResult` and has not been freed before.
486#[no_mangle]
487pub unsafe extern "C" fn AVmAttestationResult_free(res: *mut AttestationResult) {
488 if !res.is_null() {
489 // SAFETY: The result is only freed once is ensured by the caller.
490 let res = unsafe { Box::from_raw(res) };
491 drop(res)
492 }
Alice Wangc2fec932023-02-23 16:24:02 +0000493}
494
Alice Wang6bbb6da2022-10-26 12:44:06 +0000495/// Gets the path to the APK contents.
496#[no_mangle]
497pub extern "C" fn AVmPayload_getApkContentsPath() -> *const c_char {
Shikha Panwarddc124b2022-11-28 19:17:54 +0000498 VM_APK_CONTENTS_PATH_C.as_ptr()
Alice Wang6bbb6da2022-10-26 12:44:06 +0000499}
500
Alan Stokes78d24702022-11-21 15:28:31 +0000501/// Gets the path to the VM's encrypted storage.
502#[no_mangle]
503pub extern "C" fn AVmPayload_getEncryptedStoragePath() -> *const c_char {
Shikha Panwarddc124b2022-11-28 19:17:54 +0000504 if Path::new(ENCRYPTEDSTORE_MOUNTPOINT).exists() {
505 VM_ENCRYPTED_STORAGE_PATH_C.as_ptr()
506 } else {
507 ptr::null()
508 }
Alan Stokes78d24702022-11-21 15:28:31 +0000509}