[client-vm] Build client VM CSR and sign the CSR with two keys

This cl builds the CSR that a client VM sends to the RKP VM for
remote attestation and adjusted the API accordingly as discussed
in the doc go/pvm-remote-attestation

The CSR payload is signed with both the CDI_Leaf_Priv of the
client VM's DICE chain and the attestation key. RKP VM should
verify the signature later with the CDI_Leaf_Pub extracted
from the same DICE chain in the CSR and the attestation public
key.

The new unit tests are added to config at cl/577763874.

Bug: 303807447
Test: run ServiceVmClientTestApp
Test: atest libservice_vm_comm.test
Test: atest microdroid_manager_test
Change-Id: Ic2c09e7339d9981edda028e2694fa551c911a274
diff --git a/vm_payload/Android.bp b/vm_payload/Android.bp
index b5322a8..7f2b9df 100644
--- a/vm_payload/Android.bp
+++ b/vm_payload/Android.bp
@@ -19,11 +19,26 @@
         "liblazy_static",
         "liblibc",
         "liblog_rust",
+        "libopenssl",
         "librpcbinder_rs",
+        "libvm_payload_status_bindgen",
         "libvsock",
     ],
 }
 
+rust_bindgen {
+    name: "libvm_payload_status_bindgen",
+    wrapper_src: "include/vm_payload.h",
+    crate_name: "vm_payload_status_bindgen",
+    defaults: ["avf_build_flags_rust"],
+    source_stem: "bindings",
+    bindgen_flags: [
+        "--default-enum-style rust",
+        "--allowlist-type=attestation_status_t",
+    ],
+    visibility: [":__subpackages__"],
+}
+
 // Rust wrappers round the C API for Rust clients.
 // (Yes, this involves going Rust -> C -> Rust.)
 rust_bindgen {
@@ -33,6 +48,9 @@
     defaults: ["avf_build_flags_rust"],
     source_stem: "bindings",
     apex_available: ["com.android.compos"],
+    bindgen_flags: [
+        "--default-enum-style rust",
+    ],
     visibility: [
         "//packages/modules/Virtualization/compos",
         "//packages/modules/Virtualization/service_vm/test_apk",
@@ -49,6 +67,7 @@
         "libbinder_ndk",
         "libbinder_rpc_unstable",
         "liblog",
+        "libcrypto",
     ],
     whole_static_libs: ["libvm_payload_impl"],
     export_static_lib_headers: ["libvm_payload_impl"],
diff --git a/vm_payload/include-restricted/vm_payload_restricted.h b/vm_payload/include-restricted/vm_payload_restricted.h
index ee92366..15c37ed 100644
--- a/vm_payload/include-restricted/vm_payload_restricted.h
+++ b/vm_payload/include-restricted/vm_payload_restricted.h
@@ -55,23 +55,4 @@
  */
 size_t AVmPayload_getDiceAttestationCdi(void* _Nullable data, size_t size);
 
-/**
- * Requests the remote attestation of the client VM.
- *
- * The challenge will be included in the certificate chain in the attestation result,
- * serving as proof of the freshness of the result.
- *
- * \param challenge A pointer to the challenge buffer.
- * \param challenge_size size of the challenge, the maximum supported challenge size is
- *                       64 bytes. An error will be returned if an invalid challenge is
- *                       passed.
- * \param buffer A pointer to the certificate buffer.
- * \param size number of bytes that can be written to the certificate buffer.
- *
- * \return the total size of the certificate
- */
-size_t AVmPayload_requestAttestation(const void* _Nonnull challenge, size_t challenge_size,
-                                     void* _Nullable buffer, size_t size)
-        __INTRODUCED_IN(__ANDROID_API_V__);
-
 __END_DECLS
diff --git a/vm_payload/include/vm_payload.h b/vm_payload/include/vm_payload.h
index c28cd42..2dfa2cb 100644
--- a/vm_payload/include/vm_payload.h
+++ b/vm_payload/include/vm_payload.h
@@ -30,6 +30,27 @@
 typedef struct AIBinder AIBinder;
 
 /**
+ * Introduced in API 35.
+ * Remote attestation result if the attestation succeeds.
+ */
+struct AVmAttestationResult;
+
+/**
+ * Introduced in API 35.
+ * Remote attestation status types returned from remote attestation functions.
+ */
+typedef enum attestation_status_t : int32_t {
+    /** The remote attestation completes successfully. */
+    ATTESTATION_OK = 0,
+
+    /** The remote attestation has failed due to an unspecified cause. */
+    ATTESTATION_UNKNOWN_ERROR = -10000,
+
+    /** The challenge size is not between 0 and 64. */
+    ATTESTATION_ERROR_INVALID_CHALLENGE = -10001,
+} attestation_status_t;
+
+/**
  * Notifies the host that the payload is ready.
  *
  * If the host app has set a `VirtualMachineCallback` for the VM, its
@@ -112,4 +133,129 @@
  */
 const char* _Nullable AVmPayload_getEncryptedStoragePath(void);
 
+/**
+ * Requests the remote attestation of the client VM.
+ *
+ * The challenge will be included in the certificate chain in the attestation result,
+ * serving as proof of the freshness of the result.
+ *
+ * \param challenge A pointer to the challenge buffer.
+ * \param challenge_size size of the challenge. The maximum supported challenge size is
+ *          64 bytes. The status ATTESTATION_ERROR_INVALID_CHALLENGE will be returned if
+ *          an invalid challenge is passed.
+ * \param result The remote attestation result will be filled here if the attestation
+ *               succeeds. The result remains valid until it is freed with
+ *              `AVmPayload_freeAttestationResult`.
+ *
+ * \return ATTESTATION_OK upon successful attestation.
+ */
+attestation_status_t AVmPayload_requestAttestation(
+        const void* _Nonnull challenge, size_t challenge_size,
+        struct AVmAttestationResult* _Nullable* _Nonnull result) __INTRODUCED_IN(__ANDROID_API_V__);
+
+/**
+ * Converts the return value from `AVmPayload_requestAttestation` to a text string
+ * representing the status code.
+ *
+ * \return a constant string value representing the status code. The string should not
+ * be deleted or freed by the application and remains valid for the lifetime of the VM.
+ */
+const char* _Nonnull AVmAttestationResult_resultToString(attestation_status_t status)
+        __INTRODUCED_IN(__ANDROID_API_V__);
+
+/**
+ * Frees all the data owned by the provided attestation result, including the result itself.
+ *
+ * Callers should ensure to invoke this API only once on a valid attestation result
+ * returned by `AVmPayload_requestAttestation` to avoid undefined behavior.
+ *
+ * \param result A pointer to the attestation result.
+ */
+void AVmAttestationResult_free(struct AVmAttestationResult* _Nullable result)
+        __INTRODUCED_IN(__ANDROID_API_V__);
+
+/**
+ * Reads the DER-encoded ECPrivateKey structure specified in [RFC 5915 s3] for the
+ * EC P-256 private key from the provided attestation result.
+ *
+ * \param result A pointer to the attestation result filled in
+ *              `AVmPayload_requestAttestation` when the attestation succeeds.
+ * \param data A pointer to the memory where the private key will be written
+ * (can be null if size is 0).
+ * \param size The maximum number of bytes that can be written to the data buffer.
+ * If `size` is smaller than the total size of the private key, the key data will be
+ * truncated to this `size`.
+ *
+ * \return The total size of the private key.
+ *
+ * [RFC 5915 s3]: https://datatracker.ietf.org/doc/html/rfc5915#section-3
+ */
+size_t AVmAttestationResult_getPrivateKey(const struct AVmAttestationResult* _Nonnull result,
+                                          void* _Nullable data, size_t size)
+        __INTRODUCED_IN(__ANDROID_API_V__);
+
+/**
+ * Signs the given message using ECDSA P-256, the message is first hashed with SHA-256 and
+ * then it is signed with the attested EC P-256 private key in the attestation result.
+ *
+ * \param result A pointer to the attestation result filled in
+ *              `AVmPayload_requestAttestation` when the attestation succeeds.
+ * \param message A pointer to the message buffer.
+ * \param message_size size of the message.
+ * \param data A pointer to the memory where the signature will be written
+ * (can be null if size is 0). The signature is a DER-encoded ECDSASignature structure
+ * detailed in the [RFC 6979].
+ * \param size The maximum number of bytes that can be written to the data buffer.
+ * If `size` is smaller than the total size of the signature, the signature will be
+ * truncated to this `size`.
+ *
+ * \return The total size of the signature.
+ *
+ * [RFC 6979]: https://datatracker.ietf.org/doc/html/rfc6979
+ */
+size_t AVmAttestationResult_sign(const struct AVmAttestationResult* _Nonnull result,
+                                 const void* _Nonnull message, size_t message_size,
+                                 void* _Nullable data, size_t size)
+        __INTRODUCED_IN(__ANDROID_API_V__);
+
+/**
+ * Gets the number of certificates in the certificate chain.
+ *
+ * The certificate chain consists of a sequence of DER-encoded X.509 certificates that form
+ * the attestation key's certificate chain. It starts with a root certificate and ends with a
+ * leaf certificate covering the attested public key.
+ *
+ * \param result A pointer to the attestation result obtained from `AVmPayload_requestAttestation`
+ *               when the attestation succeeds.
+ *
+ * \return The number of certificates in the certificate chain.
+ */
+size_t AVmAttestationResult_getCertificateCount(const struct AVmAttestationResult* _Nonnull result)
+        __INTRODUCED_IN(__ANDROID_API_V__);
+
+/**
+ * Retrieves the certificate at the given `index` from the certificate chain in the provided
+ * attestation result.
+ *
+ * The certificate chain consists of a sequence of DER-encoded X.509 certificates that form
+ * the attestation key's certificate chain. It starts with a root certificate and ends with a
+ * leaf certificate covering the attested public key.
+ *
+ * \param result A pointer to the attestation result obtained from `AVmPayload_requestAttestation`
+ *               when the attestation succeeds.
+ * \param index Index of the certificate to retrieve. The `index` must be within the range of
+ *              [0, number of certificates). The number of certificates can be obtained with
+ *              `AVmAttestationResult_getCertificateCount`.
+ * \param data A pointer to the memory where the certificate will be written
+ *             (can be null if size is 0).
+ * \param size The maximum number of bytes that can be written to the data buffer. If `size`
+ *             is smaller than the total size of the certificate, the certificate will be
+ *             truncated to this `size`.
+ *
+ * \return The total size of the certificate at the given `index`.
+ */
+size_t AVmAttestationResult_getCertificateAt(const struct AVmAttestationResult* _Nonnull result,
+                                             size_t index, void* _Nullable data, size_t size)
+        __INTRODUCED_IN(__ANDROID_API_V__);
+
 __END_DECLS
diff --git a/vm_payload/libvm_payload.map.txt b/vm_payload/libvm_payload.map.txt
index 32dd33b..975a5a3 100644
--- a/vm_payload/libvm_payload.map.txt
+++ b/vm_payload/libvm_payload.map.txt
@@ -8,6 +8,12 @@
     AVmPayload_getApkContentsPath;       # systemapi introduced=UpsideDownCake
     AVmPayload_getEncryptedStoragePath;  # systemapi introduced=UpsideDownCake
     AVmPayload_requestAttestation;       # systemapi introduced=VanillaIceCream
+    AVmAttestationResult_getPrivateKey;  # systemapi introduced=VanillaIceCream
+    AVmAttestationResult_sign;           # systemapi introduced=VanillaIceCream
+    AVmAttestationResult_free;           # systemapi introduced=VanillaIceCream
+    AVmAttestationResult_resultToString; # systemapi introduced=VanillaIceCream
+    AVmAttestationResult_getCertificateCount; # systemapi introduced=VanillaIceCream
+    AVmAttestationResult_getCertificateAt; # systemapi introduced=VanillaIceCream
   local:
     *;
 };
