[rkp] Build MACed public key from boringssl EC_KEY

The secret will be added in a subsequent after we get the DICE
chain info of the RKP VM.

Bug: 300068317
Test: atest rialto_test
Change-Id: Ia373930fc8f1c6d38349208ca62b9b71b98d126f
diff --git a/rialto/Android.bp b/rialto/Android.bp
index cb3e477..96b9b10 100644
--- a/rialto/Android.bp
+++ b/rialto/Android.bp
@@ -12,6 +12,7 @@
         "libbssl_ffi_nostd",
         "libciborium_io_nostd",
         "libciborium_nostd",
+        "libcoset_nostd",
         "libdiced_open_dice_nostd",
         "libdiced_sample_inputs_nostd",
         "libhyp",
diff --git a/rialto/src/requests/ec_key.rs b/rialto/src/requests/ec_key.rs
index 2f3fe90..1e1a35c 100644
--- a/rialto/src/requests/ec_key.rs
+++ b/rialto/src/requests/ec_key.rs
@@ -16,22 +16,35 @@
 //! BoringSSL.
 
 use alloc::vec::Vec;
+use bssl_ffi::BN_bn2bin_padded;
+use bssl_ffi::BN_clear_free;
+use bssl_ffi::BN_new;
 use bssl_ffi::CBB_flush;
 use bssl_ffi::CBB_init_fixed;
 use bssl_ffi::CBB_len;
 use bssl_ffi::EC_KEY_free;
 use bssl_ffi::EC_KEY_generate_key;
+use bssl_ffi::EC_KEY_get0_group;
+use bssl_ffi::EC_KEY_get0_public_key;
 use bssl_ffi::EC_KEY_marshal_private_key;
 use bssl_ffi::EC_KEY_new_by_curve_name;
+use bssl_ffi::EC_POINT_get_affine_coordinates;
 use bssl_ffi::NID_X9_62_prime256v1; // EC P-256 CURVE Nid
+use bssl_ffi::BIGNUM;
+use bssl_ffi::EC_GROUP;
 use bssl_ffi::EC_KEY;
+use bssl_ffi::EC_POINT;
 use core::mem::MaybeUninit;
-use core::ptr::NonNull;
+use core::ptr::{self, NonNull};
 use core::result;
+use coset::{iana, CoseKey, CoseKeyBuilder};
 use service_vm_comm::{BoringSSLApiName, RequestProcessingError};
 use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
 
+const P256_AFFINE_COORDINATE_SIZE: usize = 32;
+
 type Result<T> = result::Result<T, RequestProcessingError>;
+type Coordinate = [u8; P256_AFFINE_COORDINATE_SIZE];
 
 /// Wrapper of an `EC_KEY` object, representing a public or private EC key.
 pub struct EcKey(NonNull<EC_KEY>);
@@ -66,7 +79,62 @@
         check_int_result(ret, BoringSSLApiName::EC_KEY_generate_key)
     }
 
