Merge changes from topic "b/302677468" into main
* changes:
Allow execution of code in extra APKs
Multi_tenant is the new payload_not_root
diff --git a/libs/bssl/Android.bp b/libs/bssl/Android.bp
index 949c2c4..0a2f334 100644
--- a/libs/bssl/Android.bp
+++ b/libs/bssl/Android.bp
@@ -32,7 +32,7 @@
rust_defaults {
name: "libbssl_avf_test_defaults",
crate_name: "bssl_avf_test",
- srcs: ["tests/*.rs"],
+ srcs: ["tests/tests.rs"],
test_suites: ["general-tests"],
static_libs: [
"libcrypto_baremetal",
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
index 1f9751f..547ad43 100644
--- a/libs/bssl/error/src/lib.rs
+++ b/libs/bssl/error/src/lib.rs
@@ -16,9 +16,13 @@
#![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>;
@@ -26,7 +30,7 @@
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Error {
/// Failed to invoke a BoringSSL API.
- CallFailed(ApiName),
+ CallFailed(ApiName, ReasonCode),
/// An unexpected internal error occurred.
InternalError,
@@ -35,8 +39,8 @@
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::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"),
}
@@ -59,5 +63,6 @@
EC_KEY_marshal_private_key,
EC_KEY_new_by_curve_name,
EC_POINT_get_affine_coordinates,
+ HKDF,
HMAC,
}
diff --git a/libs/bssl/src/digest.rs b/libs/bssl/src/digest.rs
index 47e4aba..49e66e6 100644
--- a/libs/bssl/src/digest.rs
+++ b/libs/bssl/src/digest.rs
@@ -32,7 +32,6 @@
}
/// 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.
diff --git a/libs/bssl/src/ec_key.rs b/libs/bssl/src/ec_key.rs
index 901212f..7038e21 100644
--- a/libs/bssl/src/ec_key.rs
+++ b/libs/bssl/src/ec_key.rs
@@ -16,7 +16,7 @@
//! BoringSSL.
use crate::cbb::CbbFixed;
-use crate::util::check_int_result;
+use crate::util::{check_int_result, to_call_failed_error};
use alloc::vec::Vec;
use bssl_avf_error::{ApiName, Error, Result};
use bssl_ffi::{
@@ -54,7 +54,7 @@
};
let mut ec_key = NonNull::new(ec_key)
.map(Self)
- .ok_or(Error::CallFailed(ApiName::EC_KEY_new_by_curve_name))?;
+ .ok_or(to_call_failed_error(ApiName::EC_KEY_new_by_curve_name))?;
ec_key.generate_key()?;
Ok(ec_key)
}
@@ -104,7 +104,7 @@
// `EC_KEY` pointer.
unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) };
if ec_point.is_null() {
- Err(Error::CallFailed(ApiName::EC_KEY_get0_public_key))
+ Err(to_call_failed_error(ApiName::EC_KEY_get0_public_key))
} else {
Ok(ec_point)
}
@@ -118,7 +118,7 @@
// `EC_KEY` pointer.
unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
if group.is_null() {
- Err(Error::CallFailed(ApiName::EC_KEY_get0_group))
+ Err(to_call_failed_error(ApiName::EC_KEY_get0_group))
} else {
Ok(group)
}
@@ -144,7 +144,7 @@
// SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
// and it has been flushed, thus it has no active children.
let len = unsafe { CBB_len(cbb.as_ref()) };
- Ok(buf.get(0..len).ok_or(Error::CallFailed(ApiName::CBB_len))?.to_vec().into())
+ Ok(buf.get(0..len).ok_or(to_call_failed_error(ApiName::CBB_len))?.to_vec().into())
}
}
@@ -178,7 +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(Error::CallFailed(ApiName::BN_new))
+ NonNull::new(bn).map(Self).ok_or(to_call_failed_error(ApiName::BN_new))
}
fn as_mut_ptr(&mut self) -> *mut BIGNUM {
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..5dc6876
--- /dev/null
+++ b/libs/bssl/src/hkdf.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 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;
+
+/// 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<[u8; N]> {
+ let mut key = [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
index 1e09315..ddbbe4a 100644
--- a/libs/bssl/src/hmac.rs
+++ b/libs/bssl/src/hmac.rs
@@ -15,7 +15,8 @@
//! Wrappers of the HMAC functions in BoringSSL hmac.h.
use crate::digest::Digester;
-use bssl_avf_error::{ApiName, Error, Result};
+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;
@@ -53,6 +54,6 @@
if !ret.is_null() && out_len == (out.len() as u32) {
Ok(out)
} else {
- Err(Error::CallFailed(ApiName::HMAC))
+ Err(to_call_failed_error(ApiName::HMAC))
}
}
diff --git a/libs/bssl/src/lib.rs b/libs/bssl/src/lib.rs
index 1824080..8b38f5b 100644
--- a/libs/bssl/src/lib.rs
+++ b/libs/bssl/src/lib.rs
@@ -21,10 +21,15 @@
mod cbb;
mod digest;
mod ec_key;
+mod err;
+mod hkdf;
mod hmac;
mod util;
-pub use bssl_avf_error::{ApiName, Error, Result};
+pub use bssl_avf_error::{ApiName, CipherError, Error, ReasonCode, Result};
+
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
index cb5e368..880c85b 100644
--- a/libs/bssl/src/util.rs
+++ b/libs/bssl/src/util.rs
@@ -14,13 +14,14 @@
//! 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)),
+ 0 => Err(Error::CallFailed(api_name, get_error_reason_code())),
_ => {
error!(
"Received a return value ({}) other than 0 or 1 from the BoringSSL API: {:?}",
@@ -30,3 +31,7 @@
}
}
}
+
+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/api_test.rs b/libs/bssl/tests/api_test.rs
deleted file mode 100644
index 25aaf04..0000000
--- a/libs/bssl/tests/api_test.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2023, The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-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/bssl/tests/hkdf_test.rs b/libs/bssl/tests/hkdf_test.rs
new file mode 100644
index 0000000..1cda042
--- /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())?);
+ 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())?);
+ 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())?);
+ 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/libs/bssl/tests/tests.rs b/libs/bssl/tests/tests.rs
new file mode 100644
index 0000000..1077787
--- /dev/null
+++ b/libs/bssl/tests/tests.rs
@@ -0,0 +1,18 @@
+// 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.
+
+//! API tests of the crate `bssl_avf`.
+
+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/microdroid/Android.bp b/microdroid/Android.bp
index bac93a4..b494cfa 100644
--- a/microdroid/Android.bp
+++ b/microdroid/Android.bp
@@ -418,6 +418,7 @@
],
properties: [
"rollback_index",
+ "props",
],
}
@@ -447,6 +448,12 @@
soong_config_variables: {
release_avf_enable_llpvm_changes: {
rollback_index: 1,
+ props: [
+ {
+ name: "com.android.virt.cap",
+ value: "secretkeeper_protection",
+ },
+ ],
},
},
}
@@ -487,6 +494,12 @@
soong_config_variables: {
release_avf_enable_llpvm_changes: {
rollback_index: 1,
+ props: [
+ {
+ name: "com.android.virt.cap",
+ value: "secretkeeper_protection",
+ },
+ ],
},
},
}
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/Android.bp b/pvmfw/avb/Android.bp
index 73d188b..6df1c4d 100644
--- a/pvmfw/avb/Android.bp
+++ b/pvmfw/avb/Android.bp
@@ -42,6 +42,8 @@
":test_image_with_unknown_vm_type_prop",
":test_image_with_multiple_props",
":test_image_with_duplicated_capability",
+ ":test_image_with_rollback_index_5",
+ ":test_image_with_multiple_capabilities",
":unsigned_test_image",
],
prefer_rlib: true,
@@ -194,3 +196,26 @@
private_key: ":pvmfw_sign_key",
salt: "1111",
}
+
+avb_add_hash_footer {
+ name: "test_image_with_rollback_index_5",
+ src: ":unsigned_test_image",
+ partition_name: "boot",
+ private_key: ":pvmfw_sign_key",
+ salt: "1211",
+ rollback_index: 5,
+}
+
+avb_add_hash_footer {
+ name: "test_image_with_multiple_capabilities",
+ src: ":unsigned_test_image",
+ partition_name: "boot",
+ private_key: ":pvmfw_sign_key",
+ salt: "2134",
+ props: [
+ {
+ name: "com.android.virt.cap",
+ value: "remote_attest|secretkeeper_protection",
+ },
+ ],
+}
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/avb/src/ops.rs b/pvmfw/avb/src/ops.rs
index 539291b..c7b8b01 100644
--- a/pvmfw/avb/src/ops.rs
+++ b/pvmfw/avb/src/ops.rs
@@ -229,10 +229,14 @@
_rollback_index_location: usize,
out_rollback_index: *mut u64,
) -> AvbIOResult {
- // Rollback protection is not yet implemented, but this method is required by
- // `avb_slot_verify()`.
- // We set `out_rollback_index` to 0 to ensure that the default rollback index (0)
- // is never smaller than it, thus the rollback index check will pass.
+ // This method is used by `avb_slot_verify()` to read the stored_rollback_index at
+ // rollback_index_location.
+
+ // TODO(291213394) : Refine this comment once capability for rollback protection is defined.
+ // pvmfw does not compare stored_rollback_index with rollback_index for Antirollback protection
+ // Hence, we set `out_rollback_index` to 0 to ensure that the
+ // rollback_index (including default: 0) is never smaller than it,
+ // thus the rollback index check will pass.
result_to_io_enum(write(out_rollback_index, 0))
}
@@ -334,4 +338,8 @@
unsafe { slice::from_raw_parts(data.loaded_partitions, data.num_loaded_partitions) };
Ok(loaded_partitions)
}
+
+ pub(crate) fn rollback_indexes(&self) -> &[u64] {
+ &self.as_ref().rollback_indexes
+ }
}
diff --git a/pvmfw/avb/src/verify.rs b/pvmfw/avb/src/verify.rs
index ac945e2..492d387 100644
--- a/pvmfw/avb/src/verify.rs
+++ b/pvmfw/avb/src/verify.rs
@@ -23,6 +23,9 @@
use avb_bindgen::{AvbPartitionData, AvbVBMetaData};
use core::ffi::c_char;
+// We use this for the rollback_index field if AvbSlotVerifyDataWrap has empty rollback_indexes
+const DEFAULT_ROLLBACK_INDEX: u64 = 0;
+
/// Verified data returned when the payload verification succeeds.
#[derive(Debug, PartialEq, Eq)]
pub struct VerifiedBootData<'a> {
@@ -36,6 +39,15 @@
pub public_key: &'a [u8],
/// VM capabilities.
pub capabilities: Vec<Capability>,
+ /// Rollback index of kernel.
+ pub rollback_index: u64,
+}
+
+impl VerifiedBootData<'_> {
+ /// Returns whether the kernel have the given capability
+ pub fn has_capability(&self, cap: Capability) -> bool {
+ self.capabilities.contains(&cap)
+ }
}
/// This enum corresponds to the `DebugLevel` in `VirtualMachineConfig`.
@@ -48,15 +60,18 @@
}
/// VM Capability.
-#[derive(Debug, PartialEq, Eq)]
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Capability {
/// Remote attestation.
RemoteAttest,
+ /// Secretkeeper protected secrets.
+ SecretkeeperProtection,
}
impl Capability {
const KEY: &[u8] = b"com.android.virt.cap";
const REMOTE_ATTEST: &[u8] = b"remote_attest";
+ const SECRETKEEPER_PROTECTION: &[u8] = b"secretkeeper_protection";
const SEPARATOR: u8 = b'|';
fn get_capabilities(property_value: &[u8]) -> Result<Vec<Self>, PvmfwVerifyError> {
@@ -65,6 +80,7 @@
for v in property_value.split(|b| *b == Self::SEPARATOR) {
let cap = match v {
Self::REMOTE_ATTEST => Self::RemoteAttest,
+ Self::SECRETKEEPER_PROTECTION => Self::SecretkeeperProtection,
_ => return Err(PvmfwVerifyError::UnknownVbmetaProperty),
};
if res.contains(&cap) {
@@ -153,6 +169,10 @@
let kernel_verify_result = ops.verify_partition(PartitionName::Kernel.as_cstr())?;
let vbmeta_images = kernel_verify_result.vbmeta_images()?;
+ // TODO(b/302093437): Use explicit rollback_index_location instead of default
+ // location (first element).
+ let rollback_index =
+ *kernel_verify_result.rollback_indexes().first().unwrap_or(&DEFAULT_ROLLBACK_INDEX);
verify_only_one_vbmeta_exists(vbmeta_images)?;
let vbmeta_image = vbmeta_images[0];
verify_vbmeta_is_from_kernel_partition(&vbmeta_image)?;
@@ -171,6 +191,7 @@
initrd_digest: None,
public_key: trusted_public_key,
capabilities,
+ rollback_index,
});
}
@@ -196,5 +217,6 @@
initrd_digest: Some(*initrd_descriptor.digest),
public_key: trusted_public_key,
capabilities,
+ rollback_index,
})
}
diff --git a/pvmfw/avb/tests/api_test.rs b/pvmfw/avb/tests/api_test.rs
index e7e4dcc..6344433 100644
--- a/pvmfw/avb/tests/api_test.rs
+++ b/pvmfw/avb/tests/api_test.rs
@@ -23,6 +23,7 @@
use utils::*;
const TEST_IMG_WITH_ONE_HASHDESC_PATH: &str = "test_image_with_one_hashdesc.img";
+const TEST_IMG_WITH_ROLLBACK_INDEX_5: &str = "test_image_with_rollback_index_5.img";
const TEST_IMG_WITH_PROP_DESC_PATH: &str = "test_image_with_prop_desc.img";
const TEST_IMG_WITH_SERVICE_VM_PROP_PATH: &str = "test_image_with_service_vm_prop.img";
const TEST_IMG_WITH_UNKNOWN_VM_TYPE_PROP_PATH: &str = "test_image_with_unknown_vm_type_prop.img";
@@ -31,6 +32,7 @@
const TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH: &str = "test_image_with_non_initrd_hashdesc.img";
const TEST_IMG_WITH_INITRD_AND_NON_INITRD_DESC_PATH: &str =
"test_image_with_initrd_and_non_initrd_desc.img";
+const TEST_IMG_WITH_MULTIPLE_CAPABILITIES: &str = "test_image_with_multiple_capabilities.img";
const UNSIGNED_TEST_IMG_PATH: &str = "unsigned_test.img";
const RANDOM_FOOTER_POS: usize = 30;
@@ -60,7 +62,7 @@
let public_key = load_trusted_public_key()?;
let verified_boot_data = verify_payload(
&fs::read(TEST_IMG_WITH_ONE_HASHDESC_PATH)?,
- /*initrd=*/ None,
+ /* initrd= */ None,
&public_key,
)
.map_err(|e| anyhow!("Verification failed. Error: {}", e))?;
@@ -72,6 +74,7 @@
initrd_digest: None,
public_key: &public_key,
capabilities: vec![],
+ rollback_index: 0,
};
assert_eq!(expected_boot_data, verified_boot_data);
@@ -82,7 +85,7 @@
fn payload_with_non_initrd_descriptor_fails_verification_with_no_initrd() -> Result<()> {
assert_payload_verification_fails(
&fs::read(TEST_IMG_WITH_NON_INITRD_HASHDESC_PATH)?,
- /*initrd=*/ None,
+ /* initrd= */ None,
&load_trusted_public_key()?,
PvmfwVerifyError::InvalidDescriptors(avb::IoError::NoSuchPartition),
)
@@ -103,7 +106,7 @@
let public_key = load_trusted_public_key()?;
let verified_boot_data = verify_payload(
&fs::read(TEST_IMG_WITH_SERVICE_VM_PROP_PATH)?,
- /*initrd=*/ None,
+ /* initrd= */ None,
&public_key,
)
.map_err(|e| anyhow!("Verification failed. Error: {}", e))?;
@@ -115,6 +118,7 @@
initrd_digest: None,
public_key: &public_key,
capabilities: vec![Capability::RemoteAttest],
+ rollback_index: 0,
};
assert_eq!(expected_boot_data, verified_boot_data);
@@ -125,7 +129,7 @@
fn payload_with_unknown_vm_type_fails_verification_with_no_initrd() -> Result<()> {
assert_payload_verification_fails(
&fs::read(TEST_IMG_WITH_UNKNOWN_VM_TYPE_PROP_PATH)?,
- /*initrd=*/ None,
+ /* initrd= */ None,
&load_trusted_public_key()?,
PvmfwVerifyError::UnknownVbmetaProperty,
)
@@ -135,7 +139,7 @@
fn payload_with_multiple_props_fails_verification_with_no_initrd() -> Result<()> {
assert_payload_verification_fails(
&fs::read(TEST_IMG_WITH_MULTIPLE_PROPS_PATH)?,
- /*initrd=*/ None,
+ /* initrd= */ None,
&load_trusted_public_key()?,
PvmfwVerifyError::InvalidDescriptors(avb::IoError::Io),
)
@@ -145,7 +149,7 @@
fn payload_with_duplicated_capability_fails_verification_with_no_initrd() -> Result<()> {
assert_payload_verification_fails(
&fs::read(TEST_IMG_WITH_DUPLICATED_CAP_PATH)?,
- /*initrd=*/ None,
+ /* initrd= */ None,
&load_trusted_public_key()?,
avb::SlotVerifyError::InvalidMetadata.into(),
)
@@ -155,7 +159,7 @@
fn payload_with_prop_descriptor_fails_verification_with_no_initrd() -> Result<()> {
assert_payload_verification_fails(
&fs::read(TEST_IMG_WITH_PROP_DESC_PATH)?,
- /*initrd=*/ None,
+ /* initrd= */ None,
&load_trusted_public_key()?,
PvmfwVerifyError::UnknownVbmetaProperty,
)
@@ -165,7 +169,7 @@
fn payload_expecting_initrd_fails_verification_with_no_initrd() -> Result<()> {
assert_payload_verification_fails(
&load_latest_signed_kernel()?,
- /*initrd=*/ None,
+ /* initrd= */ None,
&load_trusted_public_key()?,
avb::SlotVerifyError::InvalidMetadata.into(),
)
@@ -176,7 +180,7 @@
assert_payload_verification_with_initrd_fails(
&load_latest_signed_kernel()?,
&load_latest_initrd_normal()?,
- /*trusted_public_key=*/ &[0u8; 0],
+ /* trusted_public_key= */ &[0u8; 0],
avb::SlotVerifyError::PublicKeyRejected.into(),
)
}
@@ -186,7 +190,7 @@
assert_payload_verification_with_initrd_fails(
&load_latest_signed_kernel()?,
&load_latest_initrd_normal()?,
- /*trusted_public_key=*/ &[0u8; 512],
+ /* trusted_public_key= */ &[0u8; 512],
avb::SlotVerifyError::PublicKeyRejected.into(),
)
}
@@ -205,7 +209,7 @@
fn payload_with_an_invalid_initrd_fails_verification() -> Result<()> {
assert_payload_verification_with_initrd_fails(
&load_latest_signed_kernel()?,
- /*initrd=*/ &fs::read(UNSIGNED_TEST_IMG_PATH)?,
+ /* initrd= */ &fs::read(UNSIGNED_TEST_IMG_PATH)?,
&load_trusted_public_key()?,
avb::SlotVerifyError::Verification.into(),
)
@@ -383,3 +387,41 @@
avb::SlotVerifyError::Verification.into(),
)
}
+
+#[test]
+fn payload_with_rollback_index() -> Result<()> {
+ let public_key = load_trusted_public_key()?;
+ let verified_boot_data = verify_payload(
+ &fs::read(TEST_IMG_WITH_ROLLBACK_INDEX_5)?,
+ /* initrd= */ None,
+ &public_key,
+ )
+ .map_err(|e| anyhow!("Verification failed. Error: {}", e))?;
+
+ let kernel_digest = hash(&[&hex::decode("1211")?, &fs::read(UNSIGNED_TEST_IMG_PATH)?]);
+ let expected_boot_data = VerifiedBootData {
+ debug_level: DebugLevel::None,
+ kernel_digest,
+ initrd_digest: None,
+ public_key: &public_key,
+ capabilities: vec![],
+ rollback_index: 5,
+ };
+ assert_eq!(expected_boot_data, verified_boot_data);
+ Ok(())
+}
+
+#[test]
+fn payload_with_multiple_capabilities() -> Result<()> {
+ let public_key = load_trusted_public_key()?;
+ let verified_boot_data = verify_payload(
+ &fs::read(TEST_IMG_WITH_MULTIPLE_CAPABILITIES)?,
+ /* initrd= */ None,
+ &public_key,
+ )
+ .map_err(|e| anyhow!("Verification failed. Error: {}", e))?;
+
+ assert!(verified_boot_data.has_capability(Capability::RemoteAttest));
+ assert!(verified_boot_data.has_capability(Capability::SecretkeeperProtection));
+ Ok(())
+}
diff --git a/pvmfw/avb/tests/utils.rs b/pvmfw/avb/tests/utils.rs
index 86d2398..70eba5f 100644
--- a/pvmfw/avb/tests/utils.rs
+++ b/pvmfw/avb/tests/utils.rs
@@ -117,6 +117,7 @@
initrd_digest,
public_key: &public_key,
capabilities: vec![],
+ rollback_index: if cfg!(llpvm_changes) { 1 } else { 0 },
};
assert_eq!(expected_boot_data, verified_boot_data);
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/dice.rs b/pvmfw/src/dice.rs
index 9542429..cc31f34 100644
--- a/pvmfw/src/dice.rs
+++ b/pvmfw/src/dice.rs
@@ -45,6 +45,7 @@
pub code_hash: Hash,
pub auth_hash: Hash,
pub mode: DiceMode,
+ pub security_version: u64,
}
impl PartialInputs {
@@ -52,8 +53,10 @@
let code_hash = to_dice_hash(data)?;
let auth_hash = hash(data.public_key)?;
let mode = to_dice_mode(data.debug_level);
+ // We use rollback_index from vbmeta as the security_version field in dice certificate.
+ let security_version = data.rollback_index;
- Ok(Self { code_hash, auth_hash, mode })
+ Ok(Self { code_hash, auth_hash, mode, security_version })
}
pub fn write_next_bcc(
@@ -63,8 +66,12 @@
next_bcc: &mut [u8],
) -> diced_open_dice::Result<()> {
let mut config_descriptor_buffer = [0; 128];
- let config_values =
- DiceConfigValues { component_name: Some(cstr!("vm_entry")), ..Default::default() };
+ let config_values = DiceConfigValues {
+ component_name: Some(cstr!("vm_entry")),
+ security_version: if cfg!(llpvm_changes) { Some(self.security_version) } else { None },
+ ..Default::default()
+ };
+
let config_descriptor_size =
bcc_format_config_descriptor(&config_values, &mut config_descriptor_buffer)?;
let config = &config_descriptor_buffer[..config_descriptor_size];
diff --git a/pvmfw/src/instance.rs b/pvmfw/src/instance.rs
index f2b34da..75bc3d3 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,7 +135,6 @@
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 decrypted = aead.open(&mut entry, payload).map_err(Error::FailedOpen)?;
@@ -143,7 +153,6 @@
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)?;
// We currently only support single-blk entries.
let plaintext = body.as_bytes();
diff --git a/pvmfw/src/main.rs b/pvmfw/src/main.rs
index d39d51c..b8cbf1b 100644
--- a/pvmfw/src/main.rs
+++ b/pvmfw/src/main.rs
@@ -112,10 +112,22 @@
info!("Please disregard any previous libavb ERROR about initrd_normal.");
}
- if verified_boot_data.capabilities.contains(&Capability::RemoteAttest) {
+ if verified_boot_data.has_capability(Capability::RemoteAttest) {
info!("Service VM capable of remote attestation detected");
}
+ if verified_boot_data.has_capability(Capability::SecretkeeperProtection) {
+ info!("Guest OS is capable of Secretkeeper protection");
+ // For Secretkeeper based Antirollback protection, rollback_index of the image > 0
+ if verified_boot_data.rollback_index == 0 {
+ error!(
+ "Expected positive rollback_index, found {:?}",
+ verified_boot_data.rollback_index
+ );
+ return Err(RebootReason::InvalidPayload);
+ };
+ }
+
let next_bcc = heap::aligned_boxed_slice(NEXT_BCC_SIZE, GUEST_PAGE_SIZE).ok_or_else(|| {
error!("Failed to allocate the next-stage BCC");
RebootReason::InternalError
diff --git a/rialto/src/requests/mod.rs b/rialto/src/requests.rs
similarity index 100%
rename from rialto/src/requests/mod.rs
rename to rialto/src/requests.rs
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