diff --git a/vm_payload/src/api.rs b/vm_payload/src/api.rs
index 93dbd1c..64f8d6a 100644
--- a/vm_payload/src/api.rs
+++ b/vm_payload/src/api.rs
@@ -14,20 +14,30 @@
 
 //! This module handles the interaction with virtual machine payload service.
 
-use android_system_virtualization_payload::aidl::android::system::virtualization::payload::IVmPayloadService::{
-    ENCRYPTEDSTORE_MOUNTPOINT, IVmPayloadService, VM_PAYLOAD_SERVICE_SOCKET_NAME, VM_APK_CONTENTS_PATH};
-use anyhow::{ensure, bail, Context, Result};
-use binder::{Strong, unstable_api::{AIBinder, new_spibinder}};
+use android_system_virtualization_payload::aidl::android::system::virtualization::payload:: IVmPayloadService::{
+    IVmPayloadService, ENCRYPTEDSTORE_MOUNTPOINT, VM_APK_CONTENTS_PATH,
+    VM_PAYLOAD_SERVICE_SOCKET_NAME, AttestationResult::AttestationResult,
+};
+use anyhow::{bail, ensure, Context, Result};
+use binder::{
+    unstable_api::{new_spibinder, AIBinder},
+    Strong,
+};
 use lazy_static::lazy_static;
 use log::{error, info, Level};
