[bssl] Add no_std compatible BoringSSL wrapper library for AVF

Bug: 301068421
Test: atest rialto_test
Change-Id: I8af77d457f7a956b0bc88ba4a0498483651426b0
diff --git a/libs/bssl/Android.bp b/libs/bssl/Android.bp
new file mode 100644
index 0000000..5eda389
--- /dev/null
+++ b/libs/bssl/Android.bp
@@ -0,0 +1,30 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_defaults {
+    name: "libbssl_avf_defaults",
+    crate_name: "bssl_avf",
+    srcs: ["src/lib.rs"],
+    prefer_rlib: true,
+    apex_available: [
+        "com.android.virt",
+    ],
+}
+
+rust_library_rlib {
+    name: "libbssl_avf_nostd",
+    defaults: ["libbssl_avf_defaults"],
+    no_stdlibs: true,
+    stdlibs: [
+        "libcompiler_builtins.rust_sysroot",
+        "libcore.rust_sysroot",
+    ],
+    static_libs: [
+        "libcrypto_baremetal",
+    ],
+    rustlibs: [
+        "libbssl_avf_error_nostd",
+        "libbssl_ffi_nostd",
+    ],
+}
diff --git a/libs/bssl/error/Android.bp b/libs/bssl/error/Android.bp
new file mode 100644
index 0000000..dc2902e
--- /dev/null
+++ b/libs/bssl/error/Android.bp
@@ -0,0 +1,37 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_defaults {
+    name: "libbssl_avf_error_defaults",
+    crate_name: "bssl_avf_error",
+    srcs: ["src/lib.rs"],
+    prefer_rlib: true,
+    apex_available: [
+        "com.android.virt",
+    ],
+}
+
+rust_library_rlib {
+    name: "libbssl_avf_error_nostd",
+    defaults: ["libbssl_avf_error_defaults"],
+    no_stdlibs: true,
+    stdlibs: [
+        "libcompiler_builtins.rust_sysroot",
+        "libcore.rust_sysroot",
+    ],
+    rustlibs: [
+        "libserde_nostd",
+    ],
+}
+
+rust_library {
+    name: "libbssl_avf_error",
+    defaults: ["libbssl_avf_error_defaults"],
+    features: [
+        "std",
+    ],
+    rustlibs: [
+        "libserde",
+    ],
+}
diff --git a/libs/bssl/error/src/lib.rs b/libs/bssl/error/src/lib.rs
new file mode 100644
index 0000000..73afbc2
--- /dev/null
+++ b/libs/bssl/error/src/lib.rs
@@ -0,0 +1,60 @@
+// 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.
+
+//! Errors and relating structs thrown by the BoringSSL wrapper library.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use core::{fmt, result};
+use serde::{Deserialize, Serialize};
+
+/// libbssl_avf result type.
+pub type Result<T> = result::Result<T, Error>;
+
+/// Error type used by libbssl_avf.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum Error {
+    /// Failed to invoke a BoringSSL API.
+    CallFailed(ApiName),
+}
+
+impl fmt::Display for Error {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        match self {
+            Self::CallFailed(api_name) => {
+                write!(f, "Failed to invoke the BoringSSL API: {api_name:?}")
+            }
+        }
+    }
+}
+
+/// BoringSSL API names.
+#[allow(missing_docs)]
+#[allow(non_camel_case_types)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum ApiName {
+    BN_new,
+    BN_bn2bin_padded,
+    CBB_flush,
+    CBB_len,
+    EC_KEY_check_key,
+    EC_KEY_generate_key,
+    EC_KEY_get0_group,
+    EC_KEY_get0_public_key,
+    EC_KEY_marshal_private_key,
+    EC_KEY_new_by_curve_name,
+    EC_POINT_get_affine_coordinates,
+    EVP_sha256,
+    HMAC,
+}
diff --git a/rialto/src/requests/cbb.rs b/libs/bssl/src/cbb.rs
similarity index 89%
rename from rialto/src/requests/cbb.rs
rename to libs/bssl/src/cbb.rs
index eceac59..9b5f7fe 100644
--- a/rialto/src/requests/cbb.rs
+++ b/libs/bssl/src/cbb.rs
@@ -13,6 +13,7 @@
 // limitations under the License.
 
 //! Helpers for using BoringSSL CBB (crypto byte builder) objects.
