[rkpvm] Move requests module to a separate library

To facilitate the testing later.

No code change in this cl.

Bug: 301068421
Test: atest rialto_test
Change-Id: Iec5b56f08ae462d83dad1e97cd0031fe16eb3189
diff --git a/rialto/Android.bp b/rialto/Android.bp
index bc08d8c..326f6fc 100644
--- a/rialto/Android.bp
+++ b/rialto/Android.bp
@@ -13,7 +13,6 @@
         "libbssl_ffi_nostd",
         "libciborium_io_nostd",
         "libciborium_nostd",
-        "libcoset_nostd",
         "libdiced_open_dice_nostd",
         "libdiced_sample_inputs_nostd",
         "libhyp",
@@ -21,10 +20,10 @@
         "liblibfdt",
         "liblog_rust_nostd",
         "libservice_vm_comm_nostd",
+        "libservice_vm_requests_nostd",
         "libtinyvec_nostd",
         "libvirtio_drivers",
         "libvmbase",
-        "libzeroize_nostd",
     ],
 }
 
diff --git a/rialto/src/main.rs b/rialto/src/main.rs
index ebc16a9..d9cffe0 100644
--- a/rialto/src/main.rs
+++ b/rialto/src/main.rs
@@ -21,14 +21,12 @@
 mod error;
 mod exceptions;
 mod fdt;
-mod requests;
 
 extern crate alloc;
 
 use crate::communication::VsockStream;
 use crate::error::{Error, Result};
 use crate::fdt::read_dice_range_from;
-use crate::requests::process_request;
 use alloc::boxed::Box;
 use bssl_ffi::CRYPTO_library_init;
 use ciborium_io::Write;
@@ -40,6 +38,7 @@
 use libfdt::FdtError;
 use log::{debug, error, info};
 use service_vm_comm::{ServiceVmRequest, VmType};