-    // TODO(b/300068317): Returns the CoseKey for the public key.
+    /// Returns the `CoseKey` for the public key.
+    pub fn cose_public_key(&self) -> Result<CoseKey> {
+        const ALGO: iana::Algorithm = iana::Algorithm::ES256;
+        const CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256;
+
+        let (x, y) = self.public_key_coordinates()?;
+        let key =
+            CoseKeyBuilder::new_ec2_pub_key(CURVE, x.to_vec(), y.to_vec()).algorithm(ALGO).build();
+        Ok(key)
+    }
+
+    /// Returns the x and y coordinates of the public key.
+    fn public_key_coordinates(&self) -> Result<(Coordinate, Coordinate)> {
+        let ec_group = self.ec_group()?;
+        let ec_point = self.public_key_ec_point()?;
+        let mut x = BigNum::new()?;
+        let mut y = BigNum::new()?;
+        let ctx = ptr::null_mut();
+        // SAFETY: All the parameters are checked non-null and initialized when needed.
+        // The last parameter `ctx` is generated when needed inside the function.
+        let ret = unsafe {
+            EC_POINT_get_affine_coordinates(ec_group, ec_point, x.as_mut_ptr(), y.as_mut_ptr(), ctx)
+        };
+        check_int_result(ret, BoringSSLApiName::EC_POINT_get_affine_coordinates)?;
+        Ok((x.try_into()?, y.try_into()?))
+    }
+
+    /// Returns a pointer to the public key point inside `EC_KEY`. The memory region pointed
+    /// by the pointer is owned by the `EC_KEY`.
+    fn public_key_ec_point(&self) -> Result<*const EC_POINT> {
+        let ec_point =
+           // SAFETY: It is safe since the key pair has been generated and stored in the
+           // `EC_KEY` pointer.
+           unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) };
+        if ec_point.is_null() {
+            Err(RequestProcessingError::BoringSSLCallFailed(
+                BoringSSLApiName::EC_KEY_get0_public_key,
+            ))
+        } else {
+            Ok(ec_point)
+        }
+    }
+
+    /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed
+    /// by the pointer is owned by the `EC_KEY`.
+    fn ec_group(&self) -> Result<*const EC_GROUP> {
+        let group =
+           // SAFETY: It is safe since the key pair has been generated and stored in the
+           // `EC_KEY` pointer.
+           unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
+        if group.is_null() {
+            Err(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EC_KEY_get0_group))
+        } else {
+            Ok(group)
+        }
+    }
 
     /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
     ///
@@ -119,6 +187,43 @@
     }
 }
 
+struct BigNum(NonNull<BIGNUM>);
+
+impl Drop for BigNum {
+    fn drop(&mut self) {
+        // SAFETY: The pointer has been created with `BN_new`.
+        unsafe { BN_clear_free(self.as_mut_ptr()) }
+    }
+}
+
+impl BigNum {
+    fn new() -> Result<Self> {
+        // SAFETY: The returned pointer is checked below.
+        let bn = unsafe { BN_new() };
+        NonNull::new(bn)
+            .map(Self)
+            .ok_or(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::BN_new))
+    }
+
+    fn as_mut_ptr(&mut self) -> *mut BIGNUM {
+        self.0.as_ptr()
+    }
+}
+
+/// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to
+/// size `N`. The conversion fails if `N` is smaller thanthe size of the integer.
+impl<const N: usize> TryFrom<BigNum> for [u8; N] {
+    type Error = RequestProcessingError;
+
+    fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> {
+        let mut num = [0u8; N];
+        // SAFETY: The `BIGNUM` pointer has been created with `BN_new`.
+        let ret = unsafe { BN_bn2bin_padded(num.as_mut_ptr(), num.len(), bn.0.as_ptr()) };
+        check_int_result(ret, BoringSSLApiName::BN_bn2bin_padded)?;
+        Ok(num)
+    }
+}
+
 fn check_int_result(ret: i32, api_name: BoringSSLApiName) -> Result<()> {
     if ret == 1 {
         Ok(())
diff --git a/rialto/src/requests/mod.rs b/rialto/src/requests/mod.rs
index d70791f..8162237 100644
--- a/rialto/src/requests/mod.rs
+++ b/rialto/src/requests/mod.rs
@@ -16,6 +16,7 @@
 
 mod api;
 mod ec_key;
+mod pub_key;
 mod rkp;
 
 pub use api::process_request;
diff --git a/rialto/src/requests/pub_key.rs b/rialto/src/requests/pub_key.rs
new file mode 100644
index 0000000..84373ce
--- /dev/null
+++ b/rialto/src/requests/pub_key.rs
@@ -0,0 +1,71 @@
+// Copyright 2023, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Handles the construction of the MACed public key.
+
+use alloc::vec;
+use alloc::vec::Vec;
+use bssl_ffi::EVP_sha256;
+use bssl_ffi::HMAC;
+use core::result;
+use coset::{iana, CborSerializable, CoseKey, CoseMac0Builder, HeaderBuilder};
+use service_vm_comm::{BoringSSLApiName, RequestProcessingError};
+
+type Result<T> = result::Result<T, RequestProcessingError>;
+
+/// Returns the MACed public key.
+pub fn build_maced_public_key(public_key: CoseKey, hmac_key: &[u8]) -> Result<Vec<u8>> {
+    const ALGO: iana::Algorithm = iana::Algorithm::HMAC_256_256;
+
+    let external_aad = &[];
+    let protected = HeaderBuilder::new().algorithm(ALGO).build();
+    let cose_mac = CoseMac0Builder::new()
+        .protected(protected)
+        .payload(public_key.to_vec()?)
+        .try_create_tag(external_aad, |data| hmac_sha256(hmac_key, data))?
+        .build();
+    Ok(cose_mac.to_vec()?)
+}
+
+/// Computes the HMAC using SHA-256 for the given `data` with the given `key`.
+fn hmac_sha256(key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
+    const SHA256_HMAC_LEN: usize = 32;
+
+    let mut out = vec![0u8; SHA256_HMAC_LEN];
+    let mut out_len = 0;
+    // SAFETY: The function shouldn't access any Rust variable and the returned value is accepted
+    // as a potentially NULL pointer.
+    let digester = unsafe { EVP_sha256() };
+    if digester.is_null() {
+        return Err(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EVP_sha256));
+    }
+    // SAFETY: Only reads from/writes to the provided slices and supports digester was checked not
+    // be NULL.
+    let ret = unsafe {
+        HMAC(
+            digester,
+            key.as_ptr() as *const _,
+            key.len(),
+            data.as_ptr(),
+            data.len(),
+            out.as_mut_ptr(),
+            &mut out_len,
+        )
+    };
+    if !ret.is_null() && out_len == (out.len() as u32) {
+        Ok(out)
+    } else {
+        Err(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::HMAC))
+    }
+}
diff --git a/rialto/src/requests/rkp.rs b/rialto/src/requests/rkp.rs
index 66d3603..58e054f 100644
--- a/rialto/src/requests/rkp.rs
+++ b/rialto/src/requests/rkp.rs
@@ -16,6 +16,7 @@
 //! service VM via the RKP (Remote Key Provisioning) server.
 
 use super::ec_key::EcKey;
