use core::fmt;
use crate::module::{Fingerprint, IntegrityStatus, Profile};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Site {
AeadDecrypt,
SignatureVerify,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
NotOperational,
SelfTestFailed,
ConditionalTestFailed,
AlreadyInitialized,
InvalidInput,
AlgorithmRestricted,
NotImplemented,
Uninstantiated,
ReseedRequired,
NullPointer,
BufferTooSmall,
OutputTooLong,
NotBlockAligned,
InvalidIvLength,
TagMismatch,
LengthMismatch,
InvalidNonceLength,
InvalidTagLength,
InvalidPayloadLength,
InvalidAadLength,
IntegrityUnverified,
EntropyInputTooShort,
NonceTooShort,
Internal,
SignatureInvalid,
Unknown(i32),
LibraryAbi {
library: i32,
crate_: i32,
},
LibraryVersion {
library: Option<String>,
crate_: &'static str,
},
ProfileMismatch {
active: Profile,
requested: Profile,
},
KeyFingerprint {
found: Fingerprint,
expected: Fingerprint,
},
}
impl Error {
#[must_use]
pub fn from_code(code: i32, site: Site) -> Self {
match code {
1 => Self::NotOperational,
2 => Self::SelfTestFailed,
3 => Self::ConditionalTestFailed,
4 => Self::AlreadyInitialized,
5 => Self::InvalidInput,
6 => Self::AlgorithmRestricted,
7 => Self::NotImplemented,
8 => Self::Uninstantiated,
9 => Self::ReseedRequired,
10 => Self::NullPointer,
11 => Self::BufferTooSmall,
12 => Self::OutputTooLong,
20 => Self::NotBlockAligned,
21 => Self::InvalidIvLength,
22 => match site {
Site::SignatureVerify => Self::SignatureInvalid,
Site::AeadDecrypt | Site::Other => Self::TagMismatch,
},
23 => Self::LengthMismatch,
24 => Self::InvalidNonceLength,
25 => Self::InvalidTagLength,
26 => Self::InvalidPayloadLength,
27 => Self::InvalidAadLength,
28 => Self::IntegrityUnverified,
29 => Self::EntropyInputTooShort,
30 => Self::NonceTooShort,
255 => Self::Internal,
other => Self::Unknown(other),
}
}
}
pub(crate) fn status(code: core::ffi::c_int, site: Site) -> Result<(), Error> {
if code == 0 {
Ok(())
} else {
Err(Error::from_code(code, site))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotOperational => f.write_str("module not in the operational state"),
Self::SelfTestFailed => f.write_str("power-up self-test failed during initialisation"),
Self::ConditionalTestFailed => {
f.write_str("conditional self-test failed during operation")
}
Self::AlreadyInitialized => f.write_str("initialisation requested more than once"),
Self::InvalidInput => f.write_str("invalid input"),
Self::AlgorithmRestricted => {
f.write_str("service blocked by the active algorithm profile")
}
Self::NotImplemented => f.write_str("service not implemented"),
Self::Uninstantiated => f.write_str("DRBG used before it was instantiated"),
Self::ReseedRequired => f.write_str("DRBG must be reseeded before it generates more"),
Self::NullPointer => f.write_str("a required pointer was null"),
Self::BufferTooSmall => {
f.write_str("output buffer smaller than the documented minimum")
}
Self::OutputTooLong => f.write_str("output bound exceeded"),
Self::NotBlockAligned => f.write_str("input not aligned to the cipher block size"),
Self::InvalidIvLength => f.write_str("IV length does not match the mode"),
Self::TagMismatch => f.write_str("authentication tag did not verify"),
Self::LengthMismatch => f.write_str("input and output buffer lengths differ"),
Self::InvalidNonceLength => f.write_str("nonce length does not match the mode"),
Self::InvalidTagLength => f.write_str("tag length does not match the mode"),
Self::InvalidPayloadLength => f.write_str("payload length exceeds the mode's maximum"),
Self::InvalidAadLength => f.write_str("AAD length exceeds the mode's maximum"),
Self::IntegrityUnverified => {
f.write_str("module initialised without the software integrity test")
}
Self::EntropyInputTooShort => {
f.write_str("entropy input shorter than the DRBG's security strength")
}
Self::NonceTooShort => {
f.write_str("nonce shorter than half the DRBG's security strength")
}
Self::Internal => f.write_str("internal error in the library"),
Self::SignatureInvalid => f.write_str("signature did not verify"),
Self::Unknown(code) => write!(f, "unknown status code {code}"),
Self::LibraryAbi { library, crate_ } => {
write!(f, "library ABI {library} is not the binding's ABI {crate_}")
}
Self::LibraryVersion { library, crate_ } => match library {
Some(v) => write!(
f,
"library version {v} does not match the binding's version {crate_}"
),
None => write!(
f,
"library manifest states no version; the binding requires {crate_}"
),
},
Self::ProfileMismatch { active, requested } => write!(
f,
"library is initialised with profile {active:?}, not the requested {requested:?}"
),
Self::KeyFingerprint { found, expected } => write!(
f,
"library embeds verifying key {found}, not the pinned {expected}"
),
}
}
}
impl std::error::Error for Error {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitError {
pub code: Error,
pub integrity: Option<IntegrityStatus>,
pub detail: Result<Option<String>, DetailError>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DetailError {
Sizing(Error),
TooLong {
needed: usize,
},
Read(Error),
Overrun {
written: usize,
capacity: usize,
},
}
impl fmt::Display for DetailError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Sizing(e) => write!(f, "sizing the detail text failed: {e}"),
Self::TooLong { needed } => write!(f, "detail text of {needed} bytes not read"),
Self::Read(e) => write!(f, "reading the detail text failed: {e}"),
Self::Overrun { written, capacity } => write!(
f,
"library reported {written} bytes written into {capacity}"
),
}
}
}
impl std::error::Error for DetailError {}
impl fmt::Display for InitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.code)?;
if let Some(integrity) = self.integrity {
write!(f, " (integrity test: {integrity:?})")?;
}
match &self.detail {
Ok(Some(detail)) => write!(f, ": {detail}"),
Ok(None) => Ok(()),
Err(e) => write!(f, " ({e})"),
}
}
}
impl std::error::Error for InitError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.code)
}
}