[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/service_vm/requests/Android.bp b/service_vm/requests/Android.bp
new file mode 100644
index 0000000..4b9b46f
--- /dev/null
+++ b/service_vm/requests/Android.bp
@@ -0,0 +1,34 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_defaults {
+    name: "libservice_vm_requests_defaults",
+    crate_name: "service_vm_requests",
+    defaults: ["avf_build_flags_rust"],
+    srcs: ["src/lib.rs"],
+    prefer_rlib: true,
+    apex_available: [
+        "com.android.virt",
+    ],
+}
+
+rust_library_rlib {
+    name: "libservice_vm_requests_nostd",
+    defaults: ["libservice_vm_requests_defaults"],
+    no_stdlibs: true,
+    stdlibs: [
+        "libcore.rust_sysroot",
+    ],
+    rustlibs: [
+        "libbssl_avf_error_nostd",
+        "libbssl_avf_nostd",
+        "libciborium_nostd",
+        "libcoset_nostd",
+        "libdiced_open_dice_nostd",
+        "liblog_rust_nostd",
+        "libserde_nostd",
+        "libservice_vm_comm_nostd",
+        "libzeroize_nostd",
+    ],
+}
diff --git a/service_vm/requests/src/api.rs b/service_vm/requests/src/api.rs
new file mode 100644
index 0000000..eae0370
--- /dev/null
+++ b/service_vm/requests/src/api.rs
@@ -0,0 +1,39 @@
+// 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 crate::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/service_vm/requests/src/lib.rs b/service_vm/requests/src/lib.rs
new file mode 100644
index 0000000..fc0c87d
--- /dev/null
+++ b/service_vm/requests/src/lib.rs
@@ -0,0 +1,25 @@
+// 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 library contains functions for the request processing.
+
+#![no_std]
+
+extern crate alloc;
+
+mod api;
+mod pub_key;
+mod rkp;
+
+pub use api::process_request;
diff --git a/service_vm/requests/src/pub_key.rs b/service_vm/requests/src/pub_key.rs
new file mode 100644
index 0000000..110e3d2
--- /dev/null
+++ b/service_vm/requests/src/pub_key.rs
@@ -0,0 +1,54 @@
+// 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/service_vm/requests/src/rkp.rs b/service_vm/requests/src/rkp.rs
new file mode 100644
index 0000000..f96b85d
--- /dev/null
+++ b/service_vm/requests/src/rkp.rs
@@ -0,0 +1,165 @@
+// 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)
+    }
+}