use core::ffi::{CStr, c_int};
use core::fmt;
use std::sync::OnceLock;
use crate::error::{DetailError, Error, InitError, Site, status};
use crate::sys;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Profile {
Unrestricted,
Cnsa2,
Cnsa1,
Migration,
Unknown(i32),
}
impl Profile {
#[must_use]
pub const fn code(self) -> i32 {
match self {
Self::Unrestricted => 0,
Self::Cnsa2 => 1,
Self::Cnsa1 => 2,
Self::Migration => 3,
Self::Unknown(code) => code,
}
}
#[must_use]
pub const fn from_code(code: i32) -> Self {
match code {
0 => Self::Unrestricted,
1 => Self::Cnsa2,
2 => Self::Cnsa1,
3 => Self::Migration,
other => Self::Unknown(other),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum IntegrityStatus {
NotRun,
Passed,
SignatureInvalid,
SlotInvalid,
Unreadable,
CastNotRun,
UnknownRecord,
Refused,
NoVerifyKey,
KeyMismatch,
SlotDamaged,
Unknown(i32),
}
impl IntegrityStatus {
#[must_use]
pub const fn from_code(code: i32) -> Self {
match code {
0 => Self::NotRun,
1 => Self::Passed,
2 => Self::SignatureInvalid,
3 => Self::SlotInvalid,
4 => Self::Unreadable,
5 => Self::CastNotRun,
6 => Self::UnknownRecord,
7 => Self::Refused,
8 => Self::NoVerifyKey,
9 => Self::KeyMismatch,
10 => Self::SlotDamaged,
other => Self::Unknown(other),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Fingerprint([u8; 32]);
impl Fingerprint {
#[must_use]
pub const fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
#[must_use]
pub fn from_hex(text: &str) -> Option<Self> {
let hex = text.strip_prefix("sha256:").unwrap_or(text).as_bytes();
if hex.len() != 64 || !hex.iter().all(u8::is_ascii_hexdigit) {
return None;
}
let mut out = [0u8; 32];
for (byte, pair) in out.iter_mut().zip(hex.chunks_exact(2)) {
let digits = core::str::from_utf8(pair).ok()?;
*byte = u8::from_str_radix(digits, 16).ok()?;
}
Some(Self(out))
}
}
impl fmt::Display for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("sha256:")?;
for b in &self.0 {
write!(f, "{b:02x}")?;
}
Ok(())
}
}
impl fmt::Debug for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Module {
_private: (),
}
#[derive(Clone, Copy)]
enum Pin {
#[cfg_attr(not(any(oxicrypt_pinned, doc)), allow(dead_code))]
Required(&'static str),
#[cfg_attr(not(oxicrypt_unpinned), allow(dead_code))]
Unpinned,
}
#[cfg(oxicrypt_pinned)]
const PIN: &str = env!("OXICRYPT_BINDINGS_PIN");
impl Module {
#[cfg(any(oxicrypt_pinned, doc))]
#[allow(clippy::result_large_err)] pub fn init(profile: Profile) -> Result<Self, InitError> {
#[cfg(oxicrypt_pinned)]
let pin = Pin::Required(PIN);
#[cfg(not(oxicrypt_pinned))]
let pin = Pin::Required("");
Self::init_with(profile, pin)
}
#[cfg(any(oxicrypt_unpinned, doc))]
#[allow(clippy::result_large_err)] pub fn init_unpinned(profile: Profile) -> Result<Self, InitError> {
Self::init_with(profile, Pin::Unpinned)
}
#[cfg_attr(not(any(oxicrypt_pinned, oxicrypt_unpinned)), allow(dead_code))]
#[allow(clippy::result_large_err)] fn init_with(profile: Profile, pin: Pin) -> Result<Self, InitError> {
let profile = Profile::from_code(profile.code());
let refused = |code| InitError {
code,
integrity: Some(integrity_status()),
detail: integrity_detail(),
};
library_compatible().map_err(|code| InitError {
code,
integrity: None,
detail: Ok(None),
})?;
let code = unsafe { sys::oxi_init(profile.code()) };
status(code, Site::Other).map_err(refused)?;
if unsafe { sys::oxi_is_operational() } != 1 {
return Err(refused(Error::NotOperational));
}
if integrity_status() != IntegrityStatus::Passed {
return Err(refused(Error::IntegrityUnverified));
}
if let Pin::Required(hex) = pin {
let found = key_fingerprint().map_err(refused)?;
if found.to_string() != format!("sha256:{hex}") {
let expected = Fingerprint::from_hex(hex).unwrap_or(Fingerprint([0; 32]));
return Err(refused(Error::KeyFingerprint { found, expected }));
}
}
let active = Profile::from_code(unsafe { sys::oxi_active_profile() });
if active != profile {
return Err(refused(Error::ProfileMismatch {
active,
requested: profile,
}));
}
Ok(Self { _private: () })
}
#[must_use]
pub fn is_operational(self) -> bool {
unsafe { sys::oxi_is_operational() == 1 }
}
#[must_use]
pub fn integrity_status(self) -> IntegrityStatus {
integrity_status()
}
pub fn key_fingerprint(self) -> Result<Fingerprint, Error> {
key_fingerprint()
}
#[must_use]
pub fn library_path() -> Option<std::path::PathBuf> {
crate::platform::library_path()
}
}
fn integrity_status() -> IntegrityStatus {
IntegrityStatus::from_code(unsafe { sys::oxi_integrity_status() })
}
fn key_fingerprint() -> Result<Fingerprint, Error> {
let mut out = [0u8; 32];
let code = unsafe { sys::oxi_integrity_key_fingerprint(out.as_mut_ptr(), out.len()) };
status(code, Site::Other)?;
Ok(Fingerprint(out))
}
pub(crate) const DETAIL_MAX: usize = 64 * 1024;
fn integrity_detail() -> Result<Option<String>, DetailError> {
let mut needed: usize = 0;
let code =
unsafe { sys::oxi_integrity_status_detail(core::ptr::null_mut(), 0, &raw mut needed) };
detail_from((code, needed), |buf| {
let mut written: usize = 0;
let code = unsafe {
sys::oxi_integrity_status_detail(buf.as_mut_ptr(), buf.len(), &raw mut written)
};
(code, written)
})
}
pub(crate) fn detail_from(
sizing: (c_int, usize),
read: impl FnOnce(&mut [u8]) -> (c_int, usize),
) -> Result<Option<String>, DetailError> {
let (code, needed) = sizing;
if needed == 0 && matches!(code, 0 | 1) {
return Ok(None);
}
if !matches!(code, 0 | 11) {
return Err(DetailError::Sizing(Error::from_code(code, Site::Other)));
}
if needed > DETAIL_MAX {
return Err(DetailError::TooLong { needed });
}
let mut buf = vec![0u8; needed];
let (code, written) = read(&mut buf);
status(code, Site::Other).map_err(DetailError::Read)?;
if written > buf.len() {
return Err(DetailError::Overrun {
written,
capacity: buf.len(),
});
}
buf.truncate(written);
if buf.last() == Some(&0) {
buf.pop();
}
Ok((!buf.is_empty()).then(|| String::from_utf8_lossy(&buf).into_owned()))
}
fn manifest() -> Option<String> {
let ptr = unsafe { sys::lama_manifest() };
if ptr.is_null() {
return None;
}
let text = unsafe { CStr::from_ptr(ptr) };
Some(text.to_string_lossy().into_owned())
}
pub(crate) fn manifest_library_version(manifest: &str) -> Option<&str> {
let mut in_library = false;
let mut child_indent: Option<usize> = None;
for line in manifest.lines() {
let content = line.trim_start();
if content.is_empty() || content.starts_with('#') {
continue;
}
let indent = line.len().saturating_sub(content.len());
if indent == 0 {
if in_library {
return None;
}
in_library = content.trim_end() == "library:";
continue;
}
if !in_library {
continue;
}
let expected = *child_indent.get_or_insert(indent);
if indent != expected {
continue;
}
if let Some(value) = content.strip_prefix("version:") {
let value = value.split(" #").next().unwrap_or("").trim();
let value = value
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.unwrap_or(value);
return (!value.is_empty()).then_some(value);
}
}
None
}
fn library_compatible() -> Result<(), Error> {
static CHECKED: OnceLock<Result<(), Error>> = OnceLock::new();
CHECKED
.get_or_init(|| {
match crate::platform::abi_version() {
Some(library) if library == crate::OXI_ABI_VERSION => return Ok(()),
Some(library) => {
return Err(Error::LibraryAbi {
library,
crate_: crate::OXI_ABI_VERSION,
});
}
None => {}
}
let crate_ = env!("CARGO_PKG_VERSION");
let text = manifest();
let library = text.as_deref().and_then(manifest_library_version);
if library == Some(crate_) {
Ok(())
} else {
Err(Error::LibraryVersion {
library: library.map(str::to_owned),
crate_,
})
}
})
.clone()
}
pub(crate) fn check(code: c_int) -> Result<(), Error> {
status(code, Site::Other)
}