Merge "Latest kernel SecretkeeperProtection capability" into main
diff --git a/Android.bp b/Android.bp
index 22581b0..2f6fc20 100644
--- a/Android.bp
+++ b/Android.bp
@@ -54,7 +54,7 @@
cfgs: ["llpvm_changes"],
},
release_avf_enable_multi_tenant_microdroid_vm: {
- cfgs: ["payload_not_root"],
+ cfgs: ["multi_tenant"],
},
release_avf_enable_remote_attestation: {
cfgs: ["remote_attestation"],
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/encryptedstore/src/main.rs b/encryptedstore/src/main.rs
index db3d4f6..dcb1cba 100644
--- a/encryptedstore/src/main.rs
+++ b/encryptedstore/src/main.rs
@@ -94,7 +94,7 @@
}
mount(&crypt_device, mountpoint)
.with_context(|| format!("Unable to mount {:?}", crypt_device))?;
- if cfg!(payload_not_root) && needs_formatting {
+ if cfg!(multi_tenant) && needs_formatting {
set_root_dir_permissions(mountpoint)?;
}
Ok(())
diff --git a/javalib/api/test-current.txt b/javalib/api/test-current.txt
index 7c61712..12c099d 100644
--- a/javalib/api/test-current.txt
+++ b/javalib/api/test-current.txt
@@ -20,7 +20,7 @@
public class VirtualMachineManager {
method @RequiresPermission(android.system.virtualmachine.VirtualMachine.MANAGE_VIRTUAL_MACHINE_PERMISSION) public boolean isFeatureEnabled(String) throws android.system.virtualmachine.VirtualMachineException;
field public static final String FEATURE_DICE_CHANGES = "com.android.kvm.DICE_CHANGES";
- field public static final String FEATURE_PAYLOAD_NOT_ROOT = "com.android.kvm.PAYLOAD_NON_ROOT";
+ field public static final String FEATURE_MULTI_TENANT = "com.android.kvm.MULTI_TENANT";
field public static final String FEATURE_VENDOR_MODULES = "com.android.kvm.VENDOR_MODULES";
}
diff --git a/javalib/src/android/system/virtualmachine/VirtualMachineManager.java b/javalib/src/android/system/virtualmachine/VirtualMachineManager.java
index e45fe99..a4927db 100644
--- a/javalib/src/android/system/virtualmachine/VirtualMachineManager.java
+++ b/javalib/src/android/system/virtualmachine/VirtualMachineManager.java
@@ -107,7 +107,7 @@
@Retention(RetentionPolicy.SOURCE)
@StringDef(
prefix = "FEATURE_",
- value = {FEATURE_DICE_CHANGES, FEATURE_PAYLOAD_NOT_ROOT, FEATURE_VENDOR_MODULES})
+ value = {FEATURE_DICE_CHANGES, FEATURE_MULTI_TENANT, FEATURE_VENDOR_MODULES})
public @interface Features {}
/**
@@ -123,8 +123,7 @@
* @hide
*/
@TestApi
- public static final String FEATURE_PAYLOAD_NOT_ROOT =
- IVirtualizationService.FEATURE_PAYLOAD_NON_ROOT;
+ public static final String FEATURE_MULTI_TENANT = IVirtualizationService.FEATURE_MULTI_TENANT;
/**
* Feature to allow vendor modules in Microdroid.
diff --git a/libs/bssl/Android.bp b/libs/bssl/Android.bp
new file mode 100644
index 0000000..0a2f334
--- /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/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/code.rs b/libs/bssl/error/src/code.rs
new file mode 100644
index 0000000..7fb36c4
--- /dev/null
+++ b/libs/bssl/error/src/code.rs
@@ -0,0 +1,98 @@
+// 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 core::fmt;
+use serde::{Deserialize, Serialize};
+
+type BsslReasonCode = i32;
+type BsslLibraryCode = i32;
+
+/// BoringSSL reason code.
+#[allow(missing_docs)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum ReasonCode {
+ NoError,
+ Global(GlobalError),
+ Cipher(CipherError),
+ Unknown(BsslReasonCode, BsslLibraryCode),
+}
+
+impl fmt::Display for ReasonCode {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self {
+ Self::NoError => write!(f, "No error in the BoringSSL error queue."),
+ Self::Unknown(code, lib) => {
+ write!(f, "Unknown reason code '{code}' from the library '{lib}'")
+ }
+ other => write!(f, "{other:?}"),
+ }
+ }
+}
+
+/// Global errors may occur in any library.
+///
+/// The values are from:
+/// boringssl/src/include/openssl/err.h
+#[allow(missing_docs)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum GlobalError {
+ Fatal,
+ MallocFailure,
+ ShouldNotHaveBeenCalled,
+ PassedNullParameter,
+ InternalError,
+ Overflow,
+}
+
+impl fmt::Display for GlobalError {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "A global error occurred: {self:?}")
+ }
+}
+
+/// Errors occurred in the Cipher functions.
+///
+/// The values are from:
+/// boringssl/src/include/openssl/cipher.h
+#[allow(missing_docs)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum CipherError {
+ AesKeySetupFailed,
+ BadDecrypt,
+ BadKeyLength,
+ BufferTooSmall,
+ CtrlNotImplemented,
+ CtrlOperationNotImplemented,
+ DataNotMultipleOfBlockLength,
+ InitializationError,
+ InputNotInitialized,
+ InvalidAdSize,
+ InvalidKeyLength,
+ InvalidNonceSize,
+ InvalidOperation,
+ IvTooLarge,
+ NoCipherSet,
+ OutputAliasesInput,
+ TagTooLarge,
+ TooLarge,
+ WrongFinalBlockLength,
+ NoDirectionSet,
+ InvalidNonce,
+}
+
+impl fmt::Display for CipherError {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "An error occurred in a Cipher function: {self:?}")
+ }
+}
diff --git a/libs/bssl/error/src/lib.rs b/libs/bssl/error/src/lib.rs
new file mode 100644
index 0000000..80398c0
--- /dev/null
+++ b/libs/bssl/error/src/lib.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.
+
+//! Errors and relating structs thrown by the BoringSSL wrapper library.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+mod code;
+
+use core::{fmt, result};
+use serde::{Deserialize, Serialize};
+
+pub use crate::code::{CipherError, GlobalError, ReasonCode};
+
+/// 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, ReasonCode),
+
+ /// 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, reason) => {
+ write!(f, "Failed to invoke the BoringSSL API: {api_name:?}. Reason: {reason}")
+ }
+ 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,
+ EVP_AEAD_CTX_new,
+ EVP_AEAD_CTX_open,
+ EVP_AEAD_CTX_seal,
+ HKDF,
+ HMAC,
+}
diff --git a/libs/bssl/src/aead.rs b/libs/bssl/src/aead.rs
new file mode 100644
index 0000000..a7d03b9
--- /dev/null
+++ b/libs/bssl/src/aead.rs
@@ -0,0 +1,160 @@
+// 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 AEAD functions in BoringSSL aead.h.
+
+use crate::util::{check_int_result, to_call_failed_error};
+use bssl_avf_error::{ApiName, Result};
+use bssl_ffi::{
+ EVP_AEAD_CTX_free, EVP_AEAD_CTX_new, EVP_AEAD_CTX_open, EVP_AEAD_CTX_seal,
+ EVP_AEAD_max_overhead, EVP_AEAD_nonce_length, EVP_aead_aes_256_gcm, EVP_AEAD, EVP_AEAD_CTX,
+ EVP_AEAD_DEFAULT_TAG_LENGTH,
+};
+use core::ptr::NonNull;
+
+/// Magic value indicating that the default tag length for an AEAD should be used to
+/// initialize `AeadCtx`.
+const AEAD_DEFAULT_TAG_LENGTH: usize = EVP_AEAD_DEFAULT_TAG_LENGTH as usize;
+
+/// Represents an AEAD algorithm.
+#[derive(Clone, Copy, Debug)]
+pub struct Aead(&'static EVP_AEAD);
+
+impl Aead {
+ /// This is AES-256 in Galois Counter Mode.
+ /// AES-GCM should only be used with 12-byte (96-bit) nonces as suggested in the
+ /// BoringSSL spec:
+ ///
+ /// https://commondatastorage.googleapis.com/chromium-boringssl-docs/aead.h.html
+ pub fn aes_256_gcm() -> 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_aead_aes_256_gcm() };
+ // SAFETY: The returned pointer should always be valid and points to a static
+ // `EVP_AEAD`.
+ Self(unsafe { &*p })
+ }
+
+ /// Returns the maximum number of additional bytes added by the act of sealing data.
+ pub fn max_overhead(&self) -> usize {
+ // SAFETY: This function only reads from self.
+ unsafe { EVP_AEAD_max_overhead(self.0) }
+ }
+
+ /// Returns the length, in bytes, of the per-message nonce.
+ pub fn nonce_length(&self) -> usize {
+ // SAFETY: This function only reads from self.
+ unsafe { EVP_AEAD_nonce_length(self.0) }
+ }
+}
+
+/// Represents an AEAD algorithm configuration.
+pub struct AeadCtx {
+ ctx: NonNull<EVP_AEAD_CTX>,
+ aead: Aead,
+}
+
+impl Drop for AeadCtx {
+ fn drop(&mut self) {
+ // SAFETY: It is safe because the pointer has been created with `EVP_AEAD_CTX_new`
+ // and isn't used after this.
+ unsafe { EVP_AEAD_CTX_free(self.ctx.as_ptr()) }
+ }
+}
+
+impl AeadCtx {
+ /// Creates a new `AeadCtx` with the given `Aead` algorithm, `key` and `tag_len`.
+ ///
+ /// The default tag length will be used if `tag_len` is None.
+ pub fn new(aead: Aead, key: &[u8], tag_len: Option<usize>) -> Result<Self> {
+ let tag_len = tag_len.unwrap_or(AEAD_DEFAULT_TAG_LENGTH);
+ // SAFETY: This function only reads the given data and the returned pointer is
+ // checked below.
+ let ctx = unsafe { EVP_AEAD_CTX_new(aead.0, key.as_ptr(), key.len(), tag_len) };
+ let ctx = NonNull::new(ctx).ok_or(to_call_failed_error(ApiName::EVP_AEAD_CTX_new))?;
+ Ok(Self { ctx, aead })
+ }
+
+ /// Encrypts and authenticates `data` and writes the result to `out`.
+ /// The `out` length should be at least the `data` length plus the `max_overhead` of the
+ /// `aead` and the length of `nonce` should match the `nonce_length` of the `aead`.
+ /// Otherwise, an error will be returned.
+ ///
+ /// The output is returned as a subslice of `out`.
+ pub fn seal<'b>(
+ &self,
+ data: &[u8],
+ nonce: &[u8],
+ ad: &[u8],
+ out: &'b mut [u8],
+ ) -> Result<&'b [u8]> {
+ let mut out_len = 0;
+ // SAFETY: Only reads from/writes to the provided slices.
+ let ret = unsafe {
+ EVP_AEAD_CTX_seal(
+ self.ctx.as_ptr(),
+ out.as_mut_ptr(),
+ &mut out_len,
+ out.len(),
+ nonce.as_ptr(),
+ nonce.len(),
+ data.as_ptr(),
+ data.len(),
+ ad.as_ptr(),
+ ad.len(),
+ )
+ };
+ check_int_result(ret, ApiName::EVP_AEAD_CTX_seal)?;
+ out.get(0..out_len).ok_or(to_call_failed_error(ApiName::EVP_AEAD_CTX_seal))
+ }
+
+ /// Authenticates `data` and decrypts it to `out`.
+ /// The `out` length should be at least the `data` length, and the length of `nonce` should
+ /// match the `nonce_length` of the `aead`.
+ /// Otherwise, an error will be returned.
+ ///
+ /// The output is returned as a subslice of `out`.
+ pub fn open<'b>(
+ &self,
+ data: &[u8],
+ nonce: &[u8],
+ ad: &[u8],
+ out: &'b mut [u8],
+ ) -> Result<&'b [u8]> {
+ let mut out_len = 0;
+ // SAFETY: Only reads from/writes to the provided slices.
+ // `data` and `out` are checked to be non-alias internally.
+ let ret = unsafe {
+ EVP_AEAD_CTX_open(
+ self.ctx.as_ptr(),
+ out.as_mut_ptr(),
+ &mut out_len,
+ out.len(),
+ nonce.as_ptr(),
+ nonce.len(),
+ data.as_ptr(),
+ data.len(),
+ ad.as_ptr(),
+ ad.len(),
+ )
+ };
+ check_int_result(ret, ApiName::EVP_AEAD_CTX_open)?;
+ out.get(0..out_len).ok_or(to_call_failed_error(ApiName::EVP_AEAD_CTX_open))
+ }
+
+ /// Returns the `Aead` represented by this `AeadCtx`.
+ pub fn aead(&self) -> Aead {
+ self.aead
+ }
+}
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..49e66e6
--- /dev/null
+++ b/libs/bssl/src/digest.rs
@@ -0,0 +1,49 @@
+// 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.
+ 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..7038e21 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, to_call_failed_error};
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(to_call_failed_error(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(to_call_failed_error(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(to_call_failed_error(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(to_call_failed_error(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(to_call_failed_error(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/err.rs b/libs/bssl/src/err.rs
new file mode 100644
index 0000000..1ee40c9
--- /dev/null
+++ b/libs/bssl/src/err.rs
@@ -0,0 +1,112 @@
+// 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 error handling functions in BoringSSL err.h.
+
+use bssl_avf_error::{CipherError, GlobalError, ReasonCode};
+use bssl_ffi::{self, ERR_get_error, ERR_GET_LIB_RUST, ERR_GET_REASON_RUST};
+
+const NO_ERROR_REASON_CODE: i32 = 0;
+
+/// Returns the reason code for the least recent error and removes that
+/// error from the error queue.
+pub(crate) fn get_error_reason_code() -> ReasonCode {
+ let packed_error = get_packed_error();
+ let reason = get_reason(packed_error);
+ let lib = get_lib(packed_error);
+ map_to_reason_code(reason, lib)
+}
+
+/// Returns the packed error code for the least recent error and removes that
+/// error from the error queue.
+///
+/// Returns 0 if there are no errors in the queue.
+fn get_packed_error() -> u32 {
+ // SAFETY: This function only reads the error queue.
+ unsafe { ERR_get_error() }
+}
+
+fn get_reason(packed_error: u32) -> i32 {
+ // SAFETY: This function only reads the given error code.
+ unsafe { ERR_GET_REASON_RUST(packed_error) }
+}
+
+/// Returns the library code for the error.
+fn get_lib(packed_error: u32) -> i32 {
+ // SAFETY: This function only reads the given error code.
+ unsafe { ERR_GET_LIB_RUST(packed_error) }
+}
+
+fn map_to_reason_code(reason: i32, lib: i32) -> ReasonCode {
+ if reason == NO_ERROR_REASON_CODE {
+ return ReasonCode::NoError;
+ }
+ map_global_reason_code(reason)
+ .map(ReasonCode::Global)
+ .or_else(|| map_library_reason_code(reason, lib))
+ .unwrap_or(ReasonCode::Unknown(reason, lib))
+}
+
+/// Global errors may occur in any library.
+fn map_global_reason_code(reason: i32) -> Option<GlobalError> {
+ let reason = match reason {
+ bssl_ffi::ERR_R_FATAL => GlobalError::Fatal,
+ bssl_ffi::ERR_R_MALLOC_FAILURE => GlobalError::MallocFailure,
+ bssl_ffi::ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED => GlobalError::ShouldNotHaveBeenCalled,
+ bssl_ffi::ERR_R_PASSED_NULL_PARAMETER => GlobalError::PassedNullParameter,
+ bssl_ffi::ERR_R_INTERNAL_ERROR => GlobalError::InternalError,
+ bssl_ffi::ERR_R_OVERFLOW => GlobalError::Overflow,
+ _ => return None,
+ };
+ Some(reason)
+}
+
+fn map_library_reason_code(reason: i32, lib: i32) -> Option<ReasonCode> {
+ u32::try_from(lib).ok().and_then(|x| match x {
+ bssl_ffi::ERR_LIB_CIPHER => map_cipher_reason_code(reason).map(ReasonCode::Cipher),
+ _ => None,
+ })
+}
+
+fn map_cipher_reason_code(reason: i32) -> Option<CipherError> {
+ let error = match reason {
+ bssl_ffi::CIPHER_R_AES_KEY_SETUP_FAILED => CipherError::AesKeySetupFailed,
+ bssl_ffi::CIPHER_R_BAD_DECRYPT => CipherError::BadDecrypt,
+ bssl_ffi::CIPHER_R_BAD_KEY_LENGTH => CipherError::BadKeyLength,
+ bssl_ffi::CIPHER_R_BUFFER_TOO_SMALL => CipherError::BufferTooSmall,
+ bssl_ffi::CIPHER_R_CTRL_NOT_IMPLEMENTED => CipherError::CtrlNotImplemented,
+ bssl_ffi::CIPHER_R_CTRL_OPERATION_NOT_IMPLEMENTED => {
+ CipherError::CtrlOperationNotImplemented
+ }
+ bssl_ffi::CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH => {
+ CipherError::DataNotMultipleOfBlockLength
+ }
+ bssl_ffi::CIPHER_R_INITIALIZATION_ERROR => CipherError::InitializationError,
+ bssl_ffi::CIPHER_R_INPUT_NOT_INITIALIZED => CipherError::InputNotInitialized,
+ bssl_ffi::CIPHER_R_INVALID_AD_SIZE => CipherError::InvalidAdSize,
+ bssl_ffi::CIPHER_R_INVALID_KEY_LENGTH => CipherError::InvalidKeyLength,
+ bssl_ffi::CIPHER_R_INVALID_NONCE_SIZE => CipherError::InvalidNonceSize,
+ bssl_ffi::CIPHER_R_INVALID_OPERATION => CipherError::InvalidOperation,
+ bssl_ffi::CIPHER_R_IV_TOO_LARGE => CipherError::IvTooLarge,
+ bssl_ffi::CIPHER_R_NO_CIPHER_SET => CipherError::NoCipherSet,
+ bssl_ffi::CIPHER_R_OUTPUT_ALIASES_INPUT => CipherError::OutputAliasesInput,
+ bssl_ffi::CIPHER_R_TAG_TOO_LARGE => CipherError::TagTooLarge,
+ bssl_ffi::CIPHER_R_TOO_LARGE => CipherError::TooLarge,
+ bssl_ffi::CIPHER_R_WRONG_FINAL_BLOCK_LENGTH => CipherError::WrongFinalBlockLength,
+ bssl_ffi::CIPHER_R_NO_DIRECTION_SET => CipherError::NoDirectionSet,
+ bssl_ffi::CIPHER_R_INVALID_NONCE => CipherError::InvalidNonce,
+ _ => return None,
+ };
+ Some(error)
+}
diff --git a/libs/bssl/src/hkdf.rs b/libs/bssl/src/hkdf.rs
new file mode 100644
index 0000000..85bd1ff
--- /dev/null
+++ b/libs/bssl/src/hkdf.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 HKDF functions in BoringSSL hkdf.h.
+
+use crate::digest::Digester;
+use crate::util::check_int_result;
+use bssl_avf_error::{ApiName, Result};
+use bssl_ffi::HKDF;
+use zeroize::Zeroizing;
+
+/// Computes HKDF (as specified by [RFC 5869]) of initial keying material `secret` with
+/// `salt` and `info` using the given `digester`.
+///
+/// [RFC 5869]: https://www.rfc-editor.org/rfc/rfc5869.html
+pub fn hkdf<const N: usize>(
+ secret: &[u8],
+ salt: &[u8],
+ info: &[u8],
+ digester: Digester,
+) -> Result<Zeroizing<[u8; N]>> {
+ let mut key = Zeroizing::new([0u8; N]);
+ // SAFETY: Only reads from/writes to the provided slices and the digester was non-null.
+ let ret = unsafe {
+ HKDF(
+ key.as_mut_ptr(),
+ key.len(),
+ digester.0,
+ secret.as_ptr(),
+ secret.len(),
+ salt.as_ptr(),
+ salt.len(),
+ info.as_ptr(),
+ info.len(),
+ )
+ };
+ check_int_result(ret, ApiName::HKDF)?;
+ Ok(key)
+}
diff --git a/libs/bssl/src/hmac.rs b/libs/bssl/src/hmac.rs
new file mode 100644
index 0000000..ddbbe4a
--- /dev/null
+++ b/libs/bssl/src/hmac.rs
@@ -0,0 +1,59 @@
+// 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 crate::util::to_call_failed_error;
+use bssl_avf_error::{ApiName, 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(to_call_failed_error(ApiName::HMAC))
+ }
+}
diff --git a/libs/service_vm_comm/src/lib.rs b/libs/bssl/src/lib.rs
similarity index 65%
copy from libs/service_vm_comm/src/lib.rs
copy to libs/bssl/src/lib.rs
index 7bcb9cd..898e16c 100644
--- a/libs/service_vm_comm/src/lib.rs
+++ b/libs/bssl/src/lib.rs
@@ -12,18 +12,26 @@
// 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 aead;
+mod cbb;
+mod digest;
+mod ec_key;
+mod err;
+mod hkdf;
+mod hmac;
+mod util;
-pub use message::{
- BoringSSLApiName, EcdsaP256KeyPair, GenerateCertificateRequestParams, Request,
- RequestProcessingError, Response, ServiceVmRequest,
-};
-pub use vsock::VmType;
+pub use bssl_avf_error::{ApiName, CipherError, Error, ReasonCode, Result};
+
+pub use aead::{Aead, AeadCtx};
+pub use cbb::CbbFixed;
+pub use digest::Digester;
+pub use ec_key::{EcKey, ZVec};
+pub use hkdf::hkdf;
+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..880c85b
--- /dev/null
+++ b/libs/bssl/src/util.rs
@@ -0,0 +1,37 @@
+// 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 crate::err::get_error_reason_code;
+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, get_error_reason_code())),
+ _ => {
+ error!(
+ "Received a return value ({}) other than 0 or 1 from the BoringSSL API: {:?}",
+ ret, api_name
+ );
+ Err(Error::InternalError)
+ }
+ }
+}
+
+pub(crate) fn to_call_failed_error(api_name: ApiName) -> Error {
+ Error::CallFailed(api_name, get_error_reason_code())
+}
diff --git a/libs/bssl/tests/aead_test.rs b/libs/bssl/tests/aead_test.rs
new file mode 100644
index 0000000..8ac3f12
--- /dev/null
+++ b/libs/bssl/tests/aead_test.rs
@@ -0,0 +1,148 @@
+// 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::{Aead, AeadCtx, ApiName, CipherError, Error, ReasonCode, Result};
+
+/// The following vectors are generated randomly with:
+/// `hexdump -vn32 -e'32/1 "0x%02x, " 1 "\n"' /dev/urandom`
+const KEY1: [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 KEY2: [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,
+];
+/// The following vectors are generated randomly with:
+/// Generated with `hexdump -vn12 -e'12/1 "0x%02x, " 1 "\n"' /dev/urandom`
+const AES_256_GCM_NONCE1: [u8; 12] =
+ [0x56, 0x96, 0x73, 0xe1, 0xc6, 0x3d, 0xca, 0x9a, 0x2f, 0xad, 0x3b, 0xeb];
+const AES_256_GCM_NONCE2: [u8; 12] =
+ [0xa0, 0x27, 0xea, 0x3a, 0x29, 0xfa, 0x8a, 0x49, 0x35, 0x07, 0x32, 0xec];
+const MESSAGE: &[u8] = b"aead_aes_256_gcm test message";
+
+#[test]
+fn aes_256_gcm_encrypts_and_decrypts_successfully() -> Result<()> {
+ let ciphertext = aes_256_gcm_encrypt(MESSAGE)?;
+ let tag_len = None;
+
+ let ad = &[];
+ let aead_ctx = AeadCtx::new(Aead::aes_256_gcm(), &KEY1, tag_len)?;
+ let mut out = vec![0u8; ciphertext.len()];
+
+ let plaintext = aead_ctx.open(&ciphertext, &AES_256_GCM_NONCE1, ad, &mut out)?;
+
+ assert_eq!(MESSAGE, plaintext);
+ Ok(())
+}
+
+#[test]
+fn aes_256_gcm_fails_to_encrypt_with_invalid_nonce() -> Result<()> {
+ let tag_len = None;
+ let aead_ctx = AeadCtx::new(Aead::aes_256_gcm(), &KEY1, tag_len)?;
+ let nonce = &[];
+ let ad = &[];
+ let mut out = vec![0u8; MESSAGE.len() + aead_ctx.aead().max_overhead()];
+
+ let err = aead_ctx.seal(MESSAGE, nonce, ad, &mut out).unwrap_err();
+
+ let expected_err = Error::CallFailed(
+ ApiName::EVP_AEAD_CTX_seal,
+ ReasonCode::Cipher(CipherError::InvalidNonceSize),
+ );
+ assert_eq!(expected_err, err);
+ Ok(())
+}
+
+#[test]
+fn aes_256_gcm_fails_to_decrypt_with_wrong_key() -> Result<()> {
+ let ciphertext = aes_256_gcm_encrypt(MESSAGE)?;
+ let tag_len = None;
+
+ let ad = &[];
+ let aead_ctx2 = AeadCtx::new(Aead::aes_256_gcm(), &KEY2, tag_len)?;
+ let mut plaintext = vec![0u8; ciphertext.len()];
+
+ let err = aead_ctx2.open(&ciphertext, &AES_256_GCM_NONCE1, ad, &mut plaintext).unwrap_err();
+
+ let expected_err =
+ Error::CallFailed(ApiName::EVP_AEAD_CTX_open, ReasonCode::Cipher(CipherError::BadDecrypt));
+ assert_eq!(expected_err, err);
+ Ok(())
+}
+
+#[test]
+fn aes_256_gcm_fails_to_decrypt_with_different_ad() -> Result<()> {
+ let ciphertext = aes_256_gcm_encrypt(MESSAGE)?;
+ let tag_len = None;
+
+ let ad2 = &[1];
+ let aead_ctx = AeadCtx::new(Aead::aes_256_gcm(), &KEY1, tag_len)?;
+ let mut plaintext = vec![0u8; ciphertext.len()];
+
+ let err = aead_ctx.open(&ciphertext, &AES_256_GCM_NONCE1, ad2, &mut plaintext).unwrap_err();
+
+ let expected_err =
+ Error::CallFailed(ApiName::EVP_AEAD_CTX_open, ReasonCode::Cipher(CipherError::BadDecrypt));
+ assert_eq!(expected_err, err);
+ Ok(())
+}
+
+#[test]
+fn aes_256_gcm_fails_to_decrypt_with_different_nonce() -> Result<()> {
+ let ciphertext = aes_256_gcm_encrypt(MESSAGE)?;
+ let tag_len = None;
+
+ let ad = &[];
+ let aead_ctx = AeadCtx::new(Aead::aes_256_gcm(), &KEY1, tag_len)?;
+ let mut plaintext = vec![0u8; ciphertext.len()];
+
+ let err = aead_ctx.open(&ciphertext, &AES_256_GCM_NONCE2, ad, &mut plaintext).unwrap_err();
+
+ let expected_err =
+ Error::CallFailed(ApiName::EVP_AEAD_CTX_open, ReasonCode::Cipher(CipherError::BadDecrypt));
+ assert_eq!(expected_err, err);
+ Ok(())
+}
+
+#[test]
+fn aes_256_gcm_fails_to_decrypt_corrupted_ciphertext() -> Result<()> {
+ let mut ciphertext = aes_256_gcm_encrypt(MESSAGE)?;
+ ciphertext[1] = !ciphertext[1];
+ let tag_len = None;
+
+ let ad = &[];
+ let aead_ctx = AeadCtx::new(Aead::aes_256_gcm(), &KEY1, tag_len)?;
+ let mut plaintext = vec![0u8; ciphertext.len()];
+
+ let err = aead_ctx.open(&ciphertext, &AES_256_GCM_NONCE1, ad, &mut plaintext).unwrap_err();
+
+ let expected_err =
+ Error::CallFailed(ApiName::EVP_AEAD_CTX_open, ReasonCode::Cipher(CipherError::BadDecrypt));
+ assert_eq!(expected_err, err);
+ Ok(())
+}
+
+fn aes_256_gcm_encrypt(message: &[u8]) -> Result<Vec<u8>> {
+ let tag_len = None;
+ let aead_ctx = AeadCtx::new(Aead::aes_256_gcm(), &KEY1, tag_len)?;
+ let mut out = vec![0u8; message.len() + aead_ctx.aead().max_overhead()];
+
+ assert_eq!(aead_ctx.aead().nonce_length(), AES_256_GCM_NONCE1.len());
+ let ad = &[];
+
+ let ciphertext = aead_ctx.seal(message, &AES_256_GCM_NONCE1, ad, &mut out)?;
+ assert_ne!(message, ciphertext);
+ Ok(ciphertext.to_vec())
+}
diff --git a/libs/bssl/tests/hkdf_test.rs b/libs/bssl/tests/hkdf_test.rs
new file mode 100644
index 0000000..2e10314
--- /dev/null
+++ b/libs/bssl/tests/hkdf_test.rs
@@ -0,0 +1,95 @@
+// 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.
+
+//! Test HKDF with the test cases in [RFC 5869] Appendix A
+//!
+//! [RFC 5869]: https://datatracker.ietf.org/doc/html/rfc5869
+
+use bssl_avf::{hkdf, Digester, Result};
+
+#[test]
+fn rfc5869_test_case_1() -> Result<()> {
+ const IKM: [u8; 22] = [
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ ];
+ const SALT: [u8; 13] =
+ [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c];
+ const INFO: [u8; 10] = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9];
+ const L: usize = 42;
+ const OKM: [u8; L] = [
+ 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f,
+ 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4,
+ 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65,
+ ];
+ assert_eq!(OKM, hkdf::<L>(&IKM, &SALT, &INFO, Digester::sha256())?.as_slice());
+ Ok(())
+}
+
+#[test]
+fn rfc5869_test_case_2() -> Result<()> {
+ const IKM: [u8; 80] = [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
+ 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
+ 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c,
+ 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
+ 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
+ 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
+ ];
+ const SALT: [u8; 80] = [
+ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,
+ 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d,
+ 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c,
+ 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,
+ 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,
+ 0xab, 0xac, 0xad, 0xae, 0xaf,
+ ];
+ const INFO: [u8; 80] = [
+ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe,
+ 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd,
+ 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc,
+ 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb,
+ 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa,
+ 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
+ ];
+ const L: usize = 82;
+ const OKM: [u8; L] = [
+ 0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 0xf7, 0x8c, 0x59, 0x6a, 0x49,
+ 0x34, 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c, 0x19, 0xaf,
+ 0xa9, 0x7c, 0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb, 0x41, 0xc6, 0x5e,
+ 0x59, 0x0e, 0x09, 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, 0x36, 0x77, 0x93, 0xa9,
+ 0xac, 0xa3, 0xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec, 0x3e, 0x87, 0xc1, 0x4c, 0x01,
+ 0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x1d, 0x87,
+ ];
+ assert_eq!(OKM, hkdf::<L>(&IKM, &SALT, &INFO, Digester::sha256())?.as_slice());
+ Ok(())
+}
+
+#[test]
+fn rfc5869_test_case_3() -> Result<()> {
+ const IKM: [u8; 22] = [
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ ];
+ const SALT: [u8; 0] = [];
+ const INFO: [u8; 0] = [];
+ const L: usize = 42;
+ const OKM: [u8; L] = [
+ 0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f, 0x80, 0x2a, 0x06, 0x3c, 0x5a,
+ 0x31, 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f, 0x3c, 0x73,
+ 0x8d, 0x2d, 0x9d, 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0xc8,
+ ];
+ assert_eq!(OKM, hkdf::<L>(&IKM, &SALT, &INFO, Digester::sha256())?.as_slice());
+ Ok(())
+}
diff --git a/libs/bssl/tests/hmac_test.rs b/libs/bssl/tests/hmac_test.rs
new file mode 100644
index 0000000..c09a863
--- /dev/null
+++ b/libs/bssl/tests/hmac_test.rs
@@ -0,0 +1,115 @@
+// 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.
+
+//! Tests HMAC with the test cases in [RFC 4231] Section 4
+//!
+//! [RFC 4231]: https://datatracker.ietf.org/doc/html/rfc4231
+
+use bssl_avf::{hmac_sha256, Result};
+
+#[test]
+fn rfc4231_test_case_1() -> Result<()> {
+ const KEY: &[u8; 20] = &[0x0b; 20];
+ const DATA: &[u8] = b"Hi There";
+ const HMAC_SHA256: [u8; 32] = [
+ 0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1,
+ 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32,
+ 0xcf, 0xf7,
+ ];
+ assert_eq!(HMAC_SHA256, hmac_sha256(KEY, DATA)?);
+ Ok(())
+}
+
+#[test]
+fn rfc4231_test_case_2() -> Result<()> {
+ const KEY: &[u8] = b"Jefe";
+ const DATA: &[u8] = b"what do ya want for nothing?";
+ const HMAC_SHA256: [u8; 32] = [
+ 0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, 0x75,
+ 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec,
+ 0x38, 0x43,
+ ];
+ assert_eq!(HMAC_SHA256, hmac_sha256(KEY, DATA)?);
+ Ok(())
+}
+
+#[test]
+fn rfc4231_test_case_3() -> Result<()> {
+ const KEY: &[u8; 20] = &[0xaa; 20];
+ const DATA: &[u8; 50] = &[0xdd; 50];
+ const HMAC_SHA256: [u8; 32] = [
+ 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8, 0xeb, 0xd0, 0x91, 0x81,
+ 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8, 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5,
+ 0x65, 0xfe,
+ ];
+ assert_eq!(HMAC_SHA256, hmac_sha256(KEY, DATA)?);
+ Ok(())
+}
+
+#[test]
+fn rfc4231_test_case_4() -> Result<()> {
+ const KEY: &[u8; 25] = &[
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
+ ];
+ const DATA: &[u8; 50] = &[0xcd; 50];
+ const HMAC_SHA256: [u8; 32] = [
+ 0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81, 0x98, 0x99, 0xf2, 0x08,
+ 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78, 0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29,
+ 0x66, 0x5b,
+ ];
+ assert_eq!(HMAC_SHA256, hmac_sha256(KEY, DATA)?);
+ Ok(())
+}
+
+/// Test with a truncation of output to 128 bits.
+#[test]
+fn rfc4231_test_case_5() -> Result<()> {
+ const KEY: &[u8; 20] = &[0x0c; 20];
+ const DATA: &[u8] = b"Test With Truncation";
+ const HMAC_SHA256: [u8; 16] = [
+ 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0, 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55,
+ 0x2b,
+ ];
+ let res = hmac_sha256(KEY, DATA)?;
+ assert_eq!(HMAC_SHA256, res[..16]);
+ Ok(())
+}
+
+#[test]
+fn rfc4231_test_case_6() -> Result<()> {
+ const KEY: &[u8; 131] = &[0xaa; 131];
+ const DATA: &[u8] = b"Test Using Larger Than Block-Size Key - Hash Key First";
+ const HMAC_SHA256: [u8; 32] = [
+ 0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26, 0xaa, 0xcb, 0xf5, 0xb7,
+ 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28, 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3,
+ 0x7f, 0x54,
+ ];
+ assert_eq!(HMAC_SHA256, hmac_sha256(KEY, DATA)?);
+ Ok(())
+}
+
+#[test]
+fn rfc4231_test_case_7() -> Result<()> {
+ const KEY: &[u8; 131] = &[0xaa; 131];
+ const DATA: &str = "This is a test using a larger than block-size key and a larger than \
+ block-size data. The key needs to be hashed before being used by the HMAC algorithm.";
+ const HMAC_SHA256: [u8; 32] = [
+ 0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f, 0xbc, 0xd5, 0xb0, 0xe9,
+ 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07, 0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a,
+ 0x35, 0xe2,
+ ];
+ assert_eq!(HMAC_SHA256, hmac_sha256(KEY, DATA.as_bytes())?);
+ Ok(())
+}
diff --git a/rialto/src/requests/mod.rs b/libs/bssl/tests/tests.rs
similarity index 81%
copy from rialto/src/requests/mod.rs
copy to libs/bssl/tests/tests.rs
index 8162237..4c0b0b0 100644
--- a/rialto/src/requests/mod.rs
+++ b/libs/bssl/tests/tests.rs
@@ -12,11 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! This module contains functions for the request processing.
+//! API tests of the crate `bssl_avf`.
-mod api;
-mod ec_key;
-mod pub_key;
-mod rkp;
-
-pub use api::process_request;
+mod aead_test;
+mod hkdf_test;
+mod hmac_test;
diff --git a/libs/hyp/src/hypervisor/mod.rs b/libs/hyp/src/hypervisor.rs
similarity index 100%
rename from libs/hyp/src/hypervisor/mod.rs
rename to libs/hyp/src/hypervisor.rs
diff --git a/libs/libfdt/src/lib.rs b/libs/libfdt/src/lib.rs
index 1bf285e..19ce0f7 100644
--- a/libs/libfdt/src/lib.rs
+++ b/libs/libfdt/src/lib.rs
@@ -251,6 +251,18 @@
}
}
+ /// Returns the node name.
+ pub fn name(&self) -> Result<&'a CStr> {
+ let mut len: c_int = 0;
+ // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
+ // function returns valid null terminating string and otherwise returned values are dropped.
+ let name = unsafe { libfdt_bindgen::fdt_get_name(self.fdt.as_ptr(), self.offset, &mut len) }
+ as *const c_void;
+ let len = usize::try_from(fdt_err(len)?).unwrap();
+ let name = self.fdt.get_from_ptr(name, len + 1)?;
+ CStr::from_bytes_with_nul(name).map_err(|_| FdtError::Internal)
+ }
+
/// Retrieve the value of a given <string> property.
pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> {
let value = if let Some(bytes) = self.getprop(name)? {
@@ -293,11 +305,7 @@
/// Retrieve the value of a given property.
pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> {
if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? {
- let offset = (prop as usize)
- .checked_sub(self.fdt.as_ptr() as usize)
- .ok_or(FdtError::Internal)?;
-
- Ok(Some(self.fdt.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal)?))
+ Ok(Some(self.fdt.get_from_ptr(prop, len)?))
} else {
Ok(None) // property was not found
}
@@ -327,7 +335,7 @@
let Some(len) = fdt_err_or_option(len)? else {
return Ok(None); // Property was not found.
};
- let len = usize::try_from(len).map_err(|_| FdtError::Internal)?;
+ let len = usize::try_from(len).unwrap();
if prop.is_null() {
// We expected an error code in len but still received a valid value?!
@@ -802,16 +810,21 @@
}
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)
}
+ fn get_from_ptr(&self, ptr: *const c_void, len: usize) -> Result<&[u8]> {
+ let ptr = ptr as usize;
+ let offset = ptr.checked_sub(self.as_ptr() as usize).ok_or(FdtError::Internal)?;
+ self.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal)
+ }
+
/// Return a shared pointer to the device tree.
pub fn as_ptr(&self) -> *const c_void {
self.buffer.as_ptr().cast::<_>()
diff --git a/libs/libfdt/tests/api_test.rs b/libs/libfdt/tests/api_test.rs
index 806e6c0..866a2bb 100644
--- a/libs/libfdt/tests/api_test.rs
+++ b/libs/libfdt/tests/api_test.rs
@@ -17,6 +17,7 @@
//! Integration tests of the library libfdt.
use libfdt::{Fdt, FdtError};
+use std::ffi::CStr;
use std::fs;
use std::ops::Range;
@@ -70,3 +71,19 @@
assert_eq!(fdt.memory().unwrap_err(), FdtError::NotFound);
assert_eq!(fdt.first_memory_range(), Err(FdtError::NotFound));
}
+
+#[test]
+fn node_name() {
+ let data = fs::read(TEST_TREE_WITH_NO_MEMORY_NODE_PATH).unwrap();
+ let fdt = Fdt::from_slice(&data).unwrap();
+
+ let root = fdt.root().unwrap();
+ assert_eq!(root.name().unwrap().to_str().unwrap(), "");
+
+ let chosen = fdt.chosen().unwrap().unwrap();
+ assert_eq!(chosen.name().unwrap().to_str().unwrap(), "chosen");
+
+ let nested_node_path = CStr::from_bytes_with_nul(b"/cpus/PowerPC,970@0\0").unwrap();
+ let nested_node = fdt.node(nested_node_path).unwrap().unwrap();
+ assert_eq!(nested_node.name().unwrap().to_str().unwrap(), "PowerPC,970@0");
+}
diff --git a/libs/microdroid_uids/src/lib.rs b/libs/microdroid_uids/src/lib.rs
index 04dc190..0248c61 100644
--- a/libs/microdroid_uids/src/lib.rs
+++ b/libs/microdroid_uids/src/lib.rs
@@ -29,7 +29,7 @@
// helps avoid confusion.)
/// Group ID shared by all payload users.
-pub const MICRODROID_PAYLOAD_GID: u32 = if cfg!(payload_not_root) { 6000 } else { 0 };
+pub const MICRODROID_PAYLOAD_GID: u32 = if cfg!(multi_tenant) { 6000 } else { 0 };
/// User ID for the initial payload user.
-pub const MICRODROID_PAYLOAD_UID: u32 = if cfg!(payload_not_root) { 6000 } else { 0 };
+pub const MICRODROID_PAYLOAD_UID: u32 = if cfg!(multi_tenant) { 6000 } else { 0 };
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index a496d53..dd0ddbb 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -729,9 +729,11 @@
let mount_dir = format!("/mnt/extra-apk/{i}");
create_dir(Path::new(&mount_dir)).context("Failed to create mount dir for extra apks")?;
- // don't wait, just detach
+ let mount_for_exec =
+ if cfg!(multi_tenant) { MountForExec::Allowed } else { MountForExec::Disallowed };
+ // These run asynchronously in parallel - we wait later for them to complete.
zipfuse.mount(
- MountForExec::Disallowed,
+ mount_for_exec,
"fscontext=u:object_r:zipfusefs:s0,context=u:object_r:extra_apk_file:s0",
Path::new(&format!("/dev/block/mapper/extra-apk-{i}")),
Path::new(&mount_dir),
diff --git a/pvmfw/Android.bp b/pvmfw/Android.bp
index 523334f..8c21030 100644
--- a/pvmfw/Android.bp
+++ b/pvmfw/Android.bp
@@ -12,6 +12,7 @@
],
rustlibs: [
"libaarch64_paging",
+ "libbssl_avf_nostd",
"libbssl_ffi_nostd",
"libciborium_nostd",
"libciborium_io_nostd",
diff --git a/pvmfw/avb/src/descriptor/mod.rs b/pvmfw/avb/src/descriptor.rs
similarity index 100%
rename from pvmfw/avb/src/descriptor/mod.rs
rename to pvmfw/avb/src/descriptor.rs
diff --git a/pvmfw/src/crypto.rs b/pvmfw/src/crypto.rs
index 94714c0..2b3d921 100644
--- a/pvmfw/src/crypto.rs
+++ b/pvmfw/src/crypto.rs
@@ -31,10 +31,8 @@
use bssl_ffi::EVP_AEAD_CTX_seal;
use bssl_ffi::EVP_AEAD_max_overhead;
use bssl_ffi::EVP_aead_aes_256_gcm_randnonce;
-use bssl_ffi::EVP_sha512;
use bssl_ffi::EVP_AEAD;
use bssl_ffi::EVP_AEAD_CTX;
-use bssl_ffi::HKDF;
use vmbase::cstr;
#[derive(Debug)]
@@ -267,36 +265,6 @@
}
}
-pub fn hkdf_sh512<const N: usize>(secret: &[u8], salt: &[u8], info: &[u8]) -> Result<[u8; N]> {
- let mut key = [0; N];
- // SAFETY: The function shouldn't access any Rust variable and the returned value is accepted
- // as a potentially NULL pointer.
- let digest = unsafe { EVP_sha512() };
-
- assert!(!digest.is_null());
- // SAFETY: Only reads from/writes to the provided slices and supports digest was checked not
- // be NULL.
- let result = unsafe {
- HKDF(
- key.as_mut_ptr(),
- key.len(),
- digest,
- secret.as_ptr(),
- secret.len(),
- salt.as_ptr(),
- salt.len(),
- info.as_ptr(),
- info.len(),
- )
- };
-
- if result == 1 {
- Ok(key)
- } else {
- Err(ErrorIterator {})
- }
-}
-
pub fn init() {
// SAFETY: Configures the internal state of the library - may be called multiple times.
unsafe { CRYPTO_library_init() }
diff --git a/pvmfw/src/instance.rs b/pvmfw/src/instance.rs
index f2b34da..22839cb 100644
--- a/pvmfw/src/instance.rs
+++ b/pvmfw/src/instance.rs
@@ -15,12 +15,12 @@
//! Support for reading and writing to the instance.img.
use crate::crypto;
-use crate::crypto::hkdf_sh512;
use crate::crypto::AeadCtx;
use crate::dice::PartialInputs;
use crate::gpt;
use crate::gpt::Partition;
use crate::gpt::Partitions;
+use bssl_avf::{self, hkdf, Digester};
use core::fmt;
use core::mem::size_of;
use diced_open_dice::DiceMode;
@@ -63,6 +63,8 @@
UnsupportedEntrySize(usize),
/// Failed to create VirtIO Block device.
VirtIOBlkCreationFailed(virtio_drivers::Error),
+ /// An error happened during the interaction with BoringSSL.
+ BoringSslFailed(bssl_avf::Error),
}
impl fmt::Display for Error {
@@ -95,10 +97,19 @@
Self::VirtIOBlkCreationFailed(e) => {
write!(f, "Failed to create VirtIO Block device: {e}")
}
+ Self::BoringSslFailed(e) => {
+ write!(f, "An error happened during the interaction with BoringSSL: {e}")
+ }
}
}
}
+impl From<bssl_avf::Error> for Error {
+ fn from(e: bssl_avf::Error) -> Self {
+ Self::BoringSslFailed(e)
+ }
+}
+
pub type Result<T> = core::result::Result<T, Error>;
pub fn get_or_generate_instance_salt(
@@ -111,7 +122,7 @@
let entry = locate_entry(&mut instance_img)?;
trace!("Found pvmfw instance.img entry: {entry:?}");
- let key = hkdf_sh512::<32>(secret, /*salt=*/ &[], b"vm-instance");
+ let key = hkdf::<32>(secret, /* salt= */ &[], b"vm-instance", Digester::sha512())?;
let mut blk = [0; BLK_SIZE];
match entry {
PvmfwEntry::Existing { header_index, payload_size } => {
@@ -124,8 +135,8 @@
let payload = &blk[..payload_size];
let mut entry = [0; size_of::<EntryBody>()];
- let key = key.map_err(Error::FailedOpen)?;
- let aead = AeadCtx::new_aes_256_gcm_randnonce(&key).map_err(Error::FailedOpen)?;
+ let aead =
+ AeadCtx::new_aes_256_gcm_randnonce(key.as_slice()).map_err(Error::FailedOpen)?;
let decrypted = aead.open(&mut entry, payload).map_err(Error::FailedOpen)?;
let body = EntryBody::read_from(decrypted).unwrap();
@@ -143,8 +154,8 @@
let salt = rand::random_array().map_err(Error::FailedSaltGeneration)?;
let body = EntryBody::new(dice_inputs, &salt);
- let key = key.map_err(Error::FailedSeal)?;
- let aead = AeadCtx::new_aes_256_gcm_randnonce(&key).map_err(Error::FailedSeal)?;
+ let aead =
+ AeadCtx::new_aes_256_gcm_randnonce(key.as_slice()).map_err(Error::FailedSeal)?;
// We currently only support single-blk entries.
let plaintext = body.as_bytes();
assert!(plaintext.len() + aead.aead().unwrap().max_overhead() < blk.len());
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.rs
similarity index 97%
rename from rialto/src/requests/mod.rs
rename to rialto/src/requests.rs
index 8162237..d9e6f37 100644
--- a/rialto/src/requests/mod.rs
+++ b/rialto/src/requests.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
diff --git a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
index 2500f3b..40c5cae 100644
--- a/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
+++ b/tests/testapk/src/java/com/android/microdroid/test/MicrodroidTests.java
@@ -1550,7 +1550,7 @@
@CddTest(requirements = {"9.17/C-1-1"})
public void payloadIsNotRoot() throws Exception {
assumeSupportedDevice();
- assumeFeatureEnabled(VirtualMachineManager.FEATURE_PAYLOAD_NOT_ROOT);
+ assumeFeatureEnabled(VirtualMachineManager.FEATURE_MULTI_TENANT);
VirtualMachineConfig config =
newVmConfigBuilder()
diff --git a/virtualizationmanager/src/aidl.rs b/virtualizationmanager/src/aidl.rs
index 8456888..684aa64 100644
--- a/virtualizationmanager/src/aidl.rs
+++ b/virtualizationmanager/src/aidl.rs
@@ -34,7 +34,7 @@
IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
IVirtualMachineCallback::IVirtualMachineCallback,
IVirtualizationService::IVirtualizationService,
- IVirtualizationService::FEATURE_PAYLOAD_NON_ROOT,
+ IVirtualizationService::FEATURE_MULTI_TENANT,
IVirtualizationService::FEATURE_VENDOR_MODULES,
IVirtualizationService::FEATURE_DICE_CHANGES,
MemoryTrimLevel::MemoryTrimLevel,
@@ -276,7 +276,7 @@
// TODO(b/298012279): make this scalable.
match feature {
FEATURE_DICE_CHANGES => Ok(cfg!(dice_changes)),
- FEATURE_PAYLOAD_NON_ROOT => Ok(cfg!(payload_not_root)),
+ FEATURE_MULTI_TENANT => Ok(cfg!(multi_tenant)),
FEATURE_VENDOR_MODULES => Ok(cfg!(vendor_modules)),
_ => {
warn!("unknown feature {feature}");
diff --git a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
index 9255e1c..d6a1299 100644
--- a/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
+++ b/virtualizationservice/aidl/android/system/virtualizationservice/IVirtualizationService.aidl
@@ -23,7 +23,7 @@
interface IVirtualizationService {
const String FEATURE_DICE_CHANGES = "com.android.kvm.DICE_CHANGES";
- const String FEATURE_PAYLOAD_NON_ROOT = "com.android.kvm.PAYLOAD_NON_ROOT";
+ const String FEATURE_MULTI_TENANT = "com.android.kvm.MULTI_TENANT";
const String FEATURE_VENDOR_MODULES = "com.android.kvm.VENDOR_MODULES";
/**
diff --git a/vmbase/src/layout/mod.rs b/vmbase/src/layout.rs
similarity index 100%
rename from vmbase/src/layout/mod.rs
rename to vmbase/src/layout.rs
diff --git a/vmbase/src/memory/mod.rs b/vmbase/src/memory.rs
similarity index 100%
rename from vmbase/src/memory/mod.rs
rename to vmbase/src/memory.rs
diff --git a/vmbase/src/virtio/mod.rs b/vmbase/src/virtio.rs
similarity index 100%
rename from vmbase/src/virtio/mod.rs
rename to vmbase/src/virtio.rs