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