-use rpcbinder::{RpcSession, RpcServer};
+use rpcbinder::{RpcServer, RpcSession};
+use openssl::{ec::EcKey, sha::sha256, ecdsa::EcdsaSig};
 use std::convert::Infallible;
-use std::ffi::CString;
+use std::ffi::{CString, CStr};
 use std::fmt::Debug;
 use std::os::raw::{c_char, c_void};
 use std::path::Path;
-use std::ptr;
-use std::sync::{Mutex, atomic::{AtomicBool, Ordering}};
+use std::ptr::{self, NonNull};
+use std::sync::{
+    atomic::{AtomicBool, Ordering},
+    Mutex,
+};
+use vm_payload_status_bindgen::attestation_status_t;
 
 lazy_static! {
     static ref VM_APK_CONTENTS_PATH_C: CString =
@@ -263,42 +273,210 @@
 /// Behavior is undefined if any of the following conditions are violated:
 ///
 /// * `challenge` must be [valid] for reads of `challenge_size` bytes.
-/// * `buffer` must be [valid] for writes of `size` bytes. `buffer` can be null if `size` is 0.
+/// * `res` must be [valid] to write the attestation result.
+/// * The region of memory beginning at `challenge` with `challenge_size` bytes must not
+///  overlap with the region of memory `res` points to.
 ///
 /// [valid]: ptr#safety
 #[no_mangle]
 pub unsafe extern "C" fn AVmPayload_requestAttestation(
     challenge: *const u8,
     challenge_size: usize,
-    buffer: *mut u8,
+    res: &mut *mut AttestationResult,
+) -> attestation_status_t {
+    initialize_logging();
+    const MAX_CHALLENGE_SIZE: usize = 64;
+    if challenge_size > MAX_CHALLENGE_SIZE {
+        return attestation_status_t::ATTESTATION_ERROR_INVALID_CHALLENGE;
+    }
+    let challenge = if challenge_size == 0 {
+        &[]
+    } else {
+        // SAFETY: The caller guarantees that `challenge` is valid for reads of
+        // `challenge_size` bytes and `challenge_size` is not zero.
+        unsafe { std::slice::from_raw_parts(challenge, challenge_size) }
+    };
+    let attestation_res = unwrap_or_abort(try_request_attestation(challenge));
+    *res = Box::into_raw(Box::new(attestation_res));
+    attestation_status_t::ATTESTATION_OK
+}
+
+fn try_request_attestation(public_key: &[u8]) -> Result<AttestationResult> {
+    get_vm_payload_service()?
+        .requestAttestation(public_key)
+        .context("Failed to request attestation")
+}
+
+/// Converts the return value from `AVmPayload_requestAttestation` to a text string
+/// representing the error code.
+#[no_mangle]
+pub extern "C" fn AVmAttestationResult_resultToString(
+    status: attestation_status_t,
+) -> *const c_char {
+    let message = match status {
+        attestation_status_t::ATTESTATION_OK => {
+            CStr::from_bytes_with_nul(b"The remote attestation completes successfully.\0").unwrap()
+        }
+        attestation_status_t::ATTESTATION_ERROR_INVALID_CHALLENGE => {
+            CStr::from_bytes_with_nul(b"The challenge size is not between 0 and 64.\0").unwrap()
+        }
+        _ => CStr::from_bytes_with_nul(
+            b"The remote attestation has failed due to an unspecified cause.\0",
+        )
+        .unwrap(),
+    };
+    message.as_ptr()
+}
+
+/// Reads the DER-encoded ECPrivateKey structure specified in [RFC 5915 s3] for the
+/// EC P-256 private key from the provided attestation result.
+///
+/// # Safety
+///
+/// Behavior is undefined if any of the following conditions are violated:
+///
+/// * `data` must be [valid] for writes of `size` bytes, if size > 0.
+/// * The region of memory beginning at `data` with `size` bytes must not overlap with the
+///  region of memory `res` points to.
+///
+/// [valid]: ptr#safety
+/// [RFC 5915 s3]: https://datatracker.ietf.org/doc/html/rfc5915#section-3
+#[no_mangle]
+pub unsafe extern "C" fn AVmAttestationResult_getPrivateKey(
+    res: &AttestationResult,
+    data: *mut u8,
     size: usize,
 ) -> usize {
-    initialize_logging();
+    let private_key = &res.privateKey;
+    if size != 0 {
+        let data = NonNull::new(data).expect("data must not be null when size > 0");
+        // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
+        // the length of either buffer, and the caller ensures that `private_key` cannot overlap
+        // `data`. We allow data to be null, which is never valid, but only if size == 0
+        // which is checked above.
+        unsafe {
+            ptr::copy_nonoverlapping(
+                private_key.as_ptr(),
+                data.as_ptr(),
+                std::cmp::min(private_key.len(), size),
+            )
+        };
+    }
+    private_key.len()
+}
 
-    // SAFETY: See the requirements on `challenge` above.
-    let challenge = unsafe { std::slice::from_raw_parts(challenge, challenge_size) };
-    let certificate = unwrap_or_abort(try_request_attestation(challenge));
+/// Signs the given message using ECDSA P-256, the message is first hashed with SHA-256 and
+/// then it is signed with the attested EC P-256 private key in the attestation result.
+///
+/// # Safety
+///
+/// Behavior is undefined if any of the following conditions are violated:
+///
+/// * `message` must be [valid] for reads of `message_size` bytes.
+/// * `data` must be [valid] for writes of `size` bytes, if size > 0.
+/// * The region of memory beginning at `data` with `size` bytes must not overlap with the
+///  region of memory `res` or `message` point to.
+///
+///
+/// [valid]: ptr#safety
+#[no_mangle]
+pub unsafe extern "C" fn AVmAttestationResult_sign(
+    res: &AttestationResult,
+    message: *const u8,
+    message_size: usize,
+    data: *mut u8,
+    size: usize,
+) -> usize {
+    if message_size == 0 {
+        panic!("Message to be signed must not be empty.")
+    }
+    // SAFETY: See the requirements on `message` above.
+    let message = unsafe { std::slice::from_raw_parts(message, message_size) };
+    let signature = unwrap_or_abort(try_ecdsa_sign(message, &res.privateKey));
+    if size != 0 {
+        let data = NonNull::new(data).expect("data must not be null when size > 0");
+        // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
+        // the length of either buffer, and the caller ensures that `signature` cannot overlap
+        // `data`. We allow data to be null, which is never valid, but only if size == 0
+        // which is checked above.
+        unsafe {
+            ptr::copy_nonoverlapping(
+                signature.as_ptr(),
+                data.as_ptr(),
+                std::cmp::min(signature.len(), size),
+            )
+        };
+    }
+    signature.len()
+}
 
-    if size != 0 || buffer.is_null() {
-        // SAFETY: See the requirements on `buffer` above. The number of bytes copied doesn't exceed
-        // the length of either buffer, and `certificate` cannot overlap `buffer` because we just
-        // allocated it.
+fn try_ecdsa_sign(message: &[u8], der_encoded_ec_private_key: &[u8]) -> Result<Vec<u8>> {
+    let private_key = EcKey::private_key_from_der(der_encoded_ec_private_key)?;
+    let digest = sha256(message);
+    let sig = EcdsaSig::sign(&digest, &private_key)?;
+    Ok(sig.to_der()?)
+}
+
+/// Gets the number of certificates in the certificate chain.
+#[no_mangle]
+pub extern "C" fn AVmAttestationResult_getCertificateCount(res: &AttestationResult) -> usize {
+    res.certificateChain.len()
+}
+
+/// Retrieves the certificate at the given `index` from the certificate chain in the provided
+/// attestation result.
+///
+/// # Safety
+///
+/// Behavior is undefined if any of the following conditions are violated:
+///
+/// * `data` must be [valid] for writes of `size` bytes, if size > 0.
+/// * `index` must be within the range of [0, number of certificates). The number of certificates
+///   can be obtained with `AVmAttestationResult_getCertificateCount`.
+/// * The region of memory beginning at `data` with `size` bytes must not overlap with the
+///  region of memory `res` points to.
+///
+/// [valid]: ptr#safety
+#[no_mangle]
+pub unsafe extern "C" fn AVmAttestationResult_getCertificateAt(
+    res: &AttestationResult,
+    index: usize,
+    data: *mut u8,
+    size: usize,
+) -> usize {
+    let certificate =
+        &res.certificateChain.get(index).expect("The index is out of bounds.").encodedCertificate;
+    if size != 0 {
+        let data = NonNull::new(data).expect("data must not be null when size > 0");
+        // SAFETY: See the requirements on `data` above. The number of bytes copied doesn't exceed
+        // the length of either buffer, and the caller ensures that `certificate` cannot overlap
+        // `data`. We allow data to be null, which is never valid, but only if size == 0
+        // which is checked above.
         unsafe {
             ptr::copy_nonoverlapping(
                 certificate.as_ptr(),
-                buffer,
+                data.as_ptr(),
                 std::cmp::min(certificate.len(), size),
-            );
-        }
+            )
+        };
     }
     certificate.len()
 }
 
