Merge "Add guest OS capability: SecretkeeperProtection" into main
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 171389b..adf6309 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -72,6 +72,9 @@
"path": "packages/modules/Virtualization/libs/avb"
},
{
+ "path": "packages/modules/Virtualization/libs/bssl"
+ },
+ {
"path": "packages/modules/Virtualization/libs/capabilities"
},
{
diff --git a/libs/bssl/Android.bp b/libs/bssl/Android.bp
new file mode 100644
index 0000000..949c2c4
--- /dev/null
+++ b/libs/bssl/Android.bp
@@ -0,0 +1,48 @@
+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",
+ ],
+ rustlibs: [
+ "libbssl_avf_error_nostd",
+ "libbssl_ffi_nostd",
+ "libcoset_nostd",
+ "liblog_rust_nostd",
+ "libzeroize_nostd",
+ ],
+}
+
+rust_defaults {
+ name: "libbssl_avf_test_defaults",
+ crate_name: "bssl_avf_test",
+ srcs: ["tests/*.rs"],
+ test_suites: ["general-tests"],
+ static_libs: [
+ "libcrypto_baremetal",
+ ],
+}
+
+rust_test {
+ name: "libbssl_avf_nostd.test",
+ defaults: ["libbssl_avf_test_defaults"],
+ rustlibs: [
+ "libbssl_avf_nostd",
+ ],
+}
diff --git a/libs/bssl/TEST_MAPPING b/libs/bssl/TEST_MAPPING
new file mode 100644
index 0000000..a91e8c5
--- /dev/null
+++ b/libs/bssl/TEST_MAPPING
@@ -0,0 +1,9 @@
+// When adding or removing tests here, don't forget to amend _all_modules list in
+// wireless/android/busytown/ath_config/configs/prod/avf/tests.gcl
+{
+ "avf-presubmit" : [
+ {
+ "name" : "libbssl_avf_nostd.test"
+ }
+ ]
+}
\ No newline at end of file
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..1f9751f
--- /dev/null
+++ b/libs/bssl/error/src/lib.rs
@@ -0,0 +1,63 @@
+// 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),
+
+ /// An unexpected internal error occurred.
+ InternalError,
+}
+
+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:?}")
+ }
+ Self::InternalError => write!(f, "An unexpected internal error occurred"),
+ }
+ }
+}
+
+/// 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,
+ HMAC,
+}
diff --git a/libs/bssl/src/cbb.rs b/libs/bssl/src/cbb.rs
new file mode 100644
index 0000000..9b5f7fe
--- /dev/null
+++ b/libs/bssl/src/cbb.rs
@@ -0,0 +1,53 @@
+// 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.
+
+//! Helpers for using BoringSSL CBB (crypto byte builder) objects.
+
+use bssl_ffi::{CBB_init_fixed, CBB};
+use core::marker::PhantomData;
+use core::mem::MaybeUninit;
+
+/// Wraps a CBB that references a existing fixed-sized buffer; no memory is allocated, but the
+/// 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.
+ _buffer: PhantomData<&'a mut [u8]>,
+}
+
+impl<'a> CbbFixed<'a> {
+ /// 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.
+ // The buffer remains valid during the lifetime of `cbb`.
+ unsafe { CBB_init_fixed(cbb.as_mut_ptr(), buffer.as_mut_ptr(), buffer.len()) };
+ // SAFETY: `cbb` has just been initialized by `CBB_init_fixed()`.
+ let cbb = unsafe { cbb.assume_init() };
+ Self { cbb, _buffer: PhantomData }
+ }
+}
+
+impl<'a> AsRef<CBB> for CbbFixed<'a> {
+ fn as_ref(&self) -> &CBB {
+ &self.cbb
+ }
+}
+
+impl<'a> AsMut<CBB> for CbbFixed<'a> {
+ fn as_mut(&mut self) -> &mut CBB {
+ &mut self.cbb
+ }
+}
diff --git a/libs/bssl/src/digest.rs b/libs/bssl/src/digest.rs
new file mode 100644
index 0000000..47e4aba
--- /dev/null
+++ b/libs/bssl/src/digest.rs
@@ -0,0 +1,50 @@
+// 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.
+
+//! Wrappers of the digest functions in BoringSSL digest.h.
+
+use bssl_ffi::{EVP_MD_size, EVP_sha256, EVP_sha512, EVP_MD};
+
+/// Message digester wrapping `EVP_MD`.
+#[derive(Clone, Debug)]
+pub struct Digester(pub(crate) &'static EVP_MD);
+
+impl Digester {
+ /// Returns a `Digester` implementing `SHA-256` algorithm.
+ pub fn sha256() -> Self {
+ // SAFETY: This function does not access any Rust variables and simply returns
+ // a pointer to the static variable in BoringSSL.
+ let p = unsafe { EVP_sha256() };
+ // SAFETY: The returned pointer should always be valid and points to a static
+ // `EVP_MD`.
+ Self(unsafe { &*p })
+ }
+
+ /// Returns a `Digester` implementing `SHA-512` algorithm.
+ #[allow(dead_code)]
+ pub fn sha512() -> Self {
+ // SAFETY: This function does not access any Rust variables and simply returns
+ // a pointer to the static variable in BoringSSL.
+ let p = unsafe { EVP_sha512() };
+ // SAFETY: The returned pointer should always be valid and points to a static
+ // `EVP_MD`.
+ Self(unsafe { &*p })
+ }
+
+ /// Returns the digest size in bytes.
+ pub fn size(&self) -> usize {
+ // SAFETY: The inner pointer is fetched from EVP_* hash functions in BoringSSL digest.h
+ unsafe { EVP_MD_size(self.0) }
+ }
+}
diff --git a/rialto/src/requests/ec_key.rs b/libs/bssl/src/ec_key.rs
similarity index 69%
rename from rialto/src/requests/ec_key.rs
rename to libs/bssl/src/ec_key.rs
index 1e1a35c..901212f 100644
--- a/rialto/src/requests/ec_key.rs
+++ b/libs/bssl/src/ec_key.rs
@@ -15,35 +15,23 @@
//! Contains struct and functions that wraps the API related to EC_KEY in
//! BoringSSL.
+use crate::cbb::CbbFixed;
+use crate::util::check_int_result;
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 bssl_avf_error::{ApiName, 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,
+ EC_KEY_new_by_curve_name, EC_POINT_get_affine_coordinates, NID_X9_62_prime256v1, BIGNUM,
+ EC_GROUP, EC_KEY, EC_POINT,
+};
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.
@@ -61,10 +49,12 @@
/// Creates a new EC P-256 key pair.
pub fn new_p256() -> Result<Self> {
// SAFETY: The returned pointer is checked below.
- let ec_key = unsafe { EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) };
- let mut ec_key = NonNull::new(ec_key).map(Self).ok_or(
- RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EC_KEY_new_by_curve_name),
- )?;
+ 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(Error::CallFailed(ApiName::EC_KEY_new_by_curve_name))?;
ec_key.generate_key()?;
Ok(ec_key)
}
@@ -76,7 +66,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.
@@ -102,7 +92,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()?))
}
@@ -114,9 +104,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)
}
@@ -130,7 +118,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)
}
@@ -142,31 +130,21 @@
pub fn private_key(&self) -> Result<ZVec> {
const CAPACITY: usize = 256;
let mut buf = Zeroizing::new([0u8; CAPACITY]);
- // SAFETY: `CBB_init_fixed()` is infallible and always returns one.
- // The `buf` is never moved and remains valid during the lifetime of `cbb`.
- let mut cbb = unsafe {
- let mut cbb = MaybeUninit::uninit();
- CBB_init_fixed(cbb.as_mut_ptr(), buf.as_mut_ptr(), buf.len());
- cbb.assume_init()
- };
+ let mut cbb = CbbFixed::new(buf.as_mut());
let enc_flags = 0;
let ret =
// SAFETY: The function only write bytes to the buffer managed by the valid `CBB`
// object, and the key has been allocated by BoringSSL.
- unsafe { EC_KEY_marshal_private_key(&mut cbb, self.0.as_ptr(), enc_flags) };
+ 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(&mut cbb) }, 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) };
- Ok(buf
- .get(0..len)
- .ok_or(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::CBB_len))?
- .to_vec()
- .into())
+ let len = unsafe { CBB_len(cbb.as_ref()) };
+ Ok(buf.get(0..len).ok_or(Error::CallFailed(ApiName::CBB_len))?.to_vec().into())
}
}
@@ -200,9 +178,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 {
@@ -213,24 +189,15 @@
/// 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<()> {
- if ret == 1 {
- Ok(())
- } else {
- assert_eq!(ret, 0, "Unexpected return value {ret} for {api_name:?}");
- Err(RequestProcessingError::BoringSSLCallFailed(api_name))
- }
-}
-
// TODO(b/301068421): Unit tests the EcKey.
diff --git a/libs/bssl/src/hmac.rs b/libs/bssl/src/hmac.rs
new file mode 100644
index 0000000..1e09315
--- /dev/null
+++ b/libs/bssl/src/hmac.rs
@@ -0,0 +1,58 @@
+// 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.
+
+//! Wrappers of the HMAC functions in BoringSSL hmac.h.
+
+use crate::digest::Digester;
+use bssl_avf_error::{ApiName, Error, Result};
+use bssl_ffi::{HMAC, SHA256_DIGEST_LENGTH};
+
+const SHA256_LEN: usize = SHA256_DIGEST_LENGTH as usize;
+
+/// Computes the HMAC using SHA-256 for the given `data` with the given `key`.
+pub fn hmac_sha256(key: &[u8], data: &[u8]) -> Result<[u8; SHA256_LEN]> {
+ hmac::<SHA256_LEN>(key, data, Digester::sha256())
+}
+
+/// Computes the HMAC for the given `data` with the given `key` and `digester`.
+///
+/// The output size `HASH_LEN` should correspond to the length of the hash function's
+/// digest size in bytes.
+fn hmac<const HASH_LEN: usize>(
+ key: &[u8],
+ data: &[u8],
+ digester: Digester,
+) -> Result<[u8; HASH_LEN]> {
+ assert_eq!(digester.size(), HASH_LEN);
+
+ let mut out = [0u8; HASH_LEN];
+ let mut out_len = 0;
+ // SAFETY: Only reads from/writes to the provided slices and the digester was non-null.
+ let ret = unsafe {
+ HMAC(
+ digester.0,
+ 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(Error::CallFailed(ApiName::HMAC))
+ }
+}
diff --git a/libs/service_vm_comm/src/lib.rs b/libs/bssl/src/lib.rs
similarity index 68%
copy from libs/service_vm_comm/src/lib.rs
copy to libs/bssl/src/lib.rs
index 7bcb9cd..1824080 100644
--- a/libs/service_vm_comm/src/lib.rs
+++ b/libs/bssl/src/lib.rs
@@ -12,18 +12,19 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! This library contains the communication protocol used between the host
-//! and the service VM.
+//! Safe wrappers around the BoringSSL API.
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
-mod message;
-mod vsock;
+mod cbb;
+mod digest;
+mod ec_key;
+mod hmac;
+mod util;
-pub use message::{
- BoringSSLApiName, EcdsaP256KeyPair, GenerateCertificateRequestParams, Request,
- RequestProcessingError, Response, ServiceVmRequest,
-};
-pub use vsock::VmType;
+pub use bssl_avf_error::{ApiName, Error, Result};
+pub use cbb::CbbFixed;
+pub use ec_key::{EcKey, ZVec};
+pub use hmac::hmac_sha256;
diff --git a/libs/bssl/src/util.rs b/libs/bssl/src/util.rs
new file mode 100644
index 0000000..cb5e368
--- /dev/null
+++ b/libs/bssl/src/util.rs
@@ -0,0 +1,32 @@
+// 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.
+
+//! Utility functions.
+
+use bssl_avf_error::{ApiName, Error, Result};
+use log::error;
+
+pub(crate) fn check_int_result(ret: i32, api_name: ApiName) -> Result<()> {
+ match ret {
+ 1 => Ok(()),
+ 0 => Err(Error::CallFailed(api_name)),
+ _ => {
+ error!(
+ "Received a return value ({}) other than 0 or 1 from the BoringSSL API: {:?}",
+ ret, api_name
+ );
+ Err(Error::InternalError)
+ }
+ }
+}
diff --git a/libs/bssl/tests/api_test.rs b/libs/bssl/tests/api_test.rs
new file mode 100644
index 0000000..25aaf04
--- /dev/null
+++ b/libs/bssl/tests/api_test.rs
@@ -0,0 +1,40 @@
+// 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.
+
+use bssl_avf::{hmac_sha256, Result};
+
+const DATA1: [u8; 32] = [
+ 0xdb, 0x16, 0xcc, 0xbf, 0xf0, 0xc4, 0xbc, 0x93, 0xc3, 0x5f, 0x11, 0xc5, 0xfa, 0xae, 0x03, 0x6c,
+ 0x75, 0x40, 0x1f, 0x60, 0xb6, 0x3e, 0xb9, 0x2a, 0x6c, 0x84, 0x06, 0x4b, 0x36, 0x7f, 0xed, 0xdb,
+];
+const DATA2: [u8; 32] = [
+ 0xaa, 0x57, 0x7a, 0x1a, 0x8b, 0xa2, 0x59, 0x3b, 0xad, 0x5f, 0x4d, 0x29, 0xe1, 0x0c, 0xaa, 0x85,
+ 0xde, 0xf9, 0xad, 0xad, 0x8c, 0x11, 0x0c, 0x2e, 0x13, 0x43, 0xd7, 0xdf, 0x2a, 0x43, 0xb9, 0xdd,
+];
+
+#[test]
+fn hmac_sha256_returns_correct_result() -> Result<()> {
+ // The EXPECTED_HMAC can by computed with python:
+ // ```
+ // import hashlib; import base64; import hmac;
+ // print(hmac.new(bytes(DATA1), bytes(DATA2), hashlib.sha256).hexdigest())
+ // ```
+ const EXPECTED_HMAC: [u8; 32] = [
+ 0xe9, 0x0d, 0x40, 0x9a, 0xef, 0x0d, 0xb1, 0x0b, 0x57, 0x82, 0xc4, 0x95, 0x6b, 0x4d, 0x54,
+ 0x38, 0xa9, 0x41, 0xb0, 0xc9, 0xe2, 0x15, 0x59, 0x72, 0xb1, 0x0b, 0x0a, 0x03, 0xe1, 0x38,
+ 0x8d, 0x07,
+ ];
+ assert_eq!(EXPECTED_HMAC, hmac_sha256(&DATA1, &DATA2)?);
+ Ok(())
+}
diff --git a/libs/libfdt/src/lib.rs b/libs/libfdt/src/lib.rs
index 1bf285e..9da2054 100644
--- a/libs/libfdt/src/lib.rs
+++ b/libs/libfdt/src/lib.rs
@@ -802,13 +802,12 @@
}
fn check_full(&self) -> Result<()> {
- let len = self.buffer.len();
// SAFETY: Only performs read accesses within the limits of the slice. If successful, this
// call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
// 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
// checking. The library doesn't maintain an internal state (such as pointers) between
// calls as it expects the client code to keep track of the objects (DT, nodes, ...).
- let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), len) };
+ let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), self.capacity()) };
fdt_err_expect_zero(ret)
}
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/mod.rs b/rialto/src/requests/mod.rs
index 8162237..d9e6f37 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 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..110e3d2 100644
--- a/rialto/src/requests/pub_key.rs
+++ b/rialto/src/requests/pub_key.rs
@@ -14,13 +14,11 @@
//! 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 bssl_avf::hmac_sha256;
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>;
@@ -50,39 +48,7 @@
let cose_mac = CoseMac0Builder::new()
.protected(protected)
.payload(public_key.to_vec()?)
- .try_create_tag(external_aad, |data| hmac_sha256(hmac_key, data))?
+ .try_create_tag(external_aad, |data| hmac_sha256(hmac_key, data).map(|v| v.to_vec()))?
.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 bcddf67..f96b85d 100644
--- a/rialto/src/requests/rkp.rs
+++ b/rialto/src/requests/rkp.rs
@@ -15,25 +15,36 @@
//! This module contains functions related to the attestation of the
//! service VM via the RKP (Remote Key Provisioning) server.
-use super::ec_key::EcKey;
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::DiceArtifacts;
+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,
+ dice_artifacts: &dyn DiceArtifacts,
) -> Result<EcdsaP256KeyPair> {
- let hmac_key = [];
+ 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)?;
+ 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.
@@ -54,13 +65,12 @@
/// generateCertificateRequestV2.cddl
pub(super) fn generate_certificate_request(
params: GenerateCertificateRequestParams,
- _dice_artifacts: &dyn DiceArtifacts,
+ dice_artifacts: &dyn DiceArtifacts,
) -> Result<Vec<u8>> {
- // TODO(b/300590857): Derive the HMAC key from the DICE sealing CDI.
- let hmac_key = [];
+ 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)?;
+ let public_key = validate_public_key(&key_to_sign, hmac_key.as_ref())?;
public_keys.push(public_key.to_cbor_value()?);
}
// Builds `CsrPayload`.
@@ -75,12 +85,16 @@
// 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)?.to_cbor_value()?;
+ let signed_data = build_signed_data(&signed_data_payload, dice_artifacts)?.to_cbor_value()?;
// Builds `AuthenticatedRequest<CsrPayload>`.
- // TODO(b/287233786): Add UdsCerts and DiceCertChain here.
+ // 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 = Value::Array(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,
@@ -90,22 +104,43 @@
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) -> Result<CoseSign1> {
- // TODO(b/299256925): Adjust the signing algorithm if needed.
- let signing_algorithm = iana::Algorithm::ES256;
+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(&[], sign_data)?
+ .try_create_signature(&[], |message| sign_message(message, &cdi_leaf_priv))?
.build();
Ok(signed_data)
}
-fn sign_data(_data: &[u8]) -> Result<Vec<u8>> {
- // TODO(b/287233786): Sign the data with the CDI leaf private key.
- Ok(Vec::new())
+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>> {
@@ -113,3 +148,18 @@
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)
+ }
+}
diff --git a/libs/service_vm_comm/Android.bp b/service_vm/comm/Android.bp
similarity index 92%
rename from libs/service_vm_comm/Android.bp
rename to service_vm/comm/Android.bp
index a7481e5..3a18052 100644
--- a/libs/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/libs/service_vm_comm/src/lib.rs b/service_vm/comm/src/lib.rs
similarity index 85%
rename from libs/service_vm_comm/src/lib.rs
rename to service_vm/comm/src/lib.rs
index 7bcb9cd..d8f7bd7 100644
--- a/libs/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/libs/service_vm_comm/src/message.rs b/service_vm/comm/src/message.rs
similarity index 86%
rename from libs/service_vm_comm/src/message.rs
rename to service_vm/comm/src/message.rs
index 570cf38..f8d7420 100644
--- a/libs/service_vm_comm/src/message.rs
+++ b/service_vm/comm/src/message.rs
@@ -70,35 +70,18 @@
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,
+ /// An unexpected internal error occurred.
+ InternalError,
+
/// Any key to sign lacks a valid MAC. Maps to `STATUS_INVALID_MAC`.
InvalidMac,
@@ -107,24 +90,35 @@
/// An error happened when serializing to/from a `Value`.
CborValueError,
+
+ /// The DICE chain of the service VM is missing.
+ MissingDiceChain,
}
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::InternalError => write!(f, "An unexpected internal error occurred"),
Self::InvalidMac => write!(f, "A key to sign lacks a valid MAC."),
Self::KeyToSignHasEmptyPayload => write!(f, "No payload found in a key to sign."),
Self::CborValueError => {
write!(f, "An error happened when serializing to/from a CBOR Value.")
}
+ Self::MissingDiceChain => write!(f, "The DICE chain of the service VM is missing"),
}
}
}
+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}");
diff --git a/libs/service_vm_comm/src/vsock.rs b/service_vm/comm/src/vsock.rs
similarity index 100%
rename from libs/service_vm_comm/src/vsock.rs
rename to service_vm/comm/src/vsock.rs
diff --git a/service_vm_manager/Android.bp b/service_vm/manager/Android.bp
similarity index 100%
rename from service_vm_manager/Android.bp
rename to service_vm/manager/Android.bp
diff --git a/service_vm_manager/src/lib.rs b/service_vm/manager/src/lib.rs
similarity index 100%
rename from service_vm_manager/src/lib.rs
rename to service_vm/manager/src/lib.rs