rust/pv: Fix styling issues

Signed-off-by: Marc Hartmayer <mhartmay@linux.ibm.com>
Signed-off-by: Steffen Eiden <seiden@linux.ibm.com>
This commit is contained in:
Steffen Eiden
2024-05-21 18:12:05 +02:00
parent a9d4b1e1b9
commit f383278a5a
12 changed files with 75 additions and 69 deletions

View File

@@ -18,7 +18,7 @@ use zerocopy::{AsBytes, BigEndian, FromBytes, FromZeroes, U32, U64};
/// Page List Digest (pld)
/// Address List Digest (ald)
/// Tweak List Digest (tld)
/// SE Header Tag (tag)
/// SE-Header Tag (tag)
#[repr(C)]
#[derive(Debug, Clone, Copy, AsBytes, PartialEq, Eq, FromBytes, FromZeroes)]
pub struct BootHdrTags {
@@ -52,7 +52,7 @@ impl MagicValue<8> for BootHdrMagic {
}
impl BootHdrTags {
/// Returns a reference to the SE-hdr tag of this [`BootHdrTags`].
/// Returns a reference to the SE-header tag of this [`BootHdrTags`].
pub fn tag(&self) -> &[u8; 16] {
&self.tag
}
@@ -63,7 +63,7 @@ impl BootHdrTags {
Self { ald, tld, pld, tag }
}
/// Returns `false` if no hdr found, `true` otherwise.
/// Returns `false` if no SE-header found, `true` otherwise.
/// In the very unlikely case an IO error can appear
/// when seeking to the beginning of the header.
fn seek_se_hdr_start<R>(img: &mut R) -> Result<bool>

View File

@@ -19,7 +19,6 @@ use openssl::{
use std::{convert::TryInto, ops::Range};
/// An AES256-key that will purge itself out of the memory when going out of scope
///
pub type Aes256Key = Confidential<[u8; 32]>;
pub(crate) const AES_256_GCM_TAG_SIZE: usize = 16;
@@ -29,7 +28,6 @@ pub(crate) const SHA_256_HASH_SIZE: u32 = 32;
pub(crate) type Sha256Hash = [u8; SHA_256_HASH_SIZE as usize];
/// Types of symmetric keys, to specify during construction.
///
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymKeyType {
@@ -38,7 +36,6 @@ pub enum SymKeyType {
}
/// Types of symmetric keys
///
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SymKey {
@@ -464,9 +461,8 @@ mod tests {
#[test]
fn hmac_sha512_rfc_4868() {
/* use a test vector with key=64bytes of RFC 4868:
* https://www.rfc-editor.org/rfc/rfc4868.html#section-2.7.2.3
*/
// use a test vector with key=64bytes of RFC 4868:
// https://www.rfc-editor.org/rfc/rfc4868.html#section-2.7.2.3
let key = [0xb; 64];
let data = [0x48, 0x69, 0x20, 0x54, 0x68, 0x65, 0x72, 0x65];

View File

@@ -43,7 +43,7 @@ pub enum Error {
#[error("Provided binary request is too small")]
BinRequestSmall,
#[error("No Config UID found: {0}")]
#[error("No Configuration UID found: {0}")]
NoCuid(String),
// errors from request types
@@ -118,12 +118,11 @@ pub enum Error {
// used in macros
#[doc(hidden)]
impl Error {
pub const CRL: &'static str = "CRL";
pub const CERT: &'static str = "certificate";
pub const CRL: &'static str = "CRL";
}
/// Error cases for verifying host-key documents
///
#[allow(missing_docs)]
#[derive(thiserror::Error, Debug, PartialEq, Eq)]
#[non_exhaustive]

View File

@@ -89,7 +89,9 @@ impl Keyslot {
impl Encrypt for Keyslot {
/// Encrypts the given request protection key `prot_key`.
///
/// The AES256 encryption key is derived from `self` as public key, and `priv_key` as private key.
/// The AES256 encryption key is derived from `self` as public key, and `priv_key` as private
/// key.
///
/// # Returns
/// The encrypted Keyslot.
///
@@ -151,7 +153,7 @@ impl ReqEncrCtx {
prot_key,
})
}
///
/// Create a new encryption context with random input values.
///
/// # Errors
@@ -204,7 +206,7 @@ impl ReqEncrCtx {
}?;
let mut auth_data: Vec<u8> = Vec::with_capacity(2048);
//reserve space for the request header
// reserve space for the request header
auth_data.resize(std::mem::size_of::<RequestHdr>(), 0);
for a in aad {
@@ -231,7 +233,7 @@ impl ReqEncrCtx {
Ok(auth_data)
}
/// get the public coordinates from the private key (Customer private key)
/// Get the public coordinates from the private key (Customer private key)
/// # Errors
///
/// This function will return an error if the public key could not be extracted by OpenSSL.
@@ -240,7 +242,7 @@ impl ReqEncrCtx {
self.priv_key.as_ref().try_into().map_err(Error::Crypto)
}
/// Encrypt confidential Data with this encryption context and provide a gcm tag.
/// Encrypt confidential Data with this encryption context and provide a GCM tag.
///
/// * `aad` - additional authentic data
/// * `conf` - data to be encrypted
@@ -273,8 +275,8 @@ impl AsRef<[u8]> for EcdhPubkeyCoord {
}
}
/// Get the pub ecdh coordinates in the format the Ultravisor expects it:
/// The two coordinates are pdadded to 80 bytes each.
/// Get the pub ECDH coordinates in the format the Ultravisor expects it:
/// The two coordinates are padded to 80 bytes each.
fn get_pub_ecdh_points(pkey: &EcPointRef, grp: &EcGroupRef) -> Result<[u8; 160], ErrorStack> {
const ECDH_PUB_KEY_COORD_POINT_SIZE: i32 = 0x50;
let mut x = BigNum::new()?;
@@ -290,6 +292,7 @@ macro_rules! ecdh_from {
($type: ty) => {
impl TryFrom<&PKeyRef<$type>> for EcdhPubkeyCoord {
type Error = ErrorStack;
fn try_from(key: &PKeyRef<$type>) -> Result<Self, Self::Error> {
let k = key.ec_key()?;
k.check_key()?;
@@ -348,9 +351,9 @@ impl RequestHdr {
/// `ReqEncrCtx` when implementing `encrypt`. A hostkey should be represented by [`Keyslot`] during
/// encryption.
///
/// An UV request consists of an authenticated area (AAD), an encrypted area (Encr) and a 16 byte tag.
/// The AAD contains a general header and Request type defined data (including Keyslots).
/// It is encrypted with an Request protection key (symmetric). This key is encrypted with a
/// An UV request consists of an authenticated area (AAD), an encrypted area (Encr) and a 16 byte
/// tag. The AAD contains a general header and Request type defined data (including Keyslots). It
/// is encrypted with an Request protection key (symmetric). This key is encrypted with a
/// (generated) private key and the public key of the host system (Host key)
/// ```none
/// _______________________________________________________________
@@ -364,7 +367,7 @@ impl RequestHdr {
/// | ---------------------------------------------------- |
/// | AES GCM Tag (16) |
/// |_____________________________________________________________|
///```
/// ```
pub trait Request {
/// Encrypt the request into its binary format
///
@@ -451,7 +454,7 @@ impl<'a> BinReqValues<'a> {
/// Returns a reference to the request dependent authenticated area of this [`BinReqValues`]
/// already interpreted.
///
/// If target struct is larger than the request dependend-aad None is returned. See
/// If target struct is larger than the request depended-AAD None is returned. See
/// [`FromBytes::ref_from_prefix`]
pub fn req_dep_aad<T>(&self) -> Option<&T>
where
@@ -489,15 +492,15 @@ mod tests {
.unwrap();
let mut aad_exp = vec![
0x12, 0x34, 0x56, 0x89, 0xab, 0xcd, 0xef, 0, //progr
0x12, 0x34, 0x56, 0x89, 0xab, 0xcd, 0xef, 0, // progr
0, 0, 2, 0, // vers
0, 0, 0, 168, //size
0, 0, 0, 168, // size
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, // iv
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //res
1, //nks
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // res
1, // nks
0, 0, 0, 0, // res
0, 0, 0, 16, // sea
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, //aad
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, // aad
];
aad_exp.extend_from_slice(get_test_asset!("exp/keyslot.bin"));
assert_eq!(&aad, &aad_exp);
@@ -548,12 +551,12 @@ mod tests {
let hdr = RequestHdr::new(0x200, 22, [0x11; 12], 15, 44, None);
let hdr_bin = hdr.as_bytes();
let hdr_bin_exp = [
0u8, 0, 0, 0, 0, 0, 0, 0, //magic
0u8, 0, 0, 0, 0, 0, 0, 0, // magic
0, 0, 2, 0, // vers
0, 0, 0, 22, //size
0, 0, 0, 22, // size
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, // iv
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //res
15, //nks
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // res
15, // nks
0, 0, 0, 0, // res
0, 0, 0, 44, // sea
];
@@ -565,12 +568,12 @@ mod tests {
let mut hdr = RequestHdr::new(0x200, 0x1234, [0x11; 12], 15, 44, Some(TEST_MAGIC));
let hdr_bin = hdr.as_bytes_mut();
let hdr_bin_exp = [
0x12, 0x34, 0x56, 0x89, 0xab, 0xcd, 0xef, 0, //magic
0x12, 0x34, 0x56, 0x89, 0xab, 0xcd, 0xef, 0, // magic
0, 0, 2, 0, // vers
0, 0, 0x12, 0x34, //size
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, // iv
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //res
15, //nks
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // res
15, // nks
0, 0, 0, 0, // res
0, 0, 0, 44, // sea
];

View File

@@ -116,7 +116,7 @@ impl UserData {
///
/// Verifies that the provided data + signature fits into 512 bytes
///
/// #Error
/// # Error
/// An error is reported if the provided data and the signature would not fit into 512 bytes
/// An error is reported if the key is not of type RSA (2048|3072) or EC(specp521r1)
pub(super) fn new(sign_key: Option<PKey<Private>>, data: Vec<u8>) -> Result<Self> {
@@ -245,7 +245,7 @@ fn check_key_format(kind: UserDataType, key: &PKeyRef<Public>) -> Result<()> {
///
/// Extracrted user-data if available
///
/// #Errors
/// # Errors
///
/// returns an error if
/// - No sound add-secret request presented
@@ -316,6 +316,7 @@ impl VerifiedUserData {
/// Overwrites the signature in the buf with zeros.
///
/// #Panics
///
/// Panics it provided buffer is smaller that 512 bytes or kind is Null or Unsigned
fn new(buf: &mut [u8], kind: UserDataType) -> Self {
assert!(buf.len() >= 0x200);

View File

@@ -29,14 +29,15 @@ mod test;
pub trait HkdVerifier {
/// Checks if the given host-key document can be trusted.
///
/// #Errors
/// # Errors
///
/// This function will return an error if the Hostkey cannot be trusted.
/// Refer to the concrete Error type for the specific reason.
/// This function will return an error if the host-key document cannot be
/// trusted. Refer to the concrete Error type for the specific reason.
fn verify(&self, hkd: &X509Ref) -> Result<()>;
}
/// A "verifier" that does not verify and accepts all given host-keys as valid.
/// A verifier that does not verify and accepts all given host-keys as valid.
#[derive(Debug)]
pub struct NoVerifyHkd;
impl HkdVerifier for NoVerifyHkd {
fn verify(&self, _hkd: &X509Ref) -> Result<()> {
@@ -44,7 +45,7 @@ impl HkdVerifier for NoVerifyHkd {
}
}
/// A Verifier that checks the host-key document against a chain of trust.
/// A verifier that checks the host-key document against a chain of trust.
pub struct CertVerifier {
store: X509Store,
ibm_z_sign_key: X509,
@@ -68,15 +69,15 @@ impl HkdVerifier for CertVerifier {
fn verify(&self, hkd: &X509Ref) -> Result<()> {
helper::verify_hkd_options(hkd, &self.ibm_z_sign_key)?;
// verify that the hkd was signed with the key of the IBM signing key
// verify that the HKD was signed with the key of the IBM signing key
if !hkd.verify(self.ibm_z_sign_key.public_key()?.as_ref())? {
bail_hkd_verify!(Signature);
}
// Find matching crl for sign key in the store or download them
// Find matching CRL for sign key in the store or download them
let crls = self.hkd_crls(hkd)?;
// Verify that the CLRs are still valid
// Verify that the CRLs are still valid
let mut verified_crls = Vec::with_capacity(crls.len());
for crl in &crls {
if helper::verify_crl(crl, &self.ibm_z_sign_key).is_some() {
@@ -84,7 +85,7 @@ impl HkdVerifier for CertVerifier {
}
}
// Test if hkd was revoked (min1 required)
// Test if HKD was revoked (min1 required)
if verified_crls.is_empty() {
bail_hkd_verify!(NoCrl);
}
@@ -127,7 +128,7 @@ impl CertVerifier {
}
}
// reorder unchanged loaciliy subject
// reorder unchanged locality subject
trace!("quirk_crls: Try Reorder");
if let Ok(ordered_subject) = helper::reorder_x509_names(subject) {
match ctx.crls(&ordered_subject) {
@@ -139,7 +140,7 @@ impl CertVerifier {
Stack::new()
}
///Download the CLRs that a HKD refers to.
/// Download the CRLs that a HKD refers to.
pub fn hkd_crls(&self, hkd: &X509Ref) -> Result<Stack<StackableX509Crl>> {
let mut ctx = X509StoreContext::new()?;
// Unfortunately we cannot use a dedicated function here and have to use a closure (E0434)
@@ -168,6 +169,7 @@ impl CertVerifier {
/// * `root_ca_path` - Path to the root of trust
/// * `offline` - if set to true the verification process will not try to download CRLs from the
/// internet.
///
/// # Errors
///
/// This function will return an error if the chain of trust could not be established.

View File

@@ -33,7 +33,7 @@ const SECURITY_BITS_ARRAY: [u32; 6] = [0, 80, 112, 128, 192, 256];
const SECURITY_BITS: u32 = SECURITY_BITS_ARRAY[SECURITY_LEVEL];
const SECURITY_CHAIN_MAX_LEN: c_int = 2;
/// verifies that the HKD
/// Verifies that the HKD
/// * has enough security bits
/// * is inside its validity period
/// * the Authority Key ID matches the Signing Key ID of the [`sign_key`]
@@ -45,8 +45,8 @@ pub fn verify_hkd_options(hkd: &X509Ref, sign_key: &X509Ref) -> Result<()> {
return Err(Error::HkdVerify(SecurityBits(security_bits, SECURITY_BITS)));
}
// TODO rust-openssl fix X509::not.after/before() impl to return Option& not panic on nullptr from C?
//try_... rust-openssl
// verify that the hkd is still valid
// try_... rust-openssl
// verify that the HKD is still valid
check_validity_period(hkd.not_before(), hkd.not_after())?;
// verify that the AKID of the hkd matches the SKID of the issuer
@@ -303,8 +303,8 @@ pub fn x509_dist_points(cert: &X509Ref) -> Vec<String> {
/// Searches for CRL Distribution points and downloads the CRL. Stops after the first successful
/// download.
///
/// Error if sth bad(=unexpected) happens (not bad: crl not available at link, unexpected format)
/// Other issues are mapped to Ok(None)
/// Error if something bad(=unexpected) happens (not bad: CRL not available at link, unexpected format)
/// Other issues are mapped to Ok(None)
#[cfg(not(test))]
pub fn download_first_crl_from_x509(cert: &X509Ref) -> Result<Option<Vec<openssl::x509::X509Crl>>> {
use crate::utils::read_crls;

View File

@@ -11,7 +11,7 @@ use std::path::Path;
use crate::test_utils::*;
//mock function
// Mock function
pub fn download_first_crl_from_x509(cert: &X509Ref) -> Result<Option<Vec<X509Crl>>> {
fn mock_download<P: AsRef<Path>>(path: P) -> Result<Vec<X509Crl>> {
read_crls(&std::fs::read(path)?)

View File

@@ -39,14 +39,14 @@ pub mod uv {
/// Functionalities to verify UV requests
pub mod request {
/// Version number of the request in system-endian
/// Version number of the request in system endianness
pub type RequestVersion = u32;
/// Request magic value
///
/// The first 8 byte of a request providing an identifier of the request type
/// for programs
pub type RequestMagic = [u8; 8];
/// A `MagicValue` is a bytepattern, that indicates if a byte slice contains the specified
/// A `MagicValue` is a byte pattern, that indicates if a byte slice contains the specified
/// (binary) data.
pub trait MagicValue<const N: usize> {
/// Magic value as byte array

View File

@@ -33,7 +33,7 @@ pub use info::UvDeviceInfo;
/// User data for the attestation UVC
pub type AttestationUserData = [u8; ffi::UVIO_ATT_USER_DATA_LEN];
///Configuration Unique Id of the Secure Execution guest
/// Configuration Unique Id of the Secure Execution guest
pub type ConfigUid = [u8; ffi::UVIO_ATT_UID_LEN];
/// Bitflags as used by the Ultravisor in MSB0 ordering
@@ -61,7 +61,7 @@ fn ioctl_raw(raw_fd: RawFd, cmd: c_ulong, cb: &mut IoctlCb) -> Result<()> {
debug!("ioctl resulted with {cb:?}");
match rc {
0 => Ok(()),
//NOTE io::Error handles all errnos ioctl uses
// NOTE io::Error handles all errnos ioctl uses
_ => Err(std::io::Error::last_os_error().into()),
}
}
@@ -84,24 +84,25 @@ fn rc_fmt<C: UvCmd>(rc: u16, rrc: u16, cmd: &mut C) -> &'static str {
}
/// Ultravisor Command.
///
/// Implementers provide information on the specific Ultravisor command metadata and content.
/// API users do not need to interact directly with any functions provided by this trait and refer
/// to the specialized access and tweaking functionalities of the specivic command.
/// to the specialized access and tweaking functionalities of the specific command.
pub trait UvCmd {
/// The UV IOCTL number of the UV call
const UV_IOCTL_NR: u8;
/// Returns the uvdevice IOCTL command that his command uses.
///
/// # Returns
/// The IOCTL cmd for this UvCmd usually sth like `uv_ioctl!(CMD_NR)`
///
/// The IOCTL cmd for this UvCmd usually something like `uv_ioctl!(CMD_NR)`
fn cmd(&self) -> u64 {
uv_ioctl(Self::UV_IOCTL_NR)
}
/// Converts UV return codes into human readable error messages
///
/// # Note for implementations
///
/// No need to handle `0x0000, 0x0001, 0x0002, 0x0005, 0x0030, 0x0031, 0x0032, 0x0100`
fn rc_fmt(&self, rc: u16, rrc: u16) -> Option<&'static str>;
@@ -168,7 +169,7 @@ pub enum UvcSuccess {
///
/// # Example
///
/// Use a implementation of [`UvCmd`] to send a specific Ultravisor cammand to the uvevice to
/// Use a implementation of [`UvCmd`] to send a specific Ultravisor command to the uvdevice to
/// forward to Firmware.
///
/// ```rust,no_run
@@ -215,12 +216,15 @@ impl UvDevice {
/// Send an Ultravisor Command via this uvdevice.
///
/// This works by sending an IOCTL to the uvdevice.
///
/// # Errors
///
/// This function will return an error if the IOCTL fails or the Ultravisor does not report
/// a success.
///
/// # Returns
/// [`UvcSuccess`] if the UVC ececuted successfully
///
/// [`UvcSuccess`] if the UVC executed successfully
pub fn send_cmd<C: UvCmd>(&self, cmd: &mut C) -> Result<UvcSuccess> {
let mut cb = IoctlCb::new(cmd.data())?;
ioctl_raw(self.0.as_raw_fd(), cmd.cmd(), &mut cb)?;

View File

@@ -84,7 +84,8 @@ pub const UVIO_ATT_UID_LEN: usize = 0x10;
///
/// If the Retrieve Attestation Measurement UV facility is not present,
/// UV will return invalid command rc.
/// Obviously all numbers are in BIG-endian!
///
/// All numbers are in big-endian!
#[repr(C)]
#[derive(Debug, AsBytes, FromZeroes, FromBytes)]
pub struct uvio_attest {

View File

@@ -11,7 +11,7 @@ use byteorder::{BigEndian, ByteOrder};
use std::{fmt::Display, mem::size_of};
use zerocopy::{AsBytes, U16};
/// The magic value used to identify an add-secret request`]
/// The magic value used to identify an ['crate:AddSecretRequest']
///
/// The magic value is ASCII:
/// ```rust
@@ -78,11 +78,11 @@ pub enum UserDataType {
Null = 0x0000,
/// Arbitrary user data (max 512 bytes)
Unsigned = 0x0001,
/// User data message signed with an Ec key, (max 256 byte)
/// User data message signed with an EC key, (max 256 byte)
SgnEcSECP521R1 = 0x0002,
/// User data message signature with a Rsa key of 2048 bit size, (max 256 byte)
/// User data message signature with a RSA key of 2048 bit size, (max 256 byte)
SgnRsa2048 = 0x0003,
/// User data message signature with a Rsa key of 3072 bit size, (max 128 byte)
/// User data message signature with a RSA key of 3072 bit size, (max 128 byte)
SgnRsa3072 = 0x0004,
}