rust: Improve code formatting

Do some formatting that are in experimental stage but improve the code
readability.

Use rustfmt with a nightly toolchain and enable:

format_code_in_doc_comments = true
reorder_impl_items = true
comment_width = 100
wrap_comments = true
normalize_comments = true

(see .rustfmt.toml)

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-24 13:18:52 +02:00
parent dea5f80215
commit 503e241db1
16 changed files with 78 additions and 71 deletions

View File

@@ -177,7 +177,6 @@ impl ReqEncrCtx {
/// | Request type dependent AAD data |
/// |-------------------------------------------------------------|
/// ```
///
pub fn build_aad<O>(
&self,
version: RequestVersion,
@@ -571,7 +570,7 @@ mod tests {
let hdr_bin_exp = [
0x12, 0x34, 0x56, 0x89, 0xab, 0xcd, 0xef, 0, // magic
0, 0, 2, 0, // vers
0, 0, 0x12, 0x34, //size
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

View File

@@ -111,7 +111,7 @@ impl From<AddSecretVersion> for RequestVersion {
/// An ASRCB wraps a secret to securely transport it to the Ultravisor.
///
/// Layout:
///```none
/// ```none
/// _______________________________________________________________
/// | generic header (48)
/// | --------------------------------------------------- |
@@ -130,7 +130,7 @@ impl From<AddSecretVersion> for RequestVersion {
/// | --------------------------------------------------- |
/// | AES GCM Tag (16) |
/// |_____________________________________________________________|
///```
/// ```
#[derive(Debug)]
pub struct AddSecretRequest {
version: AddSecretVersion,
@@ -148,7 +148,6 @@ impl AddSecretRequest {
///
/// The request has no extension secret, no configuration UID, no host-keys,
/// and no user data
///
pub fn new(
version: AddSecretVersion,
secret: GuestSecret,
@@ -207,7 +206,8 @@ impl AddSecretRequest {
/// - RSA 2048 bit (up to 256 byte message)
/// - RSA 3072 bit (up to 128 byte message)
///
/// The signature can be verified during the verification of the secret-request on the target machine.
/// The signature can be verified during the verification of the secret-request on the target
/// machine.
pub fn set_user_data<T: Into<Vec<u8>>>(
&mut self,
msg: T,
@@ -258,7 +258,7 @@ impl AddSecretRequest {
/// Encrypts data, sign request with user-provided signing key, insert signature into aad,
/// calculate request tag
fn encrypt_with_signed_user_data(&self, ctx: &ReqEncrCtx) -> Result<Vec<u8>> {
//encrypt data w/o aead
// encrypt data w/o aead
let conf = self.conf.to_bytes();
let aad = self.aad(ctx, conf.value().len())?;
let AesGcmResult {

View File

@@ -2,7 +2,7 @@
//
// Copyright IBM Corp. 2023
#[allow(unused_imports)] //used for more convenient docstring
#[allow(unused_imports)] // used for more convenient docstring
use super::asrcb::AddSecretRequest;
use crate::assert_size;
use crate::{
@@ -74,11 +74,12 @@ impl GuestSecret {
GuestSecret::Association { secret, .. } => secret.value().as_slice(),
}
}
/// Creates the non-confidential part of the secret ad-hoc
pub(crate) fn auth(&self) -> SecretAuth {
match &self {
GuestSecret::Null => SecretAuth::Null,
//Panic: every non null secret type is listable -> no panic
// Panic: every non null secret type is listable -> no panic
listable => {
SecretAuth::Listable(ListableSecretHdr::from_guest_secret(listable).unwrap())
}

View File

@@ -112,6 +112,7 @@ impl UserData {
let magic: AddSecretMagic = self.data_type().into();
magic.get()
}
/// Creates new user data
///
/// Verifies that the provided data + signature fits into 512 bytes
@@ -264,7 +265,7 @@ pub fn verify_asrcb_and_get_user_data(
return Err(Error::BinAsrcbInvVersion);
}
//preventing the two lines after the truncate from panicking
// preventing the two lines after the truncate from panicking
let req_len = req.len();
if asrcb.len() < req_len
|| req_len < AddSecretRequest::V1_USER_DATA_OFFS + UserData::USER_DATA_SIZE
@@ -353,7 +354,7 @@ impl VerifiedUserData {
UserDataType::Unsigned => unreachable!(),
};
//overwrite signature field with zeros
// overwrite signature field with zeros
sgn.fill(0);
ret
}

View File

@@ -27,7 +27,6 @@ use std::{cmp::Ordering, ffi::c_int};
/// Minimum security level for the keys/certificates used to establish a chain of
/// trust (see https://www.openssl.org/docs/man1.1.1/man3/X509_VERIFY_PARAM_set_auth_level.html
/// for details).
///
const SECURITY_LEVEL: usize = 2;
const SECURITY_BITS_ARRAY: [u32; 6] = [0, 80, 112, 128, 192, 256];
const SECURITY_BITS: u32 = SECURITY_BITS_ARRAY[SECURITY_LEVEL];
@@ -44,8 +43,8 @@ pub fn verify_hkd_options(hkd: &X509Ref, sign_key: &X509Ref) -> Result<()> {
if SECURITY_BITS > 0 && SECURITY_BITS > security_bits {
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
// 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
check_validity_period(hkd.not_before(), hkd.not_after())?;
@@ -183,7 +182,7 @@ pub fn extract_ibm_sign_key(certs: Vec<X509>) -> Result<(X509, Stack<X509>)> {
}
// Name Entry values of an IBM Z key signing cert
//Asn1StringRef::as_slice aka ASN1_STRING_get0_data gives a string without \0 delimiter
// Asn1StringRef::as_slice aka ASN1_STRING_get0_data gives a string without \0 delimiter
const IBM_Z_COMMON_NAME: &[u8; 43usize] = b"International Business Machines Corporation";
const IBM_Z_COUNTRY_NAME: &[u8; 2usize] = b"US";
const IBM_Z_LOCALITY_NAME_POUGHKEEPSIE: &[u8; 12usize] = b"Poughkeepsie";
@@ -274,7 +273,7 @@ fn load_crl_to_store<P: AsRef<Path>>(
Ok(())
}
///Run through the forest of the distribution points and find them
/// Run through the forest of the distribution points and find them
pub fn x509_dist_points(cert: &X509Ref) -> Vec<String> {
let mut res = Vec::<String>::with_capacity(1);
let dps = match cert.crl_distribution_points() {
@@ -303,8 +302,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 something 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;
@@ -359,10 +358,8 @@ const NIDS_CORRECT_ORDER: [Nid; 6] = [
Nid::STATEORPROVINCENAME,
Nid::COMMONNAME,
];
/**
* Workaround to fix the mismatch between issuer name of the
* IBM Z signing CRLs and the IBM Z signing key subject name.
*/
/// Workaround to fix the mismatch between issuer name of the
/// IBM Z signing CRLs and the IBM Z signing key subject name.
pub fn reorder_x509_names(subject: &X509NameRef) -> std::result::Result<X509Name, ErrorStack> {
let mut correct_subj = X509Name::builder()?;
for nid in NIDS_CORRECT_ORDER {
@@ -373,11 +370,9 @@ pub fn reorder_x509_names(subject: &X509NameRef) -> std::result::Result<X509Name
Ok(correct_subj.build())
}
/**
* Workaround for potential locality mismatches between CRLs and Certs
* # Return
* fixed subject or none if locality was not Armonk or any OpenSSL error
*/
/// Workaround for potential locality mismatches between CRLs and Certs
/// # Return
/// fixed subject or none if locality was not Armonk or any OpenSSL error
pub fn armonk_locality_fixup(subject: &X509NameRef) -> Option<X509Name> {
if !name_data_eq(subject, Nid::LOCALITYNAME, IBM_Z_LOCALITY_NAME_ARMONK) {
return None;

View File

@@ -16,15 +16,15 @@ use zerocopy::{AsBytes, BigEndian, FromBytes, FromZeroes, U64};
pub trait Flags<T>: From<T> + for<'a> From<&'a T> {
/// Set the specified bit to one.
/// # Panics
///Panics if bit is >= 64
/// Panics if bit is >= 64
fn set_bit(&mut self, bit: u8);
/// Set the specified bit to zero.
/// # Panics
///Panics if bit is >= 64
/// Panics if bit is >= 64
fn unset_bit(&mut self, bit: u8);
/// Test if the specified bit is set.
/// # Panics
///Panics if bit is >= 64
/// Panics if bit is >= 64
fn is_set(&self, bit: u8) -> bool;
}
@@ -361,7 +361,7 @@ pub fn parse_hex(hex_str: &str) -> Vec<u8> {
pub fn pv_guest_bit_set() -> bool {
#[cfg(not(target_arch = "s390x"))]
return false;
//s390 branch
// s390 branch
let v = std::fs::read("/sys/firmware/uv/prot_virt_guest").unwrap_or_else(|_| vec![0]);
let v: u8 = String::from_utf8_lossy(&v[..1]).parse().unwrap_or(0);
v == 1

View File

@@ -162,7 +162,8 @@ pub enum UvcSuccess {
RC_MORE_DATA = UvDevice::RC_MORE_DATA,
}
/// The UvDevice is a (virtual) device on s390 machines to send Ultravisor commands(UVCs) from userspace.
/// The UvDevice is a (virtual) device on s390 machines to send Ultravisor commands(UVCs) from
/// userspace.
///
/// On s390 machines with Ultravisor enabled (Secure Execution guest & hosts) the device at
/// `/dev/uv` will accept ioctls.
@@ -184,16 +185,14 @@ pub enum UvcSuccess {
/// # Ok(())
/// # }
/// // do something with the result
///
///
/// ```
#[derive(Debug)]
pub struct UvDevice(File);
impl UvDevice {
const RC_SUCCESS: u16 = 0x0001;
const RC_MORE_DATA: u16 = 0x0100;
const PATH: &'static str = "/dev/uv";
const RC_MORE_DATA: u16 = 0x0100;
const RC_SUCCESS: u16 = 0x0001;
/// Open the uvdevice located at `/dev/uv`
///

View File

@@ -30,7 +30,6 @@ pub const UVIO_IOCTL_LOCK_SECRETS_NR: u8 = 4;
/// Ultravisor.
///
/// `flags` is currently unused and to be set zero
///
#[repr(C)]
#[derive(Debug)]
pub struct uvio_ioctl_cb {
@@ -89,11 +88,11 @@ pub const UVIO_ATT_UID_LEN: usize = 0x10;
#[repr(C)]
#[derive(Debug, AsBytes, FromZeroes, FromBytes)]
pub struct uvio_attest {
pub arcb_addr: u64, //in
pub meas_addr: u64, //out
pub add_data_addr: u64, //out
pub user_data: [u8; UVIO_ATT_USER_DATA_LEN], //in
pub config_uid: [u8; UVIO_ATT_UID_LEN], //out
pub arcb_addr: u64, // in
pub meas_addr: u64, // out
pub add_data_addr: u64, // out
pub user_data: [u8; UVIO_ATT_USER_DATA_LEN], // in
pub config_uid: [u8; UVIO_ATT_UID_LEN], // out
pub arcb_len: u32,
pub meas_len: u32,
pub add_data_len: u32,

View File

@@ -24,7 +24,6 @@ use zerocopy::{AsBytes, FromZeroes};
///
/// Note that bit 0 is always zero for `supp_uv_cmds`
/// as there is no corresponding Info UV-call.
///
#[derive(Debug)]
pub struct UvDeviceInfo {
supp_uvio_cmds: Lsb0Flags64,

View File

@@ -37,7 +37,7 @@ impl Serialize for SecretId {
where
S: Serializer,
{
//calls Display at one point
// calls Display at one point
ser.serialize_str(&self.to_string())
}
}
@@ -151,8 +151,8 @@ pub struct SecretList {
}
impl<'a> IntoIterator for &'a SecretList {
type Item = &'a SecretEntry;
type IntoIter = Iter<'a, SecretEntry>;
type Item = &'a SecretEntry;
fn into_iter(self) -> Self::IntoIter {
self.iter()
@@ -160,8 +160,8 @@ impl<'a> IntoIterator for &'a SecretList {
}
impl IntoIterator for SecretList {
type Item = SecretEntry;
type IntoIter = IntoIter<Self::Item>;
type Item = SecretEntry;
fn into_iter(self) -> Self::IntoIter {
self.secrets.into_iter()
@@ -233,11 +233,11 @@ impl SecretList {
let num_s = r.read_u16::<BigEndian>()?;
let total_num_secrets = r.read_u16::<BigEndian>()? as usize;
let mut v: Vec<SecretEntry> = Vec::with_capacity(num_s as usize);
r.seek(std::io::SeekFrom::Current(12))?; //skip reserved bytes
r.seek(std::io::SeekFrom::Current(12))?; // skip reserved bytes
let mut buf = [0u8; SecretEntry::STRUCT_SIZE];
for _ in 0..num_s {
r.read_exact(&mut buf)?;
//cannot fail. buffer has the same size as the secret entry
// cannot fail. buffer has the same size as the secret entry
let secr = SecretEntry::read_from(buf.as_slice()).unwrap();
v.push(secr);
}
@@ -250,6 +250,7 @@ impl SecretList {
impl TryFrom<ListCmd> for SecretList {
type Error = Error;
fn try_from(mut list: ListCmd) -> Result<SecretList> {
SecretList::decode(&mut Cursor::new(list.data().unwrap())).map_err(Error::InvSecretList)
}
@@ -292,11 +293,11 @@ pub enum ListableSecretType {
}
impl ListableSecretType {
const RESERVED_0: u16 = 0x0000;
/// UV type id for a null secret
pub const NULL: u16 = 0x0001;
/// UV type id for an association secret
pub const ASSOCIATION: u16 = 0x0002;
/// UV type id for a null secret
pub const NULL: u16 = 0x0001;
const RESERVED_0: u16 = 0x0000;
}
impl Display for ListableSecretType {
@@ -338,9 +339,11 @@ where
impl<'de> serde::de::Visitor<'de> for FieldVisitor {
type Value = [u8; SecretId::ID_SIZE];
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a `32 bytes long hexstring` prepended with 0x")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
@@ -370,8 +373,8 @@ mod test {
#[test]
fn dump_secret_entry() {
const EXP: &[u8] = &[
0x00, 0x01, 0x00, 0x02, //idx + type
0x00, 0x00, 0x00, 0x20, //len
0x00, 0x01, 0x00, 0x02, // idx + type
0x00, 0x00, 0x00, 0x20, // len
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
// id
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
@@ -394,10 +397,11 @@ mod test {
let buf = [
0x00u8, 0x01, // num secr stored
0x01, 0x12, // total num secrets
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //reserved
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, // reserved
// secret
0x00, 0x01, 0x00, 0x02, //idx + type
0x00, 0x00, 0x00, 0x20, //len
0x00, 0x01, 0x00, 0x02, // idx + type
0x00, 0x00, 0x00, 0x20, // len
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
// id
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
@@ -426,10 +430,11 @@ mod test {
const EXP: &[u8] = &[
0x00, 0x01, // num secr stored
0x01, 0x12, // total num secrets
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //reserved
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, // reserved
// secret
0x00, 0x01, 0x00, 0x02, //idx + type
0x00, 0x00, 0x00, 0x20, //len
0x00, 0x01, 0x00, 0x02, // idx + type
0x00, 0x00, 0x00, 0x20, // len
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
// id
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,

View File

@@ -38,6 +38,7 @@ impl IoctlCtx {
self.exp_cmd = cmd;
self
}
pub fn set_mdfy<F>(&mut self, mdfy: F) -> &mut Self
where
F: FnMut(&mut ffi::uvio_ioctl_cb) -> c_int + 'static + Send + Sync,
@@ -45,6 +46,7 @@ impl IoctlCtx {
self.modify = Box::new(mdfy);
self
}
pub fn reset(&mut self) -> bool {
let old = self.called;
self.called = false;
@@ -86,6 +88,7 @@ impl ffi::uvio_ioctl_cb {
);
self
}
fn size_eq(&self, exp: u32) -> &Self {
assert_eq!(
self.argument_len, exp,
@@ -94,10 +97,12 @@ impl ffi::uvio_ioctl_cb {
);
self
}
fn set_rc(&mut self, rc: u16) -> &mut Self {
self.uv_rc = rc;
self
}
fn set_rrc(&mut self, rrc: u16) -> &mut Self {
self.uv_rrc = rrc;
self
@@ -112,9 +117,11 @@ impl UvCmd for TestCmd {
fn cmd(&self) -> u64 {
TEST_CMD
}
fn rc_fmt(&self, _rc: u16, _rrc: u16) -> Option<&'static str> {
None
}
fn data(&mut self) -> Option<&mut [u8]> {
match &mut self.0 {
None => None,
@@ -124,7 +131,8 @@ impl UvCmd for TestCmd {
}
impl UvDevice {
///use some random fd for `uvdevice` its OK, as the ioctl is mocked and never touches the passed file
/// use some random fd for `uvdevice` its OK, as the ioctl is mocked and never touches the
/// passed file
fn test_dev() -> Self {
UvDevice(unsafe { File::from_raw_fd(17) })
}

View File

@@ -23,8 +23,7 @@ use zerocopy::{AsBytes, U16};
/// # ;
/// # assert!(AddSecretMagic::starts_with_magic(magic));
/// # }
///```
///
/// ```
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, AsBytes)]
pub struct AddSecretMagic {

View File

@@ -42,7 +42,8 @@ impl ApConfigEntry {
}
// if name is given, calculate sha256 digest for this name
// test for the hash calculated here can be done with openssl:
// echo -n "Hello" >in.bin; openssl dgst -sha256 -binary -out out.bin in.bin; hexdump -C out.bin
// echo -n "Hello" >in.bin; openssl dgst -sha256 -binary -out out.bin in.bin; hexdump -C
// out.bin
if self.name.is_empty() {
return Ok(());
}

View File

@@ -130,10 +130,11 @@ pub struct CreateSecretOpt {
///
/// Adds a signature calculated from the key in <FILE> to the add-secret request. The
/// file must be in DER or PEM format containing a private key. Supported are RSA 2048 &
/// 3072-bit and EC(secp521r1) keys. The firmware ignores the content, but the request tag protects the
/// signature. The user-signing key signs the request. The location of the signature is filled
/// with zeros during the signature calculation. The request tag also secures the signature.
/// See man pvsecret verify for more details. Optional. No signature by default.
/// 3072-bit and EC(secp521r1) keys. The firmware ignores the content, but the request tag
/// protects the signature. The user-signing key signs the request. The location of the
/// signature is filled with zeros during the signature calculation. The request tag also
/// secures the signature. See man pvsecret verify for more details. Optional. No signature
/// by default.
#[arg(long, value_name = "FILE", value_hint = ValueHint::FilePath,)]
pub user_sign_key: Option<String>,
}
@@ -157,9 +158,9 @@ pub enum AddSecretType {
/// white-spaces mapped to `_`.
name: String,
///Print the hashed name to stdout.
/// Print the hashed name to stdout.
///
///The hashed name is not written to `NAME.yaml`
/// The hashed name is not written to `NAME.yaml`
#[arg(long)]
stdout: bool,

View File

@@ -213,7 +213,7 @@ fn write_secret(secret: &AddSecretType, asrcb: &AddSecretRequest) -> Result<()>
.map(|c| if c.is_whitespace() { '_' } else { c })
.collect();
//write non confidential data (=name+id) to a yaml
// write non confidential data (=name+id) to a yaml
let secret_info = serde_yaml::to_string(asrcb.guest_secret())?;
if stdout.to_owned() {
println!("{secret_info}");

View File

@@ -33,7 +33,7 @@ fn main() -> ExitCode {
// set up logger/std(out,err)
if let Err(e) = LOGGER.start(cli.verbose) {
//should(TM) never happen
// should(TM) never happen
eprintln!("Logger error: {e:?}");
return EXIT_LOGGER.into();
}