+use service_vm_requests::process_request;
 use virtio_drivers::{
     device::socket::{VsockAddr, VMADDR_CID_HOST},
     transport::{pci::bus::PciRoot, DeviceType, Transport},
diff --git a/rialto/src/requests.rs b/rialto/src/requests.rs
deleted file mode 100644
index d9e6f37..0000000
--- a/rialto/src/requests.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-// 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.
-
-//! This module contains functions for the request processing.
-
-mod api;
-mod pub_key;
-mod rkp;
-
-pub use api::process_request;
diff --git a/rialto/src/requests/api.rs b/rialto/src/requests/api.rs
deleted file mode 100644
index ca60f85..0000000
--- a/rialto/src/requests/api.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-// 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.
-
-//! This module contains the main API for the request processing module.
-
-use super::rkp;
-use alloc::vec::Vec;
-use diced_open_dice::DiceArtifacts;
-use service_vm_comm::{Request, Response};
-
-/// Processes a request and returns the corresponding response.
-/// This function serves as the entry point for the request processing
-/// module.
-pub fn process_request(request: Request, dice_artifacts: &dyn DiceArtifacts) -> Response {
-    match request {
-        Request::Reverse(v) => Response::Reverse(reverse(v)),
-        Request::GenerateEcdsaP256KeyPair => rkp::generate_ecdsa_p256_key_pair(dice_artifacts)
-            .map_or_else(Response::Err, Response::GenerateEcdsaP256KeyPair),
-        Request::GenerateCertificateRequest(p) => {
-            rkp::generate_certificate_request(p, dice_artifacts)
-                .map_or_else(Response::Err, Response::GenerateCertificateRequest)
-        }
-    }
-}
-
-fn reverse(payload: Vec<u8>) -> Vec<u8> {
-    payload.into_iter().rev().collect()
-}
diff --git a/rialto/src/requests/pub_key.rs b/rialto/src/requests/pub_key.rs
deleted file mode 100644
index 110e3d2..0000000
--- a/rialto/src/requests/pub_key.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-// 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::Vec;
-use bssl_avf::hmac_sha256;
-use core::result;
-use coset::{iana, CborSerializable, CoseKey, CoseMac0, CoseMac0Builder, HeaderBuilder};
-use service_vm_comm::RequestProcessingError;
-
-type Result<T> = result::Result<T, RequestProcessingError>;
-
-/// Verifies the MAC of the given public key.
-pub fn validate_public_key(maced_public_key: &[u8], hmac_key: &[u8]) -> Result<CoseKey> {
-    let cose_mac = CoseMac0::from_slice(maced_public_key)?;
-    cose_mac.verify_tag(&[], |tag, data| verify_tag(tag, data, hmac_key))?;
-    let payload = cose_mac.payload.ok_or(RequestProcessingError::KeyToSignHasEmptyPayload)?;
-    Ok(CoseKey::from_slice(&payload)?)
-}
-
-fn verify_tag(tag: &[u8], data: &[u8], hmac_key: &[u8]) -> Result<()> {
-    let computed_tag = hmac_sha256(hmac_key, data)?;
-    if tag == computed_tag {
-        Ok(())
-    } else {
-        Err(RequestProcessingError::InvalidMac)
-    }
-}
-
-/// 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).map(|v| v.to_vec()))?
-        .build();
-    Ok(cose_mac.to_vec()?)
-}
diff --git a/rialto/src/requests/rkp.rs b/rialto/src/requests/rkp.rs
deleted file mode 100644
index f96b85d..0000000
--- a/rialto/src/requests/rkp.rs
+++ /dev/null
@@ -1,165 +0,0 @@
-// 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.
-
-//! This module contains functions related to the attestation of the
-//! service VM via the RKP (Remote Key Provisioning) server.
-
-use super::pub_key::{build_maced_public_key, validate_public_key};
-use alloc::string::String;
-use alloc::vec;
-use alloc::vec::Vec;
-use bssl_avf::EcKey;
-use ciborium::{cbor, value::Value};
-use core::result;
-use coset::{iana, AsCborValue, CoseSign1, CoseSign1Builder, HeaderBuilder};
-use diced_open_dice::{kdf, keypair_from_seed, sign, DiceArtifacts, PrivateKey};
-use log::error;
-use service_vm_comm::{EcdsaP256KeyPair, GenerateCertificateRequestParams, RequestProcessingError};
-use zeroize::Zeroizing;
-
-type Result<T> = result::Result<T, RequestProcessingError>;
-
-/// The salt is generated randomly with:
-/// hexdump -vn32 -e'16/1 "0x%02X, " 1 "\n"' /dev/urandom
-const HMAC_KEY_SALT: [u8; 32] = [
-    0x82, 0x80, 0xFA, 0xD3, 0xA8, 0x0A, 0x9A, 0x4B, 0xF7, 0xA5, 0x7D, 0x7B, 0xE9, 0xC3, 0xAB, 0x13,
-    0x89, 0xDC, 0x7B, 0x46, 0xEE, 0x71, 0x22, 0xB4, 0x5F, 0x4C, 0x3F, 0xE2, 0x40, 0x04, 0x3B, 0x6C,
-];
-const HMAC_KEY_INFO: &[u8] = b"rialto hmac key";
-const HMAC_KEY_LENGTH: usize = 32;
-
-pub(super) fn generate_ecdsa_p256_key_pair(
-    dice_artifacts: &dyn DiceArtifacts,
-) -> Result<EcdsaP256KeyPair> {
-    let hmac_key = derive_hmac_key(dice_artifacts)?;
-    let ec_key = EcKey::new_p256()?;
-    let maced_public_key = build_maced_public_key(ec_key.cose_public_key()?, hmac_key.as_ref())?;
-
-    // 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());
-
-    let key_pair = EcdsaP256KeyPair { maced_public_key, key_blob: Vec::new() };
-    Ok(key_pair)
-}
-
-const CSR_PAYLOAD_SCHEMA_V3: u8 = 3;
-const AUTH_REQ_SCHEMA_V1: u8 = 1;
-// TODO(b/300624493): Add a new certificate type for AVF CSR.
-const CERTIFICATE_TYPE: &str = "keymint";
-
-/// Builds the CSR described in:
-///
-/// hardware/interfaces/security/rkp/aidl/android/hardware/security/keymint/
-/// generateCertificateRequestV2.cddl
-pub(super) fn generate_certificate_request(
-    params: GenerateCertificateRequestParams,
-    dice_artifacts: &dyn DiceArtifacts,
-) -> Result<Vec<u8>> {
-    let hmac_key = derive_hmac_key(dice_artifacts)?;
-    let mut public_keys: Vec<Value> = Vec::new();
-    for key_to_sign in params.keys_to_sign {
-        let public_key = validate_public_key(&key_to_sign, hmac_key.as_ref())?;
-        public_keys.push(public_key.to_cbor_value()?);
-    }
-    // Builds `CsrPayload`.
-    let csr_payload = cbor!([
-        Value::Integer(CSR_PAYLOAD_SCHEMA_V3.into()),
-        Value::Text(String::from(CERTIFICATE_TYPE)),
-        // TODO(b/299256925): Add device info in CBOR format here.
-        Value::Array(public_keys),
-    ])?;
-    let csr_payload = cbor_to_vec(&csr_payload)?;
-
-    // Builds `SignedData`.
-    let signed_data_payload =
-        cbor!([Value::Bytes(params.challenge.to_vec()), Value::Bytes(csr_payload)])?;
-    let signed_data = build_signed_data(&signed_data_payload, dice_artifacts)?.to_cbor_value()?;
-
-    // Builds `AuthenticatedRequest<CsrPayload>`.
-    // Currently `UdsCerts` is left empty because it is only needed for Samsung devices.
-    // Check http://b/301574013#comment3 for more information.
-    let uds_certs = Value::Map(Vec::new());
-    let dice_cert_chain = dice_artifacts
-        .bcc()
-        .map(read_to_value)
-        .ok_or(RequestProcessingError::MissingDiceChain)??;
-    let auth_req = cbor!([
-        Value::Integer(AUTH_REQ_SCHEMA_V1.into()),
-        uds_certs,
-        dice_cert_chain,
-        signed_data,
-    ])?;
-    cbor_to_vec(&auth_req)
-}
-
-fn derive_hmac_key(dice_artifacts: &dyn DiceArtifacts) -> Result<Zeroizing<[u8; HMAC_KEY_LENGTH]>> {
-    let mut key = Zeroizing::new([0u8; HMAC_KEY_LENGTH]);
-    kdf(dice_artifacts.cdi_seal(), &HMAC_KEY_SALT, HMAC_KEY_INFO, key.as_mut()).map_err(|e| {
-        error!("Failed to compute the HMAC key: {e}");
-        RequestProcessingError::InternalError
-    })?;
-    Ok(key)
-}
-
-/// Builds the `SignedData` for the given payload.
-fn build_signed_data(payload: &Value, dice_artifacts: &dyn DiceArtifacts) -> Result<CoseSign1> {
-    let cdi_leaf_priv = derive_cdi_leaf_priv(dice_artifacts).map_err(|e| {
-        error!("Failed to derive the CDI_Leaf_Priv: {e}");
-        RequestProcessingError::InternalError
-    })?;
-    let signing_algorithm = iana::Algorithm::EdDSA;
-    let protected = HeaderBuilder::new().algorithm(signing_algorithm).build();
-    let signed_data = CoseSign1Builder::new()
-        .protected(protected)
-        .payload(cbor_to_vec(payload)?)
-        .try_create_signature(&[], |message| sign_message(message, &cdi_leaf_priv))?
-        .build();
-    Ok(signed_data)
-}
-
-fn derive_cdi_leaf_priv(dice_artifacts: &dyn DiceArtifacts) -> diced_open_dice::Result<PrivateKey> {
-    let (_, private_key) = keypair_from_seed(dice_artifacts.cdi_attest())?;
-    Ok(private_key)
-}
-
-fn sign_message(message: &[u8], private_key: &PrivateKey) -> Result<Vec<u8>> {
-    Ok(sign(message, private_key.as_array())
-        .map_err(|e| {
-            error!("Failed to sign the CSR: {e}");
-            RequestProcessingError::InternalError
-        })?
-        .to_vec())
-}
-
-fn cbor_to_vec(v: &Value) -> Result<Vec<u8>> {
-    let mut data = Vec::new();
-    ciborium::into_writer(v, &mut data).map_err(coset::CoseError::from)?;
-    Ok(data)
-}
-
-/// Read a CBOR `Value` from a byte slice, failing if any extra data remains
-/// after the `Value` has been read.
-fn read_to_value(mut data: &[u8]) -> Result<Value> {
-    let value = ciborium::from_reader(&mut data).map_err(|e| {
-        error!("Failed to deserialize the data into CBOR value: {e}");
-        RequestProcessingError::CborValueError
-    })?;
-    if data.is_empty() {
-        Ok(value)
-    } else {
-        error!("CBOR input has extra data.");
-        Err(RequestProcessingError::CborValueError)
-    }
-}