-fn try_request_attestation(challenge: &[u8]) -> Result<Vec<u8>> {
-    let certificate = get_vm_payload_service()?
-        .requestAttestation(challenge)
-        .context("Failed to request attestation")?;
-    Ok(certificate)
+/// Frees all the data owned by given attestation result and result itself.
+///
+/// # Safety
+///
+/// Behavior is undefined if any of the following conditions are violated:
+///
+/// * `res` must point to a valid `AttestationResult` and has not been freed before.
+#[no_mangle]
+pub unsafe extern "C" fn AVmAttestationResult_free(res: *mut AttestationResult) {
+    if !res.is_null() {
+        // SAFETY: The result is only freed once is ensured by the caller.
+        let res = unsafe { Box::from_raw(res) };
+        drop(res)
+    }
 }
 
 /// Gets the path to the APK contents.
diff --git a/vm_payload/src/lib.rs b/vm_payload/src/lib.rs
index 4d059d1..e305769 100644
--- a/vm_payload/src/lib.rs
+++ b/vm_payload/src/lib.rs
@@ -17,7 +17,9 @@
 mod api;
 
 pub use api::{
-    AVmPayload_getCertificate, AVmPayload_getDiceAttestationCdi,
-    AVmPayload_getDiceAttestationChain, AVmPayload_getVmInstanceSecret,
-    AVmPayload_notifyPayloadReady,
+    AVmAttestationResult_free, AVmAttestationResult_getCertificateAt,
+    AVmAttestationResult_getCertificatesCount, AVmAttestationResult_getPrivateKey,
+    AVmAttestationResult_resultToString, AVmAttestationResult_sign,
+    AVmPayload_getDiceAttestationCdi, AVmPayload_getDiceAttestationChain,
+    AVmPayload_getVmInstanceSecret, AVmPayload_notifyPayloadReady, AVmPayload_requestAttestation,
 };