+use super::pub_key::build_maced_public_key;
 use alloc::vec::Vec;
 use core::result;
 use diced_open_dice::DiceArtifacts;
@@ -26,14 +27,15 @@
 pub(super) fn generate_ecdsa_p256_key_pair(
     _dice_artifacts: &dyn DiceArtifacts,
 ) -> Result<EcdsaP256KeyPair> {
+    let hmac_key = [];
     let ec_key = EcKey::new_p256()?;
+    let maced_public_key = build_maced_public_key(ec_key.cose_public_key()?, &hmac_key)?;
 
     // TODO(b/279425980): Encrypt the private key in a key blob.
     // Remove the printing of the private key.
     log::debug!("Private key: {:?}", ec_key.private_key()?.as_slice());
 
-    // TODO(b/300068317): Build MACed public key.
-    let key_pair = EcdsaP256KeyPair { maced_public_key: Vec::new(), key_blob: Vec::new() };
+    let key_pair = EcdsaP256KeyPair { maced_public_key, key_blob: Vec::new() };
     Ok(key_pair)
 }
 
diff --git a/rialto/tests/test.rs b/rialto/tests/test.rs
index b8ced95..e975bbf 100644
--- a/rialto/tests/test.rs
+++ b/rialto/tests/test.rs
@@ -75,11 +75,18 @@
     info!("Received response: {response:?}.");
 
     match response {
-        Response::GenerateEcdsaP256KeyPair(EcdsaP256KeyPair { .. }) => Ok(()),
+        Response::GenerateEcdsaP256KeyPair(EcdsaP256KeyPair { maced_public_key, .. }) => {
+            assert_array_has_nonzero(&maced_public_key[..]);
+            Ok(())
+        }
         _ => bail!("Incorrect response type"),
     }
 }
 
+fn assert_array_has_nonzero(v: &[u8]) {
+    assert!(v.iter().any(|&x| x != 0))
+}
+
 fn check_processing_generating_certificate_request(vm: &mut ServiceVm) -> Result<()> {
     let params = GenerateCertificateRequestParams { keys_to_sign: vec![], challenge: vec![] };
     let request = Request::GenerateCertificateRequest(params);