blob: 64f8d6a36fba3524d297d2564566096338fc21c3 [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},
24 Strong,
25};
Alice Wang6bbb6da2022-10-26 12:44:06 +000026use lazy_static::lazy_static;
Alice Wangfb46ee12022-09-30 13:08:52 +000027use log::{error, info, Level};
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(
Alan Stokes65bbb912022-11-23 09:39:34 +000070 android_logger::Config::default().with_tag("vm_payload").with_min_level(Level::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 };
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
304fn 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]
313pub 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]
345pub unsafe extern "C" fn AVmAttestationResult_getPrivateKey(
346 res: &AttestationResult,
347 data: *mut u8,
Alice Wangc2fec932023-02-23 16:24:02 +0000348 size: usize,
349) -> usize {
Alice Wang4e3015d2023-10-10 09:35:37 +0000350 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 Wangc2fec932023-02-23 16:24:02 +0000367
Alice Wang4e3015d2023-10-10 09:35:37 +0000368/// 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]
383pub 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 Wangc2fec932023-02-23 16:24:02 +0000412
Alice Wang4e3015d2023-10-10 09:35:37 +0000413fn 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]
422pub 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]
441pub 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 Wangc2fec932023-02-23 16:24:02 +0000455 unsafe {
456 ptr::copy_nonoverlapping(
457 certificate.as_ptr(),
Alice Wang4e3015d2023-10-10 09:35:37 +0000458 data.as_ptr(),
Alice Wangc2fec932023-02-23 16:24:02 +0000459 std::cmp::min(certificate.len(), size),
Alice Wang4e3015d2023-10-10 09:35:37 +0000460 )
461 };
Alice Wangc2fec932023-02-23 16:24:02 +0000462 }
463 certificate.len()
464}
465
Alice Wang4e3015d2023-10-10 09:35:37 +0000466/// 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]
474pub 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 Wangc2fec932023-02-23 16:24:02 +0000480}
481
Alice Wang6bbb6da2022-10-26 12:44:06 +0000482/// Gets the path to the APK contents.
483#[no_mangle]
484pub extern "C" fn AVmPayload_getApkContentsPath() -> *const c_char {
Shikha Panwarddc124b2022-11-28 19:17:54 +0000485 VM_APK_CONTENTS_PATH_C.as_ptr()
Alice Wang6bbb6da2022-10-26 12:44:06 +0000486}
487
Alan Stokes78d24702022-11-21 15:28:31 +0000488/// Gets the path to the VM's encrypted storage.
489#[no_mangle]
490pub extern "C" fn AVmPayload_getEncryptedStoragePath() -> *const c_char {
Shikha Panwarddc124b2022-11-28 19:17:54 +0000491 if Path::new(ENCRYPTEDSTORE_MOUNTPOINT).exists() {
492 VM_ENCRYPTED_STORAGE_PATH_C.as_ptr()
493 } else {
494 ptr::null()
495 }
Alan Stokes78d24702022-11-21 15:28:31 +0000496}