+
 use bssl_ffi::{CBB_init_fixed, CBB};
 use core::marker::PhantomData;
 use core::mem::MaybeUninit;
@@ -21,13 +22,13 @@
 /// buffer cannot grow.
 pub struct CbbFixed<'a> {
     cbb: CBB,
-    // The CBB contains a mutable reference to the buffer, disguised as a pointer.
-    // Make sure the borrow checker knows that.
+    /// The CBB contains a mutable reference to the buffer, disguised as a pointer.
+    /// Make sure the borrow checker knows that.
     _buffer: PhantomData<&'a mut [u8]>,
 }
 
 impl<'a> CbbFixed<'a> {
-    // Create a new CBB that writes to the given buffer.
+    /// Create a new CBB that writes to the given buffer.
     pub fn new(buffer: &'a mut [u8]) -> Self {
         let mut cbb = MaybeUninit::uninit();
         // SAFETY: `CBB_init_fixed()` is infallible and always returns one.
diff --git a/libs/bssl/src/lib.rs b/libs/bssl/src/lib.rs
new file mode 100644
index 0000000..a4e00f0
--- /dev/null
+++ b/libs/bssl/src/lib.rs
@@ -0,0 +1,22 @@
+// 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.
+
+//! Safe wrappers around the BoringSSL API.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+mod cbb;
+
+pub use bssl_avf_error::{ApiName, Error, Result};
+pub use cbb::CbbFixed;
diff --git a/rialto/Android.bp b/rialto/Android.bp
index 8a56ebe..bc08d8c 100644
--- a/rialto/Android.bp
+++ b/rialto/Android.bp
@@ -9,6 +9,7 @@
     defaults: ["vmbase_ffi_defaults"],
     rustlibs: [
         "libaarch64_paging",
+        "libbssl_avf_nostd",
         "libbssl_ffi_nostd",
         "libciborium_io_nostd",
         "libciborium_nostd",
@@ -25,9 +26,6 @@
         "libvmbase",
         "libzeroize_nostd",
     ],
-    static_libs: [
-        "libcrypto_baremetal",
-    ],
 }
 
 cc_binary {
diff --git a/rialto/src/requests/ec_key.rs b/rialto/src/requests/ec_key.rs
index 4578526..fa96023 100644
--- a/rialto/src/requests/ec_key.rs
+++ b/rialto/src/requests/ec_key.rs
@@ -15,8 +15,8 @@
 //! Contains struct and functions that wraps the API related to EC_KEY in
 //! BoringSSL.
 
-use super::cbb::CbbFixed;
 use alloc::vec::Vec;
+use bssl_avf::{ApiName, CbbFixed, Error, Result};
 use bssl_ffi::{
     BN_bn2bin_padded, BN_clear_free, BN_new, CBB_flush, CBB_len, EC_KEY_free, EC_KEY_generate_key,
     EC_KEY_get0_group, EC_KEY_get0_public_key, EC_KEY_marshal_private_key,
@@ -26,12 +26,10 @@
 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.
@@ -52,9 +50,9 @@
         let ec_key = unsafe {
             EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
         };
-        let mut ec_key = NonNull::new(ec_key).map(Self).ok_or(
-            RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EC_KEY_new_by_curve_name),
-        )?;
+        let mut ec_key = NonNull::new(ec_key)
+            .map(Self)
+            .ok_or(Error::CallFailed(ApiName::EC_KEY_new_by_curve_name))?;
         ec_key.generate_key()?;
         Ok(ec_key)
     }
@@ -66,7 +64,7 @@
         // point to a valid `EC_KEY`.
         // The randomness is provided by `getentropy()` in `vmbase`.
         let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) };
-        check_int_result(ret, BoringSSLApiName::EC_KEY_generate_key)
+        check_int_result(ret, ApiName::EC_KEY_generate_key)
     }
 
     /// Returns the `CoseKey` for the public key.
@@ -92,7 +90,7 @@
         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)?;
+        check_int_result(ret, ApiName::EC_POINT_get_affine_coordinates)?;
         Ok((x.try_into()?, y.try_into()?))
     }
 
@@ -104,9 +102,7 @@
            // `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,
-            ))
+            Err(Error::CallFailed(ApiName::EC_KEY_get0_public_key))
         } else {
             Ok(ec_point)
         }
@@ -120,7 +116,7 @@
            // `EC_KEY` pointer.
            unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
         if group.is_null() {
-            Err(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EC_KEY_get0_group))
+            Err(Error::CallFailed(ApiName::EC_KEY_get0_group))
         } else {
             Ok(group)
         }
@@ -139,18 +135,14 @@
             // object, and the key has been allocated by BoringSSL.
             unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.0.as_ptr(), enc_flags) };
 
-        check_int_result(ret, BoringSSLApiName::EC_KEY_marshal_private_key)?;
+        check_int_result(ret, ApiName::EC_KEY_marshal_private_key)?;
         // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
         // `CBB_init_fixed()`.
-        check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, BoringSSLApiName::CBB_flush)?;
+        check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, ApiName::CBB_flush)?;
         // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
         // and it has been flushed, thus it has no active children.
         let len = unsafe { CBB_len(cbb.as_ref()) };
-        Ok(buf
-            .get(0..len)
-            .ok_or(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::CBB_len))?
-            .to_vec()
-            .into())
+        Ok(buf.get(0..len).ok_or(Error::CallFailed(ApiName::CBB_len))?.to_vec().into())
     }
 }
 
@@ -184,9 +176,7 @@
     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))
+        NonNull::new(bn).map(Self).ok_or(Error::CallFailed(ApiName::BN_new))
     }
 
     fn as_mut_ptr(&mut self) -> *mut BIGNUM {
@@ -197,23 +187,23 @@
 /// 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;
+    type Error = Error;
 
     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)?;
+        check_int_result(ret, ApiName::BN_bn2bin_padded)?;
         Ok(num)
     }
 }
 
-fn check_int_result(ret: i32, api_name: BoringSSLApiName) -> Result<()> {
+fn check_int_result(ret: i32, api_name: ApiName) -> Result<()> {
     if ret == 1 {
         Ok(())
     } else {
         assert_eq!(ret, 0, "Unexpected return value {ret} for {api_name:?}");
-        Err(RequestProcessingError::BoringSSLCallFailed(api_name))
+        Err(Error::CallFailed(api_name))
     }
 }
 
diff --git a/rialto/src/requests/mod.rs b/rialto/src/requests/mod.rs
index 12838f3..8162237 100644
--- a/rialto/src/requests/mod.rs
+++ b/rialto/src/requests/mod.rs
@@ -15,7 +15,6 @@
 //! This module contains functions for the request processing.
 
 mod api;
-mod cbb;
 mod ec_key;
 mod pub_key;
 mod rkp;
diff --git a/rialto/src/requests/pub_key.rs b/rialto/src/requests/pub_key.rs
index 3a69a2e..a86ddee 100644
--- a/rialto/src/requests/pub_key.rs
+++ b/rialto/src/requests/pub_key.rs
@@ -16,11 +16,12 @@
 
 use alloc::vec;
 use alloc::vec::Vec;
+use bssl_avf::{self, ApiName};
 use bssl_ffi::EVP_sha256;
 use bssl_ffi::HMAC;
 use core::result;
 use coset::{iana, CborSerializable, CoseKey, CoseMac0, CoseMac0Builder, HeaderBuilder};
-use service_vm_comm::{BoringSSLApiName, RequestProcessingError};
+use service_vm_comm::RequestProcessingError;
 
 type Result<T> = result::Result<T, RequestProcessingError>;
 
@@ -56,7 +57,7 @@
 }
 
 /// Computes the HMAC using SHA-256 for the given `data` with the given `key`.
-fn hmac_sha256(key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
+fn hmac_sha256(key: &[u8], data: &[u8]) -> bssl_avf::Result<Vec<u8>> {
     const SHA256_HMAC_LEN: usize = 32;
 
     let mut out = vec![0u8; SHA256_HMAC_LEN];
@@ -65,7 +66,7 @@
     // as a potentially NULL pointer.
     let digester = unsafe { EVP_sha256() };
     if digester.is_null() {
-        return Err(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EVP_sha256));
+        return Err(bssl_avf::Error::CallFailed(ApiName::EVP_sha256));
     }
     // SAFETY: Only reads from/writes to the provided slices and supports digester was checked not
     // be NULL.
@@ -83,6 +84,6 @@
     if !ret.is_null() && out_len == (out.len() as u32) {
         Ok(out)
     } else {
-        Err(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::HMAC))
+        Err(bssl_avf::Error::CallFailed(ApiName::HMAC))
     }
 }
diff --git a/service_vm/comm/Android.bp b/service_vm/comm/Android.bp
index a7481e5..3a18052 100644
--- a/service_vm/comm/Android.bp
+++ b/service_vm/comm/Android.bp
@@ -21,6 +21,7 @@
         "libcore.rust_sysroot",
     ],
     rustlibs: [
+        "libbssl_avf_error_nostd",
         "libciborium_nostd",
         "libcoset_nostd",
         "liblog_rust_nostd",
@@ -32,6 +33,7 @@
     name: "libservice_vm_comm",
     defaults: ["libservice_vm_comm_defaults"],
     rustlibs: [
+        "libbssl_avf_error",
         "libciborium",
         "libcoset",
         "liblog_rust",
diff --git a/service_vm/comm/src/lib.rs b/service_vm/comm/src/lib.rs
index 7bcb9cd..d8f7bd7 100644
--- a/service_vm/comm/src/lib.rs
+++ b/service_vm/comm/src/lib.rs
@@ -23,7 +23,7 @@
 mod vsock;
 
 pub use message::{
-    BoringSSLApiName, EcdsaP256KeyPair, GenerateCertificateRequestParams, Request,
-    RequestProcessingError, Response, ServiceVmRequest,
+    EcdsaP256KeyPair, GenerateCertificateRequestParams, Request, RequestProcessingError, Response,
+    ServiceVmRequest,
 };
 pub use vsock::VmType;
diff --git a/service_vm/comm/src/message.rs b/service_vm/comm/src/message.rs
index 570cf38..443c285 100644
--- a/service_vm/comm/src/message.rs
+++ b/service_vm/comm/src/message.rs
@@ -70,31 +70,11 @@
     Err(RequestProcessingError),
 }
 
-/// BoringSSL API names.
-#[allow(missing_docs)]
-#[allow(non_camel_case_types)]
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
-pub enum BoringSSLApiName {
-    BN_new,
-    BN_bn2bin_padded,
-    CBB_flush,
-    CBB_len,
-    EC_KEY_check_key,
-    EC_KEY_generate_key,
-    EC_KEY_get0_group,
-    EC_KEY_get0_public_key,
-    EC_KEY_marshal_private_key,
-    EC_KEY_new_by_curve_name,
-    EC_POINT_get_affine_coordinates,
-    EVP_sha256,
-    HMAC,
-}
-
 /// Errors related to request processing.
 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
 pub enum RequestProcessingError {
-    /// Failed to invoke a BoringSSL API.
-    BoringSSLCallFailed(BoringSSLApiName),
+    /// An error happened during the interaction with BoringSSL.
+    BoringSslError(bssl_avf_error::Error),
 
     /// An error happened during the interaction with coset.
     CosetError,
@@ -112,8 +92,8 @@
 impl fmt::Display for RequestProcessingError {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         match self {
-            Self::BoringSSLCallFailed(api_name) => {
-                write!(f, "Failed to invoke a BoringSSL API: {api_name:?}")
+            Self::BoringSslError(e) => {
+                write!(f, "An error happened during the interaction with BoringSSL: {e}")
             }
             Self::CosetError => write!(f, "Encountered an error with coset"),
             Self::InvalidMac => write!(f, "A key to sign lacks a valid MAC."),
@@ -125,6 +105,12 @@
     }
 }
 
+impl From<bssl_avf_error::Error> for RequestProcessingError {
+    fn from(e: bssl_avf_error::Error) -> Self {
+        Self::BoringSslError(e)
+    }
+}
+
 impl From<coset::CoseError> for RequestProcessingError {
     fn from(e: coset::CoseError) -> Self {
         error!("Coset error: {e}");