mirror of
https://github.com/ibm-s390-linux/s390-tools.git
synced 2026-08-05 02:14:52 +00:00
rust/pv: Refactor pv crate
Big refactoring patch of the pv crate. The main reason behind this refactoring is to simplify testing and maintaining the pv crate while keeping OpenSSL/libcurl dependencies optional. Using crate features increases the number of targets that have to be tested. This refactoring eliminates the use of features by splitting the functionality of pv into a use OpenSSL and no-use-OpenSSL crate. Split off some code from the pv crate into a pv_core crate. pv requires pv_core and reexports all symbols. pv_base contains all code from former pv that does not use OpenSSL or libcurl functionalities. The refactored pv crate contains functionalities to generate requests and validate host key documents. All features from pv are dropped as they are not needed anymore and to streamline the codebase for easier use and testing. While at it fix some documentation issues. Users (pvsecret & pvapconfig) have next to no code change, besides the different import of the crate. Acked-by: Marc Hartmayer <mhartmay@linux.ibm.com> Signed-off-by: Steffen Eiden <seiden@linux.ibm.com> Signed-off-by: Jan Höppner <hoeppner@linux.ibm.com>
This commit is contained in:
committed by
Jan Höppner
parent
48539596ef
commit
9b51b8b882
+2
-4
@@ -8,10 +8,9 @@ use std::{
|
||||
};
|
||||
|
||||
// (SE) boot request control block aka SE header
|
||||
use crate::{
|
||||
assert_size, request::MagicValue, requires_feat, static_assert, Error, Result, PAGESIZE,
|
||||
};
|
||||
use crate::{assert_size, static_assert, Error, Result, PAGESIZE};
|
||||
use log::debug;
|
||||
use pv_core::request::MagicValue;
|
||||
use zerocopy::{AsBytes, BigEndian, FromBytes, U32, U64};
|
||||
|
||||
/// Struct containing all SE-header tags.
|
||||
@@ -22,7 +21,6 @@ use zerocopy::{AsBytes, BigEndian, FromBytes, U32, U64};
|
||||
/// Tweak List Digest (tld)
|
||||
/// SE Header Tag (seht)
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, AsBytes, PartialEq, Eq)]
|
||||
pub struct BootHdrTags {
|
||||
|
||||
+3
-16
@@ -2,13 +2,12 @@
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use crate::misc::{create_file, open_file};
|
||||
use crate::Result;
|
||||
use clap::{ArgGroup, Args, ValueHint};
|
||||
use std::io::{Read, Write};
|
||||
|
||||
/// CLI Argument collection for handling certificates.
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
#[derive(Args, Debug, PartialEq, Eq, Default)]
|
||||
#[command(
|
||||
group(ArgGroup::new("pv_verify").required(true).args(["no_verify", "certs"])),
|
||||
@@ -103,37 +102,25 @@ impl CertificateOptions {
|
||||
}
|
||||
|
||||
/// stdout
|
||||
#[cfg(feature = "request")]
|
||||
pub const STDOUT: &str = "-";
|
||||
/// stdin
|
||||
#[cfg(feature = "request")]
|
||||
pub const STDIN: &str = "-";
|
||||
|
||||
/// Converts an argument value into a Writer.
|
||||
///
|
||||
/// # Errors
|
||||
/// No Error will occur but function must match a signature
|
||||
///
|
||||
#[cfg(feature = "request")]
|
||||
pub fn get_writer_from_cli_file_arg(path: &str) -> Result<Box<dyn Write>> {
|
||||
if path == STDOUT {
|
||||
Ok(Box::new(std::io::stdout()))
|
||||
} else {
|
||||
Ok(Box::new(crate::misc::create_file(path)?))
|
||||
Ok(Box::new(create_file(path)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts an argument value into a Reader.
|
||||
///
|
||||
/// # Errors
|
||||
/// No Error will occur but function must match a signature
|
||||
///
|
||||
#[cfg(feature = "request")]
|
||||
pub fn get_reader_from_cli_file_arg(path: &str) -> Result<Box<dyn Read>> {
|
||||
if path == STDIN {
|
||||
Ok(Box::new(std::io::stdin()))
|
||||
} else {
|
||||
Ok(Box::new(crate::misc::open_file(path)?))
|
||||
Ok(Box::new(open_file(path)?))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use crate::requires_feat;
|
||||
use crate::{error::Result, secret::Secret, Error};
|
||||
use openssl::rand::rand_bytes;
|
||||
use openssl::{
|
||||
@@ -19,12 +18,10 @@ use std::convert::TryInto;
|
||||
|
||||
/// An AES256-key that will purge itself out of the memory when going out of scope
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
pub type Aes256Key = Secret<[u8; 32]>;
|
||||
|
||||
/// Types of symmetric keys, to specify during construction.
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SymKeyType {
|
||||
@@ -34,7 +31,6 @@ pub enum SymKeyType {
|
||||
|
||||
/// Types of symmetric keys
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum SymKey {
|
||||
@@ -88,7 +84,6 @@ impl From<Aes256Key> for SymKey {
|
||||
/// Performs an hkdf according to RFC 5869.
|
||||
/// See [`OpenSSL HKDF`]()
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an OpenSSL error if the key could not be generated.
|
||||
@@ -113,7 +108,6 @@ pub fn hkdf_rfc_5869<const COUNT: usize>(
|
||||
|
||||
/// Derive a symmetric key from a private and a public key.
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if something went bad in OpenSSL.
|
||||
@@ -132,7 +126,6 @@ pub fn derive_key(k1: &PKey<Private>, k2: &PKey<Public>) -> Result<Aes256Key> {
|
||||
|
||||
/// Generate a random array.
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if the entropy source fails or is not available.
|
||||
@@ -144,7 +137,6 @@ pub fn random_array<const COUNT: usize>() -> Result<[u8; COUNT]> {
|
||||
|
||||
/// Generate a new random EC-SECP521R1 key.
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if the key could not be generated by OpenSSL.
|
||||
@@ -160,7 +152,6 @@ pub fn gen_ec_key() -> Result<PKey<Private>> {
|
||||
/// * `iv` - initialisation vector
|
||||
/// * `conf` - data to be encrypted
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if the data could not be encrypted by OpenSSL.
|
||||
@@ -179,7 +170,6 @@ pub fn encrypt_aes(key: &SymKey, iv: &[u8], conf: &[u8]) -> Result<Vec<u8>> {
|
||||
/// * `aad` - additional authentic data
|
||||
/// * `conf` - data to be encrypted
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
/// # Returns
|
||||
/// [`Vec<u8>`] with the following content:
|
||||
/// 1. `aad`
|
||||
@@ -212,7 +202,6 @@ pub fn encrypt_aes_gcm(key: &SymKey, iv: &[u8], aad: &[u8], conf: &[u8]) -> Resu
|
||||
|
||||
/// Calculate the hash of a slice.
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if OpenSSL could not compute the hash.
|
||||
|
||||
+2
-106
@@ -10,49 +10,19 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[cfg_attr(debug_assertions, error("Ultravisor: '{msg}' ({rc:#06x},{rrc:#06x})"))]
|
||||
#[cfg_attr(not(debug_assertions), error("Ultravisor: '{msg}' ({rc:#06x})"))]
|
||||
Uv {
|
||||
rc: u16,
|
||||
rrc: u16,
|
||||
msg: &'static str,
|
||||
},
|
||||
|
||||
#[error("Invalid SE header provided")]
|
||||
#[cfg(feature = "request")]
|
||||
InvBootHdr,
|
||||
|
||||
#[error("{0}")]
|
||||
Specification(String),
|
||||
|
||||
#[error("Cannot {ty} {ctx} at `{path}`")]
|
||||
FileIo {
|
||||
ty: FileIoErrorType,
|
||||
ctx: String,
|
||||
path: String,
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("Cannot {ty} `{path}`")]
|
||||
FileAccess {
|
||||
ty: FileAccessErrorType,
|
||||
path: String,
|
||||
source: std::io::Error,
|
||||
},
|
||||
|
||||
#[error("Host-key verification failed: {0}")]
|
||||
#[cfg(feature = "request")]
|
||||
HkdVerify(HkdVerifyErrorType),
|
||||
|
||||
#[error("No host-key provided")]
|
||||
#[cfg(feature = "request")]
|
||||
NoHostkey,
|
||||
|
||||
#[error("To many host-keys provided")]
|
||||
#[cfg(feature = "request")]
|
||||
ManyHostkeys,
|
||||
|
||||
#[error("Cannot load {ty} from {path}")]
|
||||
#[cfg(feature = "request")]
|
||||
X509Load {
|
||||
path: String,
|
||||
ty: &'static str,
|
||||
@@ -60,38 +30,16 @@ pub enum Error {
|
||||
},
|
||||
|
||||
#[error("Internal (unexpected) error: {0}, caused by {1}")]
|
||||
#[cfg(feature = "request")]
|
||||
InternalSsl(&'static str, #[source] openssl::error::ErrorStack),
|
||||
|
||||
#[error("No Config UID found: {0}")]
|
||||
NoCuid(String),
|
||||
// errors from request types
|
||||
#[cfg(feature = "uvsecret")]
|
||||
#[error("Customer Communication Key must be 32 bytes long")]
|
||||
CckSize,
|
||||
|
||||
#[cfg(feature = "uvsecret")]
|
||||
#[error("Cannot encode secrets (Too many secrets)")]
|
||||
ManySecrets,
|
||||
|
||||
#[cfg(feature = "uvsecret")]
|
||||
#[error("Cannot decode secret list")]
|
||||
InvSecretList(#[source] std::io::Error),
|
||||
|
||||
#[cfg(feature = "uvsecret")]
|
||||
#[error("Input does not contain an add-secret request")]
|
||||
NoAsrcb,
|
||||
|
||||
// errors from other crates
|
||||
#[error(transparent)]
|
||||
PvCore(#[from] pv_core::Error),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error(transparent)]
|
||||
#[cfg(feature = "request")]
|
||||
Crypto(#[from] openssl::error::ErrorStack),
|
||||
#[error(transparent)]
|
||||
ParseInt(#[from] std::num::ParseIntError),
|
||||
#[cfg(feature = "request")]
|
||||
#[error(transparent)]
|
||||
Curl(#[from] curl::Error),
|
||||
}
|
||||
|
||||
@@ -102,35 +50,11 @@ impl Error {
|
||||
pub const CERT: &str = "certificate";
|
||||
}
|
||||
|
||||
/// Error cases for I/O operations
|
||||
#[allow(missing_docs)]
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum FileIoErrorType {
|
||||
#[error("read")]
|
||||
Read,
|
||||
#[error("write")]
|
||||
Write,
|
||||
}
|
||||
|
||||
/// Error cases for accessing files
|
||||
#[allow(missing_docs)]
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum FileAccessErrorType {
|
||||
#[error("open")]
|
||||
Open,
|
||||
#[error("create")]
|
||||
Create,
|
||||
}
|
||||
|
||||
/// Error cases for verifying host-key documents
|
||||
///
|
||||
#[doc = crate::requires_feat!(request)]
|
||||
#[allow(missing_docs)]
|
||||
#[derive(thiserror::Error, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
#[cfg(feature = "request")]
|
||||
pub enum HkdVerifyErrorType {
|
||||
#[error("Signature verification failed")]
|
||||
Signature,
|
||||
@@ -160,37 +84,9 @@ pub enum HkdVerifyErrorType {
|
||||
IbmSignInvalid(#[source] openssl::x509::X509VerifyResult, u32),
|
||||
}
|
||||
|
||||
macro_rules! path_to_str {
|
||||
($path: expr) => {
|
||||
$path.as_ref().to_str().unwrap_or("no UTF-8 path")
|
||||
};
|
||||
}
|
||||
pub(crate) use path_to_str;
|
||||
|
||||
macro_rules! file_error {
|
||||
($ty: tt, $ctx: expr, $path:expr, $src: expr) => {
|
||||
$crate::Error::FileIo {
|
||||
ty: $crate::FileIoErrorType::$ty,
|
||||
ctx: $ctx.to_string(),
|
||||
path: $path.to_string(),
|
||||
source: $src,
|
||||
}
|
||||
};
|
||||
}
|
||||
pub(crate) use file_error;
|
||||
|
||||
#[cfg(feature = "request")]
|
||||
macro_rules! bail_hkd_verify {
|
||||
($var: tt) => {
|
||||
return Err($crate::Error::HkdVerify($crate::HkdVerifyErrorType::$var))
|
||||
};
|
||||
}
|
||||
#[cfg(feature = "request")]
|
||||
pub(crate) use bail_hkd_verify;
|
||||
|
||||
macro_rules! bail_spec {
|
||||
($str: expr) => {
|
||||
return Err($crate::Error::Specification($str.to_string()))
|
||||
};
|
||||
}
|
||||
pub(crate) use bail_spec;
|
||||
|
||||
+47
-121
@@ -2,7 +2,6 @@
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]
|
||||
#![deny(missing_docs)]
|
||||
//! pv - library for pv-tools
|
||||
//!
|
||||
@@ -11,156 +10,83 @@
|
||||
//! `pv` provides abstraction layers for encryption, secure memory management,
|
||||
//! logging, and accessing the uvdevice.
|
||||
//!
|
||||
//! ## Feature Flags
|
||||
//! The following feature flags are available:
|
||||
//! - `request`
|
||||
//! - optional
|
||||
//! - Enables generation of UV requests
|
||||
//! - `uvsecret`
|
||||
//! - optional
|
||||
//! - Enables support for the UV Secret API.
|
||||
//! If you do not need any OpenSSL features use `pv_core`.
|
||||
//! This crate reexports all symbols from `pv_core`
|
||||
mod brcb;
|
||||
mod cli;
|
||||
mod crypto;
|
||||
mod error;
|
||||
mod log;
|
||||
mod req;
|
||||
mod secret;
|
||||
mod utils;
|
||||
mod uvdevice;
|
||||
mod uvsecret;
|
||||
mod verify;
|
||||
|
||||
/// Internal macro to conveninetly document required features on items
|
||||
// #[macro_export]
|
||||
/// utility functions for writing TESTS!!!
|
||||
//hide any test helpers on docs!
|
||||
#[doc(hidden)]
|
||||
macro_rules! requires_feat {
|
||||
(request) => {
|
||||
" Requires the feature `request`"
|
||||
};
|
||||
(uvsecret) => {
|
||||
" Requires the feature `uvsecret`"
|
||||
};
|
||||
(reqsecret) => {
|
||||
"Requires the features `request` & `uvsecret`"
|
||||
};
|
||||
}
|
||||
#[allow(unused_imports)]
|
||||
use requires_feat;
|
||||
|
||||
//only some features need this
|
||||
#[allow(dead_code)]
|
||||
pub mod test_utils;
|
||||
|
||||
pub use ::utils::assert_size;
|
||||
pub use ::utils::static_assert;
|
||||
|
||||
const PAGESIZE: usize = 0x1000;
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(feature = "request")] {
|
||||
mod brcb;
|
||||
mod cli;
|
||||
mod crypto;
|
||||
mod req;
|
||||
mod secret;
|
||||
mod uvsecret;
|
||||
mod verify;
|
||||
|
||||
/// utility functions for writing TESTS!!!
|
||||
#[allow(dead_code)]
|
||||
//hide any test helpers on docs!
|
||||
#[doc(hidden)]
|
||||
pub mod test_utils;
|
||||
|
||||
}
|
||||
}
|
||||
/// Definitions and functions for interacting with the Ultravisor
|
||||
pub mod uv {
|
||||
pub use crate::uvdevice::{
|
||||
pub use pv_core::uv::{
|
||||
uv_ioctl, ConfigUid, UvCmd, UvDevice, UvDeviceInfo, UvFlags, UvcSuccess,
|
||||
};
|
||||
#[cfg(feature = "uvsecret")]
|
||||
pub use crate::uvsecret::{
|
||||
secret_list::{ListableSecretType, SecretEntry, SecretList},
|
||||
uvc::{AddCmd, ListCmd, LockCmd},
|
||||
};
|
||||
pub use pv_core::uv::{AddCmd, ListCmd, LockCmd};
|
||||
pub use pv_core::uv::{ListableSecretType, SecretEntry, SecretList};
|
||||
}
|
||||
|
||||
/// Miscellaneous functions and definitions
|
||||
pub mod misc {
|
||||
|
||||
#[cfg(feature = "request")]
|
||||
pub use crate::cli::{
|
||||
get_reader_from_cli_file_arg, get_writer_from_cli_file_arg, CertificateOptions, STDIN,
|
||||
STDOUT,
|
||||
};
|
||||
pub use crate::log::PvLogger;
|
||||
pub use crate::utils::{
|
||||
create_file, memeq, open_file, parse_hex, pv_guest_bit_set, read, read_exact_file,
|
||||
read_file, to_u16, to_u32, try_parse_u128, try_parse_u64, write, write_file, Flags,
|
||||
Lsb0Flags64, Msb0Flags64,
|
||||
};
|
||||
#[cfg(feature = "request")]
|
||||
pub use crate::utils::{read_certs, read_crls};
|
||||
pub use pv_core::misc::*;
|
||||
pub use pv_core::PvLogger;
|
||||
}
|
||||
|
||||
#[cfg(feature = "request")]
|
||||
pub use crate::error::HkdVerifyErrorType;
|
||||
pub use error::{Error, FileAccessErrorType, FileIoErrorType, Result};
|
||||
pub use error::{Error, Result};
|
||||
|
||||
/// Functionalities to build UV requests
|
||||
#[doc = requires_feat!(request)]
|
||||
pub mod request {
|
||||
pub use crate::brcb::{BootHdrMagic, BootHdrTags};
|
||||
pub use crate::crypto::derive_key;
|
||||
pub use crate::crypto::random_array;
|
||||
pub use crate::crypto::{encrypt_aes, encrypt_aes_gcm, gen_ec_key};
|
||||
pub use crate::crypto::{hash, hkdf_rfc_5869};
|
||||
pub use crate::crypto::{Aes256Key, SymKey, SymKeyType};
|
||||
pub use crate::req::{Aad, Encrypt, Keyslot, ReqEncrCtx, Request};
|
||||
pub use crate::secret::{Secret, Zeroize};
|
||||
pub use crate::verify::HkdVerifier;
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(feature = "request")] {
|
||||
pub use crate::brcb::{BootHdrTags, BootHdrMagic};
|
||||
pub use crate::crypto::{
|
||||
derive_key, encrypt_aes, encrypt_aes_gcm, gen_ec_key, hash, hkdf_rfc_5869,
|
||||
random_array, Aes256Key, SymKey, SymKeyType,
|
||||
};
|
||||
pub use crate::req::{Aad, Encrypt, Keyslot, ReqEncrCtx, Request};
|
||||
pub use crate::secret::{Secret, Zeroize};
|
||||
pub use crate::verify::HkdVerifier;
|
||||
|
||||
/// Reexports some useful OpenSSL symbols
|
||||
///
|
||||
#[doc = requires_feat!(request)]
|
||||
pub mod openssl {
|
||||
pub use openssl::error::ErrorStack;
|
||||
pub use openssl::hash::MessageDigest;
|
||||
pub use openssl::md::Md;
|
||||
pub use openssl::pkey;
|
||||
}
|
||||
|
||||
}
|
||||
/// Reexports some useful OpenSSL symbols
|
||||
pub mod openssl {
|
||||
pub use openssl::error::ErrorStack;
|
||||
pub use openssl::hash::MessageDigest;
|
||||
pub use openssl::md::Md;
|
||||
pub use openssl::pkey;
|
||||
}
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(feature = "uvsecret")] {
|
||||
/// Functionalities for creating add-secret requests
|
||||
pub mod uvsecret {
|
||||
#[cfg(feature = "request")]
|
||||
pub use crate::uvsecret::{
|
||||
asrcb::{AddSecretFlags, AddSecretRequest, AddSecretVersion,},
|
||||
ext_secret::ExtSecret,
|
||||
guest_secret::GuestSecret,
|
||||
};
|
||||
pub use crate::uvsecret::AddSecretMagic;
|
||||
pub use crate::uvsecret::UserDataType;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Version number of the request in system-endian
|
||||
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
|
||||
/// (binary) data.
|
||||
pub trait MagicValue<const N: usize> {
|
||||
/// Magic value as byte array
|
||||
const MAGIC: [u8; N];
|
||||
/// Test whether the given slice starts with the magic value.
|
||||
fn starts_with_magic(v: &[u8]) -> bool {
|
||||
if v.len() < Self::MAGIC.len() {
|
||||
return false;
|
||||
}
|
||||
crate::misc::memeq(&v[..Self::MAGIC.len()], &Self::MAGIC)
|
||||
}
|
||||
/// Functionalities for creating add-secret requests
|
||||
pub mod uvsecret {
|
||||
pub use crate::uvsecret::{
|
||||
asrcb::{AddSecretFlags, AddSecretRequest, AddSecretVersion},
|
||||
ext_secret::ExtSecret,
|
||||
guest_secret::GuestSecret,
|
||||
};
|
||||
pub use pv_core::request::uvsecret::AddSecretMagic;
|
||||
pub use pv_core::request::uvsecret::UserDataType;
|
||||
}
|
||||
pub use pv_core::request::RequestMagic;
|
||||
}
|
||||
|
||||
/// Provides cargo version Info about this crate.
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use log::{self, Level, LevelFilter, Log, Metadata, Record};
|
||||
|
||||
/// A simple Logger that prints to stderr if the verbosity level is high enough.
|
||||
/// Prints log-level for Debug+Trace
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct PvLogger;
|
||||
|
||||
fn to_level(verbosity: u8) -> LevelFilter {
|
||||
match verbosity {
|
||||
// Error and Warn on by default
|
||||
0 => LevelFilter::Warn,
|
||||
1 => LevelFilter::Info,
|
||||
2 => LevelFilter::Debug,
|
||||
_ => LevelFilter::Trace,
|
||||
}
|
||||
}
|
||||
|
||||
impl PvLogger {
|
||||
/// Set self as the logger for this application.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// An error is returned if a logger has already been set.
|
||||
pub fn start(&'static self, verbosity: u8) -> Result<(), log::SetLoggerError> {
|
||||
log::set_logger(self).map(|()| log::set_max_level(to_level(verbosity)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Log for PvLogger {
|
||||
fn enabled(&self, _metadata: &Metadata) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn log(&self, record: &Record) {
|
||||
if self.enabled(record.metadata()) {
|
||||
if record.level() > Level::Info {
|
||||
eprintln!("{}: {}", record.level(), record.args());
|
||||
} else {
|
||||
eprintln!("{}", record.args());
|
||||
}
|
||||
}
|
||||
}
|
||||
fn flush(&self) {}
|
||||
}
|
||||
+6
-5
@@ -4,8 +4,7 @@
|
||||
|
||||
use crate::misc::to_u32;
|
||||
use crate::request::{
|
||||
derive_key, encrypt_aes, encrypt_aes_gcm, gen_ec_key, random_array, RequestMagic,
|
||||
RequestVersion, SymKey, SymKeyType,
|
||||
derive_key, encrypt_aes, encrypt_aes_gcm, gen_ec_key, random_array, SymKey, SymKeyType,
|
||||
};
|
||||
use crate::{Error, Result};
|
||||
use openssl::bn::{BigNum, BigNumContext};
|
||||
@@ -13,6 +12,7 @@ use openssl::ec::{EcGroupRef, EcPointRef};
|
||||
use openssl::error::ErrorStack;
|
||||
use openssl::hash::{hash, MessageDigest};
|
||||
use openssl::pkey::{PKey, PKeyRef, Private, Public};
|
||||
use pv_core::request::{RequestMagic, RequestVersion};
|
||||
use std::convert::TryInto;
|
||||
use zerocopy::{AsBytes, BigEndian, FromBytes, U32};
|
||||
|
||||
@@ -215,10 +215,11 @@ impl ReqEncrCtx {
|
||||
}
|
||||
}
|
||||
|
||||
let rql = to_u32(auth_data.len() + encr_size + 16)
|
||||
.ok_or_else(|| Error::Specification("Configured request size to large".to_string()))?;
|
||||
let rql = to_u32(auth_data.len() + encr_size + 16).ok_or_else(|| {
|
||||
pv_core::Error::Specification("Configured request size to large".to_string())
|
||||
})?;
|
||||
let sea = to_u32(encr_size)
|
||||
.ok_or_else(|| Error::Specification("Encrypted size to large".to_string()))?;
|
||||
.ok_or_else(|| pv_core::Error::Specification("Encrypted size to large".to_string()))?;
|
||||
|
||||
let req_hdr = RequestHdr::new(version, rql, self.iv, nks, sea, magic);
|
||||
// copy request header to the start of the request
|
||||
|
||||
+1
-630
@@ -1,355 +1,9 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use crate::{
|
||||
error::{bail_spec, file_error, path_to_str, FileAccessErrorType},
|
||||
Error, FileIoErrorType, Result,
|
||||
};
|
||||
|
||||
#[cfg(feature = "request")]
|
||||
use crate::{Error, Result};
|
||||
use openssl::x509::X509Crl;
|
||||
#[cfg(feature = "request")]
|
||||
use openssl::x509::X509;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
path::Path,
|
||||
};
|
||||
use zerocopy::{AsBytes, BigEndian, FromBytes, U64};
|
||||
|
||||
/// Asserts a constant expression evaluates to `true`.
|
||||
///
|
||||
/// If the expression is not evaluated to `true` the compilation will fail.
|
||||
#[macro_export]
|
||||
macro_rules! static_assert {
|
||||
($condition:expr) => {
|
||||
const _: () = core::assert!($condition);
|
||||
};
|
||||
}
|
||||
|
||||
/// Asserts that a type has a specific size.
|
||||
///
|
||||
/// Useful to validate structs that are passed to C code.
|
||||
/// If the expression is not evaluated to `true` the compilation will fail.
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust
|
||||
/// # use pv::assert_size;
|
||||
/// # fn main() {}
|
||||
/// #[repr(C)]
|
||||
/// struct c_struct {
|
||||
/// v: u64,
|
||||
/// }
|
||||
/// assert_size!(c_struct, 8);
|
||||
/// // assert_size!(c_struct, 7);//won't compile
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! assert_size {
|
||||
($t:ty, $sz:expr ) => {
|
||||
$crate::static_assert!(::std::mem::size_of::<$t>() == $sz);
|
||||
};
|
||||
}
|
||||
|
||||
/// Trait that describes bitflags, represented by `T`.
|
||||
pub trait Flags<T>: From<T> + for<'a> From<&'a T> {
|
||||
/// Set the specified bit to one.
|
||||
/// # Panics
|
||||
///Panics if bit is >= 64
|
||||
fn set_bit(&mut self, bit: u8);
|
||||
/// Set the specified bit to zero.
|
||||
/// # Panics
|
||||
///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
|
||||
fn is_set(&self, bit: u8) -> bool;
|
||||
}
|
||||
|
||||
/// Bitflags in MSB0 ordering
|
||||
///
|
||||
/// Wraps an u64 to set/get individual bits
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, AsBytes, FromBytes)]
|
||||
pub struct Msb0Flags64(U64<BigEndian>);
|
||||
impl Flags<u64> for Msb0Flags64 {
|
||||
#[track_caller]
|
||||
fn set_bit(&mut self, bit: u8) {
|
||||
assert!(bit < 64, "Flag bit set to greater than 63");
|
||||
let mut v = self.0.get();
|
||||
v |= 1 << (63 - bit);
|
||||
self.0.set(v)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn unset_bit(&mut self, bit: u8) {
|
||||
assert!(bit < 64, "Flag bit set to greater than 63");
|
||||
let mut v = self.0.get();
|
||||
v &= !(1 << (63 - bit));
|
||||
self.0.set(v)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn is_set(&self, bit: u8) -> bool {
|
||||
assert!(bit < 64, "Flag bit set to greater than 63");
|
||||
self.0.get() & (1 << (63 - bit)) > 0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for Msb0Flags64 {
|
||||
fn from(value: u64) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&u64> for Msb0Flags64 {
|
||||
fn from(value: &u64) -> Self {
|
||||
(*value).into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Bitflags in LSB0 ordering
|
||||
///
|
||||
/// Wraps an u64 to set/get individual bits
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default, AsBytes, FromBytes)]
|
||||
pub struct Lsb0Flags64(U64<BigEndian>);
|
||||
impl Flags<u64> for Lsb0Flags64 {
|
||||
#[track_caller]
|
||||
fn set_bit(&mut self, bit: u8) {
|
||||
assert!(bit < 64, "Flag bit set to greater than 63");
|
||||
let mut v = self.0.get();
|
||||
v |= 1 << bit;
|
||||
self.0.set(v)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn unset_bit(&mut self, bit: u8) {
|
||||
assert!(bit < 64, "Flag bit set to greater than 63");
|
||||
let mut v = self.0.get();
|
||||
v &= !(1 << bit);
|
||||
self.0.set(v)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn is_set(&self, bit: u8) -> bool {
|
||||
assert!(bit < 64, "Flag bit set to greater than 63");
|
||||
self.0.get() & (1 << bit) > 0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for Lsb0Flags64 {
|
||||
fn from(value: u64) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&u64> for Lsb0Flags64 {
|
||||
fn from(value: &u64) -> Self {
|
||||
(*value).into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to convert a BE hex string into a 128 unsigned integer
|
||||
/// The hexstring must contain 32chars of hexdigits
|
||||
///
|
||||
/// * `hex_str` - string to convert can be prepended with "0x"
|
||||
/// * `ctx` - Error context string in case of an error
|
||||
/// ```rust
|
||||
/// # use std::error::Error;
|
||||
/// # use pv::misc::try_parse_u128;
|
||||
/// # fn main() -> Result<(), Box<dyn Error>> {
|
||||
/// let hex = "11223344556677889900aabbccddeeff";
|
||||
/// try_parse_u128(&hex, "The test")?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// # Errors
|
||||
/// If `hex_string` is not a 32 byte hex string an Error appears
|
||||
pub fn try_parse_u128(hex_str: &str, ctx: &str) -> Result<[u8; 16]> {
|
||||
let hex_str = if hex_str.starts_with("0x") {
|
||||
hex_str.split_at(2).1
|
||||
} else {
|
||||
hex_str
|
||||
};
|
||||
if hex_str.len() != 32 {
|
||||
bail_spec!(format!(
|
||||
"{ctx} hexstring must be 32chars long to cover all 16 bytes"
|
||||
));
|
||||
}
|
||||
parse_hex(hex_str).try_into().map_err(|_| {
|
||||
Error::Specification(format!(
|
||||
"{ctx} hexstring must be 32chars long to cover all 16 bytes"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Tries to convert a BE hex string into a 64 unsigned integer
|
||||
/// The hexstring must *NOT* contain 16 chars of hexdigits, but
|
||||
/// 16 chars at most.
|
||||
///
|
||||
/// * `hex_str` - string to convert can be prepended with "0x"
|
||||
/// * `ctx` - Error context string in case of an error
|
||||
/// ```rust
|
||||
/// # use std::error::Error;
|
||||
/// # use pv::misc::try_parse_u64;
|
||||
/// # fn main() -> Result<(), Box<dyn Error>> {
|
||||
/// let hex = "1234567890abcdef";
|
||||
/// try_parse_u64(&hex, "The test")?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// # Errors
|
||||
/// If `hex_string` is not a 32 byte hex string an Error appears
|
||||
pub fn try_parse_u64(hex_str: &str, ctx: &str) -> Result<u64> {
|
||||
let hex_str = if hex_str.starts_with("0x") {
|
||||
hex_str.split_at(2).1
|
||||
} else {
|
||||
hex_str
|
||||
};
|
||||
if hex_str.len() > 16 {
|
||||
bail_spec!(format!(
|
||||
"{ctx} hexstring {hex_str} must be max 16 chars long"
|
||||
));
|
||||
}
|
||||
Ok(u64::from_str_radix(hex_str, 16)?)
|
||||
}
|
||||
|
||||
/// Open a file.
|
||||
///
|
||||
/// Wraps [`File::open`]
|
||||
///
|
||||
/// * `path` - Path to file
|
||||
pub fn open_file<P: AsRef<Path>>(path: P) -> Result<File> {
|
||||
File::open(&path).map_err(|e| Error::FileAccess {
|
||||
ty: FileAccessErrorType::Open,
|
||||
path: path_to_str!(path).to_string(),
|
||||
source: e,
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a file.
|
||||
///
|
||||
/// Wraps [`File::create`]
|
||||
///
|
||||
/// * `path` - Path to file
|
||||
pub fn create_file<P: AsRef<Path>>(path: P) -> Result<File> {
|
||||
File::create(&path).map_err(|e| Error::FileAccess {
|
||||
ty: FileAccessErrorType::Create,
|
||||
path: path_to_str!(path).to_string(),
|
||||
source: e,
|
||||
})
|
||||
}
|
||||
|
||||
/// Read exactly COUNT bytes into the buffer.
|
||||
///
|
||||
/// * `path` - Path to file
|
||||
/// * `ctx` - Error context string in case of an error
|
||||
///
|
||||
/// # Errors
|
||||
/// If this function encounters an "end of file" before completely filling
|
||||
/// the buffer, it returns an error. The contents of `buf` are unspecified in this case.
|
||||
///
|
||||
/// If any other read error is encountered then this function immediately
|
||||
/// returns. The contents of `buf` are unspecified in this case.
|
||||
///
|
||||
/// If this function returns an error, it is unspecified how many bytes it
|
||||
/// has read, but it will never read more than would be necessary to
|
||||
/// completely fill the buffer.
|
||||
pub fn read_exact_file<P: AsRef<Path>, const COUNT: usize>(
|
||||
path: P,
|
||||
ctx: &str,
|
||||
) -> Result<[u8; COUNT]> {
|
||||
let mut f = std::fs::File::open(&path).map_err(|e| Error::FileAccess {
|
||||
ty: crate::FileAccessErrorType::Open,
|
||||
path: path_to_str!(path).to_string(),
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
if f.metadata()?.len() as usize != COUNT {
|
||||
bail_spec!(format!("{ctx} must be exactly {COUNT} bytes long"));
|
||||
}
|
||||
|
||||
let mut buf = [0; COUNT];
|
||||
f.read_exact(&mut buf)
|
||||
.map_err(|e| file_error!(Read, ctx, path_to_str!(path).to_string(), e))?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// Read content from a file and add context in case of an error
|
||||
///
|
||||
/// * `path` - Path to file
|
||||
/// * `ctx` - Error context string in case of an error
|
||||
///
|
||||
///
|
||||
/// # Errors
|
||||
/// Passes through any kind of error `std::fs::read` produces
|
||||
pub fn read_file<P: AsRef<Path>>(path: P, ctx: &str) -> Result<Vec<u8>> {
|
||||
std::fs::read(&path).map_err(|e| {
|
||||
file_error!(
|
||||
Read,
|
||||
ctx,
|
||||
path.as_ref().to_str().unwrap_or("no UTF-8 path"),
|
||||
e
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads all content from a [`std::io::Read`] and add context in case of an error
|
||||
///
|
||||
/// * `path` - Path to file
|
||||
/// * `ctx` - Error context string in case of an error
|
||||
///
|
||||
///
|
||||
/// # Errors
|
||||
/// Passes through any kind of error `std::fs::write` produces
|
||||
pub fn read<R: Read>(rd: &mut R, path: &str, ctx: &str) -> Result<Vec<u8>> {
|
||||
let mut buf = vec![];
|
||||
rd.read_to_end(&mut buf).map_err(|e| Error::FileIo {
|
||||
ty: FileIoErrorType::Write,
|
||||
ctx: ctx.to_string(),
|
||||
path: path.to_string(),
|
||||
source: e,
|
||||
})?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// write content to a file and add context in case of an error
|
||||
///
|
||||
/// * `path` - Path to file
|
||||
/// * `ctx` - Error context string in case of an error
|
||||
///
|
||||
///
|
||||
/// # Errors
|
||||
/// Passes through any kind of error `std::fs::write` produces
|
||||
pub fn write_file<D: AsRef<[u8]>>(path: &str, data: D, ctx: &str) -> Result<()> {
|
||||
std::fs::write(path, data.as_ref()).map_err(|e| Error::FileIo {
|
||||
ty: FileIoErrorType::Write,
|
||||
ctx: ctx.to_string(),
|
||||
path: path.to_string(),
|
||||
source: e,
|
||||
})
|
||||
}
|
||||
|
||||
/// Write content to a [`std::io::Write`] and add context in case of an error
|
||||
///
|
||||
/// * `path` - Path to file
|
||||
/// * `ctx` - Error context string in case of an error
|
||||
///
|
||||
///
|
||||
/// # Errors
|
||||
/// Passes through any kind of error `std::fs::write` produces
|
||||
pub fn write<D: AsRef<[u8]>, W: Write>(wr: &mut W, data: D, path: &str, ctx: &str) -> Result<()> {
|
||||
wr.write_all(data.as_ref()).map_err(|e| Error::FileIo {
|
||||
ty: FileIoErrorType::Write,
|
||||
ctx: ctx.to_string(),
|
||||
path: path.to_string(),
|
||||
source: e,
|
||||
})
|
||||
}
|
||||
|
||||
/// Read all CRLs from the buffer and parse them into a vector.
|
||||
///
|
||||
@@ -357,9 +11,6 @@ pub fn write<D: AsRef<[u8]>, W: Write>(wr: &mut W, data: D, path: &str, ctx: &st
|
||||
///
|
||||
/// This function will return an error if the underlying openssl implementation cannot parse `buf`
|
||||
/// as `DER` or `PEM`.
|
||||
///
|
||||
/// Requires the `request` feature.
|
||||
#[cfg(feature = "request")]
|
||||
pub fn read_crls(buf: &[u8]) -> Result<Vec<X509Crl>> {
|
||||
use openssl_extensions::crl::StackableX509Crl;
|
||||
X509Crl::from_der(buf)
|
||||
@@ -374,9 +25,6 @@ pub fn read_crls(buf: &[u8]) -> Result<Vec<X509Crl>> {
|
||||
///
|
||||
/// This function will return an error if the underlying openssl implementation cannot parse `buf`
|
||||
/// as `DER` or `PEM`.
|
||||
///
|
||||
/// Requires the `request` feature.
|
||||
#[cfg(feature = "request")]
|
||||
pub fn read_certs(buf: &[u8]) -> Result<Vec<X509>> {
|
||||
X509::from_der(buf)
|
||||
.map(|crt| vec![crt])
|
||||
@@ -384,191 +32,11 @@ pub fn read_certs(buf: &[u8]) -> Result<Vec<X509>> {
|
||||
.map_err(Error::Crypto)
|
||||
}
|
||||
|
||||
macro_rules! usize_to_ui {
|
||||
($(#[$attr:meta])* => $t: ident, $name:ident) => {
|
||||
///Converts an [`usize`] to an [`
|
||||
$(#[$attr])*
|
||||
///`] if possible
|
||||
pub fn $name(u: usize) -> Option<$t> {
|
||||
if u > $t::MAX as usize {
|
||||
None
|
||||
} else {
|
||||
Some(u as $t)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
usize_to_ui! {
|
||||
#[doc = r"u32"]
|
||||
=> u32, to_u32}
|
||||
usize_to_ui! {
|
||||
#[doc = r"u16"]
|
||||
=> u16, to_u16}
|
||||
|
||||
/// Test if both slices contain the exact same bytes.
|
||||
///
|
||||
/// Do not use this to compare cryptographic values (i.e. hashes)
|
||||
pub fn memeq(lhs: &[u8], rhs: &[u8]) -> bool {
|
||||
let size = lhs.len();
|
||||
|
||||
size == rhs.len()
|
||||
&& unsafe {
|
||||
let l = lhs as *const _ as _;
|
||||
let r = rhs as *const _ as _;
|
||||
(l as usize) == (r as usize) || libc::memcmp(l, r, size) == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the hexstring into a byte vector.
|
||||
///
|
||||
/// Stops if the end or until a non hex chat is found
|
||||
pub fn parse_hex(hex_str: &str) -> Vec<u8> {
|
||||
let mut hex_bytes = hex_str.as_bytes().iter().map_while(|b| match b {
|
||||
b'0'..=b'9' => Some(b - b'0'),
|
||||
b'a'..=b'f' => Some(b - b'a' + 10),
|
||||
b'A'..=b'F' => Some(b - b'A' + 10),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
while let (Some(h), Some(l)) = (hex_bytes.next(), hex_bytes.next()) {
|
||||
bytes.push(h << 4 | l)
|
||||
}
|
||||
bytes
|
||||
}
|
||||
/// Report if the `prot_virt_guest` sysfs entry is one.
|
||||
///
|
||||
/// If the entry does not exist returns false.
|
||||
///
|
||||
/// for non-s390-architectures:
|
||||
/// Returns always false
|
||||
/// A non-s390 system cannot be a secure execution guest.
|
||||
#[allow(unreachable_code)]
|
||||
pub fn pv_guest_bit_set() -> bool {
|
||||
#[cfg(not(target_arch = "s390x"))]
|
||||
return false;
|
||||
//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
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::usize;
|
||||
|
||||
use super::*;
|
||||
#[cfg(feature = "request")]
|
||||
use crate::test_utils::*;
|
||||
|
||||
#[test]
|
||||
fn msb_flags() {
|
||||
let v = 17;
|
||||
let v_flag: Msb0Flags64 = v.into();
|
||||
assert_eq!(v, v_flag.0.get());
|
||||
|
||||
let mut v: Msb0Flags64 = 4.into();
|
||||
v.unset_bit(61);
|
||||
assert_eq!(v.0.get(), 0);
|
||||
v.set_bit(61);
|
||||
assert_eq!(4, v.0.get());
|
||||
|
||||
let mut v = Msb0Flags64::default();
|
||||
v.set_bit(0);
|
||||
assert_eq!(&[0x80, 0, 0, 0, 0, 0, 0, 0], v.as_bytes());
|
||||
v.set_bit(0);
|
||||
assert_eq!(&[0x80, 0, 0, 0, 0, 0, 0, 0], v.as_bytes());
|
||||
v.set_bit(1);
|
||||
assert_eq!(&[0xc0, 0, 0, 0, 0, 0, 0, 0], v.as_bytes());
|
||||
v.set_bit(2);
|
||||
assert_eq!(&[0xe0, 0, 0, 0, 0, 0, 0, 0], v.as_bytes());
|
||||
v.set_bit(3);
|
||||
assert_eq!(&[0xf0, 0, 0, 0, 0, 0, 0, 0], v.as_bytes());
|
||||
|
||||
v.unset_bit(3);
|
||||
assert_eq!(&[0xe0, 0, 0, 0, 0, 0, 0, 0], v.as_bytes());
|
||||
v.unset_bit(3);
|
||||
assert_eq!(&[0xe0, 0, 0, 0, 0, 0, 0, 0], v.as_bytes());
|
||||
|
||||
v.set_bit(16);
|
||||
assert_eq!(&[0xe0, 0, 0x80, 0, 0, 0, 0, 0], v.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn msb_flags_set_panic() {
|
||||
Msb0Flags64::default().set_bit(64)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn msb_flags_unset_panic() {
|
||||
Msb0Flags64::default().unset_bit(64)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lsb_flags() {
|
||||
let v = 17;
|
||||
let v_flag: Lsb0Flags64 = v.into();
|
||||
assert_eq!(v, v_flag.0.get());
|
||||
|
||||
let mut v: Lsb0Flags64 = 4.into();
|
||||
v.unset_bit(2);
|
||||
assert_eq!(v.0.get(), 0);
|
||||
v.set_bit(2);
|
||||
assert_eq!(4, v.0.get());
|
||||
|
||||
let mut v = Lsb0Flags64::default();
|
||||
v.set_bit(0);
|
||||
assert_eq!(&[0, 0, 0, 0, 0, 0, 0, 1], v.as_bytes());
|
||||
v.set_bit(0);
|
||||
assert_eq!(&[0, 0, 0, 0, 0, 0, 0, 1], v.as_bytes());
|
||||
v.set_bit(1);
|
||||
assert_eq!(&[0, 0, 0, 0, 0, 0, 0, 3], v.as_bytes());
|
||||
v.set_bit(2);
|
||||
assert_eq!(&[0, 0, 0, 0, 0, 0, 0, 7], v.as_bytes());
|
||||
v.set_bit(3);
|
||||
assert_eq!(&[0, 0, 0, 0, 0, 0, 0, 0xf], v.as_bytes());
|
||||
|
||||
v.unset_bit(3);
|
||||
assert_eq!(&[0, 0, 0, 0, 0, 0, 0, 7], v.as_bytes());
|
||||
v.unset_bit(3);
|
||||
assert_eq!(&[0, 0, 0, 0, 0, 0, 0, 7], v.as_bytes());
|
||||
|
||||
v.set_bit(16);
|
||||
assert_eq!(&[0, 0, 0, 0, 0, 1, 0, 7], v.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn lsb_flags_set_panic() {
|
||||
Lsb0Flags64::default().set_bit(64)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn lsb_flags_unset_panic() {
|
||||
Lsb0Flags64::default().unset_bit(64)
|
||||
}
|
||||
#[test]
|
||||
fn parse_hex() {
|
||||
let s = "123456acbef0";
|
||||
let exp = vec![0x12, 0x34, 0x56, 0xac, 0xbe, 0xf0];
|
||||
assert_eq!(super::parse_hex(s), exp);
|
||||
|
||||
let s = "00123456acbef0";
|
||||
let exp = vec![0, 0x12, 0x34, 0x56, 0xac, 0xbe, 0xf0];
|
||||
assert_eq!(super::parse_hex(s), exp);
|
||||
|
||||
let s = "00123456acbef0ii90";
|
||||
let exp = vec![0, 0x12, 0x34, 0x56, 0xac, 0xbe, 0xf0];
|
||||
assert_eq!(super::parse_hex(s), exp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "request")]
|
||||
fn read_crls() {
|
||||
let crl = get_cert_asset("ibm.crl");
|
||||
let crl_der = get_cert_asset("der.crl");
|
||||
@@ -579,7 +47,6 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "request")]
|
||||
fn read_certs() {
|
||||
let crt = get_cert_asset("ibm.crt");
|
||||
let crt_der = get_cert_asset("der.crt");
|
||||
@@ -588,100 +55,4 @@ mod tests {
|
||||
assert_eq!(super::read_certs(&crt_der).unwrap().len(), 1);
|
||||
assert_eq!(super::read_certs(&fail).unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_u32() {
|
||||
assert_eq!(Some(17), super::to_u32(17));
|
||||
assert_eq!(Some(0), super::to_u32(0));
|
||||
assert_eq!(Some(u32::MAX), super::to_u32(u32::MAX as usize));
|
||||
assert_eq!(None, super::to_u32(u32::MAX as usize + 1));
|
||||
assert_eq!(None, super::to_u32(usize::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_u128() {
|
||||
assert!(matches!(
|
||||
try_parse_u128("123456", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
try_parse_u128("-1234", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
try_parse_u128("0011223344556677889900aabbccddeeff", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
try_parse_u128("dd11223344556677889900aabbccddeeff", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
try_parse_u128("-1223344556677889900aabbccddeeff", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
|
||||
assert!(matches!(
|
||||
try_parse_u128("0x123456", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
try_parse_u128("-0x1234", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
try_parse_u128("0x0011223344556677889900aabbccddeeff", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
try_parse_u128("0xdd11223344556677889900aabbccddeeff", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
try_parse_u128("0x-1223344556677889900aabbccddeeff", ""),
|
||||
Err(Error::Specification(_))
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
[
|
||||
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd,
|
||||
0xee, 0xff
|
||||
],
|
||||
try_parse_u128("11223344556677889900aabbccddeeff", "").unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
[
|
||||
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xaa, 0xbb, 0xcc, 0xdd,
|
||||
0xee, 0xff
|
||||
],
|
||||
try_parse_u128("0x11223344556677889900aabbccddeeff", "").unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
[
|
||||
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
|
||||
0xee, 0xff
|
||||
],
|
||||
try_parse_u128("00112233445566778899aabbccddeeff", "").unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
[
|
||||
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
|
||||
0xee, 0xff
|
||||
],
|
||||
try_parse_u128("00112233445566778899aabbccddeeff", "").unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memeq() {
|
||||
let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
|
||||
let b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1];
|
||||
let c = [0, 0, 1, 2, 3, 4];
|
||||
|
||||
assert!(super::memeq(&a, &a));
|
||||
assert!(super::memeq(&a, &a.clone()));
|
||||
assert!(!super::memeq(&b, &a));
|
||||
assert!(!super::memeq(&b, &c));
|
||||
assert!(!super::memeq(&b, &[]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,212 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
#![allow(non_camel_case_types)]
|
||||
use crate::FileAccessErrorType;
|
||||
use crate::{Error, Result};
|
||||
use libc::c_ulong;
|
||||
use log::debug;
|
||||
use std::convert::TryInto;
|
||||
use std::fs::File;
|
||||
use std::os::unix::prelude::{AsRawFd, RawFd};
|
||||
|
||||
#[cfg(not(test))]
|
||||
use ::libc::ioctl;
|
||||
#[cfg(test)]
|
||||
use test::mock_libc::ioctl;
|
||||
|
||||
/// Contains the rust representation of asm/uvdevice.h
|
||||
/// from kernel version: 6.5 verify
|
||||
mod ffi;
|
||||
mod info;
|
||||
mod test;
|
||||
pub use ffi::uv_ioctl;
|
||||
|
||||
pub use info::UvDeviceInfo;
|
||||
#[allow(dead_code)] //TODO rm when pv learns attestation
|
||||
pub type AttestationUserData = [u8; ffi::UVIO_ATT_USER_DATA_LEN];
|
||||
|
||||
///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
|
||||
///
|
||||
/// Wraps an u64 to set/get individual bits
|
||||
pub type UvFlags = crate::misc::Msb0Flags64;
|
||||
|
||||
/// Fire an ioctl.
|
||||
///
|
||||
/// # Safety:
|
||||
/// Raw fd must point to an open file
|
||||
fn ioctl_raw(raw_fd: RawFd, cmd: c_ulong, cb: &mut IoctlCb) -> Result<()> {
|
||||
debug!("calling unsafe fn wrapper uv::ioctl_raw with {raw_fd:#x?}, {cmd:#x?}, {cb:?}");
|
||||
|
||||
let rc;
|
||||
|
||||
// Get the raw pointer and do an ioctl.
|
||||
//
|
||||
// SAFETY: the passed pointer points to a valid memory region that
|
||||
// contains the expected C-struct. The struct outlives this function.
|
||||
unsafe {
|
||||
rc = ioctl(raw_fd, cmd, cb.as_ptr_mut());
|
||||
}
|
||||
|
||||
debug!("ioctl resulted with {cb:?}");
|
||||
match rc {
|
||||
0 => Ok(()),
|
||||
//NOTE io::Error handles all errnos ioctl uses
|
||||
_ => Err(std::io::Error::last_os_error().into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts UV return codes into human readable error messages
|
||||
fn rc_fmt<C: UvCmd>(rc: u16, rrc: u16, cmd: &mut C) -> &'static str {
|
||||
let s = match (rc, rrc) {
|
||||
(0x0000, _) => Some("invalid rc"),
|
||||
(0x0002, _) => Some("invalid UV command"),
|
||||
(0x0005, _) => Some("request has an invalid size"),
|
||||
(0x0030, _) => Some("home address space control bit has R-bit set to one"),
|
||||
(0x0031, _) => Some("access exception"),
|
||||
(0x0032, _) => Some("request contains virtual address translating to an invalid address"),
|
||||
(UvDevice::RC_MORE_DATA, _) => unreachable!("This is no Error!!!!"),
|
||||
(UvDevice::RC_SUCCESS, _) => unreachable!("This is no Error!!!!"),
|
||||
|
||||
_ => cmd.rc_fmt(rc, rrc),
|
||||
};
|
||||
s.unwrap_or("unexpected error-code")
|
||||
}
|
||||
|
||||
/// Ultravisor Command.
|
||||
pub trait UvCmd {
|
||||
/// Returns the uvdevice IOCTL command that his command uses.
|
||||
///
|
||||
/// # Returns
|
||||
/// The IOCTL cmd for this UvCmd usually sth like `uv_ioctl!(CMD_NR)`
|
||||
fn cmd(&self) -> u64;
|
||||
/// Converts UV return codes into human readable error messages
|
||||
///
|
||||
/// no need to handle `0x0000, 0x0001, 0x0002, 0x0005, 0x0030, 0x0031, 0x0032, 0x0100`
|
||||
fn rc_fmt(&self, rc: u16, rrc: u16) -> Option<&'static str>;
|
||||
/// Returns data used by this command if available.
|
||||
fn data(&mut self) -> Option<&mut [u8]> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// [`UvDevice`] IOCTL control block.
|
||||
#[derive(Debug)]
|
||||
struct IoctlCb(ffi::uvio_ioctl_cb);
|
||||
impl IoctlCb {
|
||||
fn new(data: Option<&mut [u8]>) -> Result<Self> {
|
||||
let (data_raw, data_size) = match data {
|
||||
Some(data) => (
|
||||
data.as_mut_ptr(),
|
||||
data.len()
|
||||
.try_into()
|
||||
.map_err(|_| Error::Specification("passed data too large".to_string()))?,
|
||||
),
|
||||
None => (std::ptr::null_mut(), 0),
|
||||
};
|
||||
|
||||
Ok(Self(ffi::uvio_ioctl_cb {
|
||||
flags: 0,
|
||||
uv_rc: 0,
|
||||
uv_rrc: 0,
|
||||
argument_addr: data_raw as u64,
|
||||
argument_len: data_size,
|
||||
reserved14: [0; 44],
|
||||
}))
|
||||
}
|
||||
|
||||
fn rc(&self) -> u16 {
|
||||
self.0.uv_rc
|
||||
}
|
||||
|
||||
fn rrc(&self) -> u16 {
|
||||
self.0.uv_rrc
|
||||
}
|
||||
|
||||
fn as_ptr_mut(&mut self) -> *mut ffi::uvio_ioctl_cb {
|
||||
&mut self.0 as *mut _
|
||||
}
|
||||
}
|
||||
|
||||
/// The Ultravisor has two codes that represent a successful execution.
|
||||
/// These are represented by this enum.
|
||||
#[repr(u16)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum UvcSuccess {
|
||||
/// Command executed successfully
|
||||
RC_SUCCESS = UvDevice::RC_SUCCESS,
|
||||
/// Command executed successfully, but there is more data available and the buffer was to small
|
||||
/// to hold it all. The returned data is still valid.
|
||||
RC_MORE_DATA = UvDevice::RC_MORE_DATA,
|
||||
}
|
||||
|
||||
/// The UvDevice is a (virtual) device on s390 machines to send Ultravisor commands from userspace.
|
||||
pub struct UvDevice(File);
|
||||
|
||||
impl UvDevice {
|
||||
const RC_SUCCESS: u16 = 0x0001;
|
||||
const RC_MORE_DATA: u16 = 0x0100;
|
||||
const PATH: &'static str = "/dev/uv";
|
||||
|
||||
/// IOCTL number for the info UVC
|
||||
pub const INFO_NR: u8 = ffi::UVIO_IOCTL_UVDEV_INFO_NR;
|
||||
/// IOCTL number for the attestation UVC
|
||||
pub const ATTESTATION_NR: u8 = ffi::UVIO_IOCTL_ATT_NR;
|
||||
/// IOCTL number for the add secret UVC
|
||||
pub const ADD_SECRET_NR: u8 = ffi::UVIO_IOCTL_ADD_SECRET_NR;
|
||||
/// IOCTL number for the list secret UVC
|
||||
pub const LIST_SECRET_NR: u8 = ffi::UVIO_IOCTL_LIST_SECRETS_NR;
|
||||
/// IOCTL number for the lock ksecret UVC
|
||||
pub const LOCK_SECRET_NR: u8 = ffi::UVIO_IOCTL_LOCK_SECRETS_NR;
|
||||
/// Maximum length for add-secret requests
|
||||
pub const ADD_SECRET_MAX_LEN: usize = ffi::UVIO_ADD_SECRET_MAX_LEN;
|
||||
/// Size of the buffer for list secret requests
|
||||
pub const LIST_SECRETS_LEN: usize = ffi::UVIO_LIST_SECRETS_LEN;
|
||||
|
||||
/// Open the uvdevice located at `/dev/uv`
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if the device file cannot be opened.
|
||||
pub fn open() -> Result<Self> {
|
||||
Ok(Self(
|
||||
std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(UvDevice::PATH)
|
||||
.map_err(|e| Error::FileAccess {
|
||||
ty: FileAccessErrorType::Open,
|
||||
path: (UvDevice::PATH).to_string(),
|
||||
source: e,
|
||||
})?,
|
||||
))
|
||||
}
|
||||
|
||||
/// 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
|
||||
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)?;
|
||||
|
||||
match (cb.rc(), cb.rrc()) {
|
||||
(Self::RC_SUCCESS, _) => Ok(UvcSuccess::RC_SUCCESS),
|
||||
(Self::RC_MORE_DATA, _) => Ok(UvcSuccess::RC_MORE_DATA),
|
||||
(rc, rrc) => Err(Error::Uv {
|
||||
rc,
|
||||
rrc,
|
||||
msg: rc_fmt(rc, rrc, cmd),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use crate::{assert_size, static_assert};
|
||||
use zerocopy::{AsBytes, FromBytes};
|
||||
|
||||
pub const UVIO_ATT_ARCB_MAX_LEN: usize = 0x100000;
|
||||
pub const UVIO_ATT_MEASUREMENT_MAX_LEN: usize = 0x8000;
|
||||
pub const UVIO_ATT_ADDITIONAL_MAX_LEN: usize = 0x8000;
|
||||
pub const UVIO_ADD_SECRET_MAX_LEN: usize = 0x100000;
|
||||
pub const UVIO_LIST_SECRETS_LEN: usize = 0x1000;
|
||||
|
||||
// equal to ascii 'u'
|
||||
pub const UVIO_TYPE_UVC: u8 = 117u8;
|
||||
|
||||
pub const UVIO_IOCTL_UVDEV_INFO_NR: u8 = 0;
|
||||
pub const UVIO_IOCTL_ATT_NR: u8 = 1;
|
||||
pub const UVIO_IOCTL_ADD_SECRET_NR: u8 = 2;
|
||||
pub const UVIO_IOCTL_LIST_SECRETS_NR: u8 = 3;
|
||||
pub const UVIO_IOCTL_LOCK_SECRETS_NR: u8 = 4;
|
||||
|
||||
/// Uvdevice IOCTL control block
|
||||
/// Programs can use this struct to communicate with the uvdevice via IOCTLs
|
||||
/// `argument_{addr,len}` specifies in/out data depending on the request
|
||||
///
|
||||
/// 'uv_rc' and `uv_rrc` are the response and reason response codes from the
|
||||
/// Ultravisor.
|
||||
///
|
||||
/// `flags` is currently unused and to be set zero
|
||||
///
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub struct uvio_ioctl_cb {
|
||||
pub flags: u32,
|
||||
pub uv_rc: u16,
|
||||
pub uv_rrc: u16,
|
||||
pub argument_addr: u64,
|
||||
pub argument_len: u32,
|
||||
pub reserved14: [u8; 44usize],
|
||||
}
|
||||
assert_size!(uvio_ioctl_cb, 0x40);
|
||||
|
||||
/// Information of supported functions by the uvdevice
|
||||
///
|
||||
/// * `supp_uvio_cmds` - supported IOCTLs by this device
|
||||
/// * `supp_uv_cmds` - supported UVCs corresponding to the IOCTL
|
||||
///
|
||||
/// UVIO request to get information about supported request types by this
|
||||
/// uvdevice and the Ultravisor.
|
||||
/// Everything is output. Bits are in LSB0 ordering.
|
||||
/// If the bit is set in both, `supp_uvio_cmds` and `supp_uv_cmds`,
|
||||
/// the uvdevice and the Ultravisor support that call.
|
||||
///
|
||||
/// Note that bit 0 (UVIO_IOCTL_UVDEV_INFO_NR) is always zero for `supp_uv_cmds`
|
||||
/// as there is no corresponding UV-call.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone, AsBytes, FromBytes)]
|
||||
pub struct uvio_uvdev_info {
|
||||
pub supp_uvio_cmds: u64,
|
||||
pub supp_uv_cmds: u64,
|
||||
}
|
||||
assert_size!(uvio_uvdev_info, 0x10);
|
||||
|
||||
pub const UVIO_ATT_USER_DATA_LEN: usize = 0x100;
|
||||
pub const UVIO_ATT_UID_LEN: usize = 0x10;
|
||||
|
||||
/// Request Attestation Measurement control block
|
||||
///
|
||||
/// The Attestation Request has two input and two outputs.
|
||||
/// ARCB and User Data are inputs for the UV.
|
||||
/// Measurement and Additional Data are outputs generated by UV.
|
||||
///
|
||||
/// The Attestation Request Control Block (ARCB) is a cryptographically verified
|
||||
/// and secured request to UV and User Data is some plaintext data which is
|
||||
/// going to be included in the Attestation Measurement calculation.
|
||||
///
|
||||
/// Measurement is a cryptographic measurement of the callers properties,
|
||||
/// optional data configured by the ARCB and the user data. If specified by the
|
||||
/// ARCB, UV will add some Additional Data to the measurement calculation.
|
||||
/// This Additional Data is then returned as well.
|
||||
///
|
||||
/// If the Retrieve Attestation Measurement UV facility is not present,
|
||||
/// UV will return invalid command rc.
|
||||
/// Obviously all numbers are in BIG-endian!
|
||||
#[repr(C)]
|
||||
#[derive(Debug, AsBytes, 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_len: u32,
|
||||
pub meas_len: u32,
|
||||
pub add_data_len: u32,
|
||||
pub user_data_len: u16,
|
||||
pub reserved136: u16,
|
||||
}
|
||||
assert_size!(uvio_attest, 0x138);
|
||||
|
||||
#[allow(dead_code)] //TODO rm when pv learns attestation
|
||||
impl uvio_attest {
|
||||
pub const ARCB_MAX_LEN: usize = UVIO_ATT_ARCB_MAX_LEN;
|
||||
pub const MEASUREMENT_MAX_LEN: usize = UVIO_ATT_MEASUREMENT_MAX_LEN;
|
||||
pub const ADDITIONAL_MAX_LEN: usize = UVIO_ATT_ADDITIONAL_MAX_LEN;
|
||||
}
|
||||
|
||||
/// corresponds to the UV_IOCTL macro
|
||||
pub const fn uv_ioctl(nr: u8) -> u64 {
|
||||
iowr(UVIO_TYPE_UVC, nr, std::mem::size_of::<uvio_ioctl_cb>())
|
||||
}
|
||||
static_assert!(uv_ioctl(UVIO_IOCTL_ATT_NR) == 0xc0407501);
|
||||
|
||||
/// corresponds to the __IOWR macro
|
||||
const fn iowr(ty: u8, nr: u8, size: usize) -> u64 {
|
||||
// constants and calculation from linux: asm-generic/ioctl.h
|
||||
const _IOC_WRITE: u32 = 1;
|
||||
const _IOC_READ: u32 = 2;
|
||||
const _IOC_NRSHIFT: u32 = 0;
|
||||
const _IOC_TYPESHIFT: u32 = 8;
|
||||
const _IOC_SIZESHIFT: u32 = 16;
|
||||
const _IOC_DIRSHIFT: u32 = 30;
|
||||
((_IOC_READ | _IOC_WRITE) as u64) << _IOC_DIRSHIFT
|
||||
| ((ty as u64) << _IOC_TYPESHIFT)
|
||||
| ((nr as u64) << _IOC_NRSHIFT)
|
||||
| ((size as u64) << _IOC_SIZESHIFT)
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use super::ffi::uvio_uvdev_info;
|
||||
use crate::{
|
||||
misc::{Flags, Lsb0Flags64},
|
||||
uv::{uv_ioctl, UvCmd, UvDevice},
|
||||
Result,
|
||||
};
|
||||
use std::fmt::Display;
|
||||
use zerocopy::{AsBytes, FromBytes};
|
||||
|
||||
/// Information of supported functions by the uvdevice
|
||||
///
|
||||
/// * `supp_uvio_cmds` - supported IOCTLs by this device
|
||||
/// * `supp_uv_cmds` - supported UVCs corresponding to the IOCTL
|
||||
///
|
||||
/// UVIO request to get information about supported request types by this
|
||||
/// uvdevice and the Ultravisor.
|
||||
/// Everything is output.
|
||||
/// If the bit is set in both, `supp_uvio_cmds` and `supp_uv_cmds`,
|
||||
/// the uvdevice and the Ultravisor support that call.
|
||||
///
|
||||
/// Note that bit 0 ([`UvDevice::INFO_NR`]) is always zero for `supp_uv_cmds`
|
||||
/// as there is no corresponding UV-call.
|
||||
///
|
||||
#[derive(Debug)]
|
||||
pub struct UvDeviceInfo {
|
||||
supp_uvio_cmds: Lsb0Flags64,
|
||||
supp_uv_cmds: Option<Lsb0Flags64>,
|
||||
}
|
||||
|
||||
impl UvDeviceInfo {
|
||||
/// Get information from the uvdevice.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if the ioctl fails and the error code is not
|
||||
/// [`libc::ENOTTY`].
|
||||
/// `ENOTTY` is most likely because the uvdevice does not support the info IOCTL.
|
||||
/// In that case one can safely assume that the device only supports the Attestation IOCTL.
|
||||
/// Therefore this is what this function returns IOCTL support for Attestation and _Data not
|
||||
/// available_ for the UV Attestation facility.
|
||||
/// To check if the Ultravisor supports the Attestation call check at
|
||||
/// `/sys/firmware/uv/query/facilities` and check for bit 28 (Msb0 ordering!)
|
||||
pub fn get(uv: &UvDevice) -> Result<Self> {
|
||||
let mut cmd = uvio_uvdev_info::new_zeroed();
|
||||
match uv.send_cmd(&mut cmd) {
|
||||
Ok(_) => Ok(cmd.into()),
|
||||
Err(crate::Error::Io(e)) if e.raw_os_error() == Some(libc::ENOTTY) => Ok(Self {
|
||||
supp_uvio_cmds: (UvDevice::ATTESTATION_NR as u64).into(),
|
||||
supp_uv_cmds: None,
|
||||
}),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<uvio_uvdev_info> for UvDeviceInfo {
|
||||
fn from(value: uvio_uvdev_info) -> Self {
|
||||
Self {
|
||||
supp_uvio_cmds: value.supp_uvio_cmds.into(),
|
||||
supp_uv_cmds: Some(value.supp_uv_cmds.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UvCmd for uvio_uvdev_info {
|
||||
fn cmd(&self) -> u64 {
|
||||
uv_ioctl(UvDevice::INFO_NR)
|
||||
}
|
||||
|
||||
fn data(&mut self) -> Option<&mut [u8]> {
|
||||
Some(self.as_bytes_mut())
|
||||
}
|
||||
|
||||
fn rc_fmt(&self, _: u16, _: u16) -> Option<&'static str> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn nr_as_string(nr: u8) -> Option<&'static str> {
|
||||
match nr {
|
||||
UvDevice::INFO_NR => Some("Info"),
|
||||
UvDevice::ATTESTATION_NR => Some("Attestation"),
|
||||
UvDevice::ADD_SECRET_NR => Some("Add Secret"),
|
||||
UvDevice::LIST_SECRET_NR => Some("List Secrets"),
|
||||
UvDevice::LOCK_SECRET_NR => Some("Lock Secret Store"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn print_uvdevice_cmd(nr: u8, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match nr_as_string(nr) {
|
||||
Some(s) => write!(f, "{s}"),
|
||||
None => write!(f, "Unknown ({nr})"),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_flags(uv_cmds: &Lsb0Flags64, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let supp_cmds: Vec<_> = (0u8..64)
|
||||
.filter(|v| -> bool { uv_cmds.is_set(*v) })
|
||||
.enumerate()
|
||||
.collect();
|
||||
let num_supp_cmds = supp_cmds.len();
|
||||
if num_supp_cmds == 0 {
|
||||
println!("None");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for (n, cmd) in supp_cmds {
|
||||
print_uvdevice_cmd(cmd, f)?;
|
||||
if n != num_supp_cmds - 1 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
}
|
||||
writeln!(f)
|
||||
}
|
||||
impl Display for UvDeviceInfo {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "uvdevice supports:")?;
|
||||
parse_flags(&self.supp_uvio_cmds, f)?;
|
||||
writeln!(f, "Ultravisor-calls available:")?;
|
||||
match &self.supp_uv_cmds {
|
||||
Some(cmds) => parse_flags(cmds, f),
|
||||
None => writeln!(f, "Data not available"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,231 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
#![cfg(test)]
|
||||
|
||||
use std::{
|
||||
os::unix::prelude::FromRawFd,
|
||||
sync::{Mutex, MutexGuard},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
lazy_static! {
|
||||
/// needed to serialize all tests as tests operate on static data required by the mock
|
||||
static ref TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
/// exists to have a lazy static mod variable
|
||||
static ref IOCTL_MTX: Mutex<IoctlCtx> = Mutex::new(IoctlCtx::new());
|
||||
}
|
||||
|
||||
fn get_lock<T>(m: &'static Mutex<T>) -> MutexGuard<'static, T> {
|
||||
match m.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
struct IoctlCtx {
|
||||
modify: Box<dyn FnMut(&mut ffi::uvio_ioctl_cb) -> i32 + Send + Sync>,
|
||||
exp_cmd: ::libc::c_ulong,
|
||||
called: bool,
|
||||
}
|
||||
|
||||
impl IoctlCtx {
|
||||
pub fn exp_cmd(&mut self, cmd: ::libc::c_ulong) -> &mut Self {
|
||||
self.exp_cmd = cmd;
|
||||
self
|
||||
}
|
||||
pub fn set_mdfy<F>(&mut self, mdfy: F) -> &mut Self
|
||||
where
|
||||
F: FnMut(&mut ffi::uvio_ioctl_cb) -> ::libc::c_int + 'static + Send + Sync,
|
||||
{
|
||||
self.modify = Box::new(mdfy);
|
||||
self
|
||||
}
|
||||
pub fn reset(&mut self) -> bool {
|
||||
let old = self.called;
|
||||
self.called = false;
|
||||
old
|
||||
}
|
||||
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
modify: Box::new(|_| -1),
|
||||
exp_cmd: 0,
|
||||
called: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod mock_libc {
|
||||
use super::*;
|
||||
|
||||
pub unsafe fn ioctl(
|
||||
fd: ::libc::c_int,
|
||||
cmd: ::libc::c_ulong,
|
||||
data: *mut ffi::uvio_ioctl_cb,
|
||||
) -> ::libc::c_int {
|
||||
let mut ctx = get_lock(&IOCTL_MTX);
|
||||
assert!(!ctx.called, "IOCTL called more than once");
|
||||
ctx.called = true;
|
||||
|
||||
assert_eq!(cmd, ctx.exp_cmd, "IOCTL cmd mismatch");
|
||||
assert_eq!(fd, 17, "IOCTL fd mismatch");
|
||||
|
||||
let data_ref: &mut ffi::uvio_ioctl_cb = &mut *data;
|
||||
|
||||
(ctx.modify)(data_ref)
|
||||
}
|
||||
}
|
||||
|
||||
impl ffi::uvio_ioctl_cb {
|
||||
fn addr_eq(&self, exp: u64) -> &Self {
|
||||
assert_eq!(
|
||||
self.argument_addr, exp,
|
||||
"ioctl arg addr not eq: {} == {}",
|
||||
self.argument_addr, exp
|
||||
);
|
||||
self
|
||||
}
|
||||
fn size_eq(&self, exp: u32) -> &Self {
|
||||
assert_eq!(
|
||||
self.argument_len, exp,
|
||||
"ioctl arg len not eq: {} == {}",
|
||||
self.argument_len, exp
|
||||
);
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
const TEST_CMD: u64 = 17;
|
||||
struct TestCmd(Option<Vec<u8>>);
|
||||
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,
|
||||
Some(d) => Some(d.as_mut_slice()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UvDevice {
|
||||
///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 { std::fs::File::from_raw_fd(17) })
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ioctl_fail() {
|
||||
let _m = get_lock(&TEST_LOCK);
|
||||
|
||||
let mut mock_cmd = TestCmd(None);
|
||||
|
||||
get_lock(&IOCTL_MTX).exp_cmd(TEST_CMD).set_mdfy(|_| -1);
|
||||
|
||||
let uv = UvDevice::test_dev();
|
||||
|
||||
let res = uv.send_cmd(&mut mock_cmd);
|
||||
assert!(get_lock(&IOCTL_MTX).reset(), "IOCTL was never called");
|
||||
assert!(matches!(res, Err(Error::Io(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ioctl_simpleo() {
|
||||
let _m = get_lock(&TEST_LOCK);
|
||||
|
||||
let mut mock_cmd = TestCmd(None);
|
||||
|
||||
get_lock(&IOCTL_MTX).exp_cmd(TEST_CMD).set_mdfy(|cb| {
|
||||
cb.set_rc(1).addr_eq(0).size_eq(0);
|
||||
0
|
||||
});
|
||||
|
||||
let uv = UvDevice::test_dev();
|
||||
let res = uv.send_cmd(&mut mock_cmd);
|
||||
assert!(get_lock(&IOCTL_MTX).reset(), "IOCTL was never called");
|
||||
assert!(res.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ioctl_simple_err() {
|
||||
let _m = get_lock(&TEST_LOCK);
|
||||
|
||||
let mut mock_cmd = TestCmd(None);
|
||||
|
||||
get_lock(&IOCTL_MTX).exp_cmd(TEST_CMD).set_mdfy(|cb| {
|
||||
cb.set_rc(17).set_rrc(3).addr_eq(0).size_eq(0);
|
||||
0
|
||||
});
|
||||
|
||||
let uv = UvDevice::test_dev();
|
||||
let res = uv.send_cmd(&mut mock_cmd);
|
||||
assert!(get_lock(&IOCTL_MTX).reset(), "IOCTL was never called");
|
||||
assert!(matches!(res, Err(Error::Uv{rc, rrc, ..}) if rc == 17 && rrc == 3 ));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ioctl_write_data() {
|
||||
let _m = get_lock(&TEST_LOCK);
|
||||
|
||||
let cmd_data = vec![0u8; 32];
|
||||
let cmd_data_len = cmd_data.len();
|
||||
let data_addr = cmd_data.as_ptr() as u64;
|
||||
|
||||
let mut mock_cmd = TestCmd(Some(cmd_data));
|
||||
|
||||
get_lock(&IOCTL_MTX).exp_cmd(TEST_CMD).set_mdfy(move |cb| {
|
||||
cb.set_rc(1).addr_eq(data_addr).size_eq(32);
|
||||
unsafe {
|
||||
::libc::memset(cb.argument_addr as *mut ::libc::c_void, 0x42, cmd_data_len);
|
||||
}
|
||||
0
|
||||
});
|
||||
|
||||
let uv = UvDevice::test_dev();
|
||||
let res = uv.send_cmd(&mut mock_cmd);
|
||||
assert!(get_lock(&IOCTL_MTX).reset(), "IOCTL was never called");
|
||||
assert_eq!(res.unwrap(), UvcSuccess::RC_SUCCESS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ioctl_read_data() {
|
||||
let _m = get_lock(&TEST_LOCK);
|
||||
|
||||
let cmd_data = vec![42u8; 32];
|
||||
let cmd_data_len = cmd_data.len();
|
||||
let data_addr = cmd_data.as_ptr() as u64;
|
||||
let data_exp = cmd_data.clone();
|
||||
|
||||
let mut mock_cmd = TestCmd(Some(cmd_data));
|
||||
|
||||
get_lock(&IOCTL_MTX).exp_cmd(TEST_CMD).set_mdfy(move |cb| {
|
||||
cb.set_rc(1).addr_eq(data_addr).size_eq(32);
|
||||
unsafe {
|
||||
let data = std::slice::from_raw_parts(cb.argument_addr as *const u8, cmd_data_len);
|
||||
assert_eq!(data, data_exp);
|
||||
}
|
||||
0
|
||||
});
|
||||
|
||||
let uv = UvDevice::test_dev();
|
||||
let res = uv.send_cmd(&mut mock_cmd);
|
||||
assert!(get_lock(&IOCTL_MTX).reset(), "IOCTL was never called");
|
||||
assert_eq!(res.unwrap(), UvcSuccess::RC_SUCCESS);
|
||||
}
|
||||
@@ -2,79 +2,11 @@
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
#![cfg(feature = "uvsecret")]
|
||||
//! Provides functionality to manage the UV secret store.
|
||||
//!
|
||||
//! Provides functionality to build `add-secret` requests.
|
||||
//! Also provides interfaces, to dispatch `Add Secret`, `Lock Secret Store`,
|
||||
//! and `List Secrets` requests,
|
||||
#[cfg(feature = "request")]
|
||||
pub mod asrcb;
|
||||
#[cfg(feature = "request")]
|
||||
pub mod ext_secret;
|
||||
#[cfg(feature = "request")]
|
||||
pub mod guest_secret;
|
||||
pub mod secret_list;
|
||||
pub mod uvc;
|
||||
|
||||
use crate::request::MagicValue;
|
||||
use crate::requires_feat;
|
||||
|
||||
#[allow(unused_imports)] //used for more convenient docstring
|
||||
use asrcb::AddSecretRequest;
|
||||
/// Types of (non architectured) user data for [`AddSecretRequest`]
|
||||
///
|
||||
#[doc = requires_feat!(uvsecret)]
|
||||
#[repr(u16)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, zerocopy::AsBytes)]
|
||||
pub enum UserDataType {
|
||||
/// Marker that the request does not contain any user data
|
||||
Null = 0x0000,
|
||||
}
|
||||
|
||||
/// The magic value used to identify an [`AddSecretRequest`]
|
||||
///
|
||||
/// The magic value is ASCII:
|
||||
/// ```rust
|
||||
/// # use pv::request::uvsecret::AddSecretMagic;
|
||||
/// # use pv::request::MagicValue;
|
||||
/// # fn main() {
|
||||
/// # let magic =
|
||||
/// # b"asrcbM"
|
||||
/// # ;
|
||||
/// # assert!(AddSecretMagic::starts_with_magic(magic));
|
||||
/// # }
|
||||
///```
|
||||
///
|
||||
#[doc = requires_feat!(uvsecret)]
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, zerocopy::AsBytes)]
|
||||
pub struct AddSecretMagic {
|
||||
magic: [u8; 6], // [0x61, 0x73, 0x72, 0x63, 0x62, 0x4D]
|
||||
tp: UserDataType,
|
||||
}
|
||||
|
||||
impl MagicValue<6> for AddSecretMagic {
|
||||
// "asrcbM"
|
||||
const MAGIC: [u8; 6] = [0x61, 0x73, 0x72, 0x63, 0x62, 0x4D];
|
||||
}
|
||||
|
||||
impl From<UserDataType> for AddSecretMagic {
|
||||
fn from(tp: UserDataType) -> Self {
|
||||
Self {
|
||||
magic: Self::MAGIC,
|
||||
tp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SECRET_ID_SIZE: usize = 32;
|
||||
fn ser_gsid<S>(id: &[u8; SECRET_ID_SIZE], ser: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let mut s = String::with_capacity(32 * 2 + 2);
|
||||
s.push_str("0x");
|
||||
let s = id.iter().fold(s, |acc, e| acc + &format!("{e:02x}"));
|
||||
ser.serialize_str(&s)
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use super::{AddSecretMagic, UserDataType};
|
||||
use crate::requires_feat;
|
||||
use crate::{
|
||||
assert_size,
|
||||
misc::Flags,
|
||||
@@ -14,11 +12,15 @@ use crate::{
|
||||
Md,
|
||||
},
|
||||
uvsecret::{ExtSecret, GuestSecret},
|
||||
Aad, BootHdrTags, Keyslot, ReqEncrCtx, Request, RequestVersion, Secret,
|
||||
Aad, BootHdrTags, Keyslot, ReqEncrCtx, Request, Secret,
|
||||
},
|
||||
uv::{ConfigUid, UvFlags},
|
||||
Result,
|
||||
};
|
||||
use pv_core::request::{
|
||||
uvsecret::{AddSecretMagic, UserDataType},
|
||||
RequestVersion,
|
||||
};
|
||||
use zerocopy::AsBytes;
|
||||
|
||||
/// Internal wrapper for Guest Secret, so that we can dump it in the form the UV wants it to be
|
||||
@@ -96,8 +98,6 @@ impl ReqConfData {
|
||||
}
|
||||
|
||||
/// Flags for [`AddSecretRequest`]
|
||||
///
|
||||
#[doc = requires_feat!(reqsecret)]
|
||||
#[derive(Default, Clone, Copy, Debug)]
|
||||
pub struct AddSecretFlags(UvFlags);
|
||||
impl AddSecretFlags {
|
||||
@@ -123,8 +123,6 @@ impl From<AddSecretFlags> for UvFlags {
|
||||
}
|
||||
|
||||
/// Versions for [`AddSecretRequest`]
|
||||
///
|
||||
#[doc = requires_feat!(reqsecret)]
|
||||
#[repr(u32)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AddSecretVersion {
|
||||
@@ -143,12 +141,6 @@ impl From<AddSecretVersion> for RequestVersion {
|
||||
}
|
||||
}
|
||||
|
||||
impl AddSecretMagic {
|
||||
fn get(&self) -> crate::request::RequestMagic {
|
||||
self.as_bytes().try_into().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// Add-secret request Control Block
|
||||
///
|
||||
/// An ASRCB wraps a secret to transport it securely to the Ultravisor.
|
||||
@@ -173,8 +165,6 @@ impl AddSecretMagic {
|
||||
/// | AES GCM Tag (16) |
|
||||
/// |_____________________________________________________________|
|
||||
///```
|
||||
///
|
||||
#[doc = requires_feat!(reqsecret)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AddSecretRequest {
|
||||
magic: AddSecretMagic,
|
||||
@@ -249,7 +239,11 @@ impl AddSecretRequest {
|
||||
self.keyslots.iter().for_each(|k| aad.push(Aad::Ks(k)));
|
||||
aad.push(Aad::Plain(&secr_auth));
|
||||
|
||||
ctx.build_aad(self.version.into(), &aad, conf_len, self.magic.get())
|
||||
ctx.build_aad(self.version.into(), &aad, conf_len, self.magic())
|
||||
}
|
||||
|
||||
fn magic(&self) -> crate::request::RequestMagic {
|
||||
self.magic.as_bytes().try_into().unwrap()
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
|
||||
@@ -2,11 +2,9 @@
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use crate::{request::Secret, requires_feat};
|
||||
use crate::request::Secret;
|
||||
|
||||
/// Extension Secret for [`crate::request::uvsecret::AddSecretRequest`]
|
||||
///
|
||||
#[doc = requires_feat!(reqsecret)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ExtSecret {
|
||||
/// A bytepattern that must be equal for each request targeting the same SE-guest instance
|
||||
|
||||
@@ -4,18 +4,16 @@
|
||||
|
||||
#[allow(unused_imports)] //used for more convenient docstring
|
||||
use super::asrcb::AddSecretRequest;
|
||||
use super::{ser_gsid, SECRET_ID_SIZE};
|
||||
use crate::{
|
||||
request::{hash, openssl::MessageDigest, random_array, Secret},
|
||||
requires_feat, Result,
|
||||
Result,
|
||||
};
|
||||
use pv_core::for_pv::{ser_gsid, SECRET_ID_SIZE};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::convert::TryInto;
|
||||
|
||||
const SECRET_SIZE: usize = 32;
|
||||
/// A Secret to be added in [`AddSecretRequest`]
|
||||
///
|
||||
#[doc = requires_feat!(reqsecret)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum GuestSecret {
|
||||
/// No guest secret
|
||||
|
||||
@@ -1,356 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use crate::{assert_size, misc::to_u16, uv::ListCmd, uvdevice::UvCmd, Error, Result};
|
||||
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
|
||||
use serde::{Serialize, Serializer};
|
||||
use std::{
|
||||
fmt::Display,
|
||||
io::{Cursor, Read, Seek, Write},
|
||||
slice::Iter,
|
||||
vec::IntoIter,
|
||||
};
|
||||
use zerocopy::{AsBytes, FromBytes, U16, U32};
|
||||
|
||||
use super::ser_gsid;
|
||||
|
||||
/// List of secrets used to parse the [`crate::uv::ListCmd`] result
|
||||
///
|
||||
/// Requires the `uvsecret` feature.
|
||||
#[derive(Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct SecretList {
|
||||
total_num_secrets: usize,
|
||||
secrets: Vec<SecretEntry>,
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a SecretList {
|
||||
type Item = &'a SecretEntry;
|
||||
type IntoIter = Iter<'a, SecretEntry>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoIterator for SecretList {
|
||||
type Item = SecretEntry;
|
||||
type IntoIter = IntoIter<Self::Item>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.secrets.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<SecretEntry> for SecretList {
|
||||
fn from_iter<T: IntoIterator<Item = SecretEntry>>(iter: T) -> Self {
|
||||
let secrets: Vec<_> = iter.into_iter().collect();
|
||||
let total_num_secrets = secrets.len() as u16;
|
||||
Self::new(total_num_secrets, secrets)
|
||||
}
|
||||
}
|
||||
|
||||
impl SecretList {
|
||||
#[doc(hidden)]
|
||||
/// For testing purposes.
|
||||
pub fn new(total_num_secrets: u16, secrets: Vec<SecretEntry>) -> Self {
|
||||
Self {
|
||||
total_num_secrets: total_num_secrets as usize,
|
||||
secrets,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an iterator over the slice.
|
||||
///
|
||||
/// The iterator yields all secret entries from start to end.
|
||||
pub fn iter(&self) -> Iter<'_, SecretEntry> {
|
||||
self.secrets.iter()
|
||||
}
|
||||
|
||||
/// Returns the length of this [`SecretList`].
|
||||
pub fn len(&self) -> usize {
|
||||
self.secrets.len()
|
||||
}
|
||||
|
||||
/// Check for is_empty of this [`SecretList`].
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.secrets.is_empty()
|
||||
}
|
||||
|
||||
/// Reports the number of secrets stored in UV
|
||||
///
|
||||
/// This number may be not equal to the provided number of [`SecretEntry`]
|
||||
pub fn total_num_secrets(&self) -> usize {
|
||||
self.total_num_secrets
|
||||
}
|
||||
|
||||
/// Encodes the list in the same binary format the UV would do
|
||||
pub fn encode<T: Write>(&self, w: &mut T) -> Result<()> {
|
||||
let num_s = to_u16(self.secrets.len()).ok_or(Error::ManySecrets)?;
|
||||
w.write_u16::<BigEndian>(num_s)?;
|
||||
w.write_u16::<BigEndian>(
|
||||
self.total_num_secrets
|
||||
.try_into()
|
||||
.map_err(|_| Error::ManySecrets)?,
|
||||
)?;
|
||||
w.write_all(&[0u8; 12])?;
|
||||
for secret in &self.secrets {
|
||||
w.write_all(secret.as_bytes())?;
|
||||
}
|
||||
w.flush().map_err(Error::Io)
|
||||
}
|
||||
|
||||
/// Decodes the list from the binary format of the UV into this internal representation
|
||||
pub fn decode<R: Read + Seek>(r: &mut R) -> std::io::Result<Self> {
|
||||
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
|
||||
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
|
||||
let secr = SecretEntry::read_from(buf.as_slice()).unwrap();
|
||||
v.push(secr);
|
||||
}
|
||||
Ok(Self {
|
||||
total_num_secrets,
|
||||
secrets: v,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for SecretList {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
writeln!(f, "Total number of secrets: {}", self.total_num_secrets)?;
|
||||
if !self.secrets.is_empty() {
|
||||
writeln!(f)?;
|
||||
}
|
||||
for s in &self.secrets {
|
||||
writeln!(f, "{s}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn ser_u32<S: Serializer>(v: &U32<BigEndian>, ser: S) -> Result<S::Ok, S::Error> {
|
||||
ser.serialize_u32(v.get())
|
||||
}
|
||||
|
||||
fn ser_u16<S: Serializer>(v: &U16<BigEndian>, ser: S) -> Result<S::Ok, S::Error> {
|
||||
ser.serialize_u16(v.get())
|
||||
}
|
||||
|
||||
/// Secret types that can appear in a [`SecretList`]
|
||||
#[non_exhaustive]
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub enum ListableSecretType {
|
||||
/// Association Secret
|
||||
Association,
|
||||
/// Invalid secret type, that should never appear in a list
|
||||
///
|
||||
/// 0 is reserved
|
||||
/// 1 is Null secret, with no id and not listable
|
||||
Invalid(u16),
|
||||
/// Unknown secret type
|
||||
Unknown(u16),
|
||||
}
|
||||
impl ListableSecretType {
|
||||
const RESERVED_0: u16 = 0x0000;
|
||||
const NULL: u16 = 0x0001;
|
||||
const ASSOCIATION: u16 = 0x0002;
|
||||
}
|
||||
|
||||
impl Display for ListableSecretType {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Association => write!(f, "Association"),
|
||||
Self::Invalid(n) => write!(f, "Invalid({n})"),
|
||||
Self::Unknown(n) => write!(f, "Unknown({n})"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<U16<BigEndian>> for ListableSecretType {
|
||||
fn from(value: U16<BigEndian>) -> Self {
|
||||
match value.get() {
|
||||
Self::RESERVED_0 => Self::Invalid(Self::RESERVED_0),
|
||||
Self::NULL => Self::Invalid(Self::NULL),
|
||||
Self::ASSOCIATION => ListableSecretType::Association,
|
||||
n => Self::Unknown(n),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ListableSecretType> for U16<BigEndian> {
|
||||
fn from(value: ListableSecretType) -> Self {
|
||||
match value {
|
||||
ListableSecretType::Association => ListableSecretType::ASSOCIATION,
|
||||
ListableSecretType::Invalid(n) | ListableSecretType::Unknown(n) => n,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// A secret in a [`SecretList`]
|
||||
#[repr(C)]
|
||||
#[derive(Debug, PartialEq, Eq, AsBytes, FromBytes, Serialize)]
|
||||
pub struct SecretEntry {
|
||||
#[serde(serialize_with = "ser_u16")]
|
||||
index: U16<BigEndian>,
|
||||
#[serde(serialize_with = "ser_u16")]
|
||||
stype: U16<BigEndian>,
|
||||
#[serde(serialize_with = "ser_u32")]
|
||||
len: U32<BigEndian>,
|
||||
#[serde(skip)]
|
||||
res_8: u64,
|
||||
#[serde(serialize_with = "ser_gsid")]
|
||||
id: [u8; 32],
|
||||
}
|
||||
assert_size!(SecretEntry, SecretEntry::STRUCT_SIZE);
|
||||
|
||||
impl SecretEntry {
|
||||
const STRUCT_SIZE: usize = 0x30;
|
||||
|
||||
#[doc(hidden)]
|
||||
/// For testing purposes.
|
||||
pub fn new(index: u16, stype: ListableSecretType, id: [u8; 32], secret_len: u32) -> Self {
|
||||
Self {
|
||||
index: index.into(),
|
||||
stype: stype.into(),
|
||||
len: secret_len.into(),
|
||||
res_8: 0,
|
||||
id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the index of this [`SecretEntry`].
|
||||
pub fn index(&self) -> u16 {
|
||||
self.index.get()
|
||||
}
|
||||
|
||||
/// Returns the secret type of this [`SecretEntry`].
|
||||
pub fn stype(&self) -> ListableSecretType {
|
||||
self.stype.into()
|
||||
}
|
||||
|
||||
/// Returns a reference to the id of this [`SecretEntry`].
|
||||
pub fn id(&self) -> &[u8] {
|
||||
&self.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for SecretEntry {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let stype: ListableSecretType = self.stype.into();
|
||||
writeln!(f, "{} {}:", self.index, stype)?;
|
||||
write!(f, " ")?;
|
||||
for b in self.id {
|
||||
write!(f, "{b:02x}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use std::io::{BufReader, BufWriter, Cursor};
|
||||
|
||||
#[test]
|
||||
fn dump_secret_entry() {
|
||||
const EXP: &[u8] = &[
|
||||
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,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
];
|
||||
let s = SecretEntry {
|
||||
index: 1.into(),
|
||||
stype: 2.into(),
|
||||
len: 32.into(),
|
||||
res_8: 0,
|
||||
id: [0; 32],
|
||||
};
|
||||
|
||||
assert_eq!(s.as_bytes(), EXP);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secret_list_dec() {
|
||||
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
|
||||
// secret
|
||||
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,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
];
|
||||
|
||||
let exp = SecretList {
|
||||
total_num_secrets: 0x112,
|
||||
secrets: vec![SecretEntry {
|
||||
index: 1.into(),
|
||||
stype: 2.into(),
|
||||
len: 32.into(),
|
||||
res_8: 0,
|
||||
id: [0; 32],
|
||||
}],
|
||||
};
|
||||
|
||||
let mut br = BufReader::new(Cursor::new(buf));
|
||||
let sl = SecretList::decode(&mut br).unwrap();
|
||||
assert_eq!(sl, exp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secret_list_enc() {
|
||||
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
|
||||
// secret
|
||||
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,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
];
|
||||
|
||||
let sl = SecretList {
|
||||
total_num_secrets: 0x112,
|
||||
secrets: vec![SecretEntry {
|
||||
index: 1.into(),
|
||||
stype: 2.into(),
|
||||
len: 32.into(),
|
||||
res_8: 0,
|
||||
id: [0; 32],
|
||||
}],
|
||||
};
|
||||
|
||||
let mut buf = [0u8; 0x40];
|
||||
{
|
||||
let mut bw = BufWriter::new(&mut buf[..]);
|
||||
sl.encode(&mut bw).unwrap();
|
||||
}
|
||||
println!("list: {sl:?}");
|
||||
assert_eq!(buf, EXP);
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,12 @@
|
||||
//
|
||||
// Copyright IBM Corp. 2023
|
||||
|
||||
use super::AddSecretMagic;
|
||||
use crate::{
|
||||
request::MagicValue,
|
||||
requires_feat,
|
||||
uv::{uv_ioctl, UvCmd, UvDevice},
|
||||
Error, Result, PAGESIZE,
|
||||
};
|
||||
use pv_core::request::{uvsecret::AddSecretMagic, MagicValue};
|
||||
use std::io::Read;
|
||||
use std::usize;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user