use std::fmt;
pub const FORMAT: u8 = 1;
pub const MAX_KEY_REF: usize = 1024;
pub const MAX_CIPHERTEXT: usize = 8192;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BackendKind {
AwsKms,
GcpKms,
AzureKeyVault,
VaultTransit,
OpenbaoTransit,
Pkcs11,
}
impl BackendKind {
pub const ALL: [BackendKind; 6] = [
BackendKind::AwsKms,
BackendKind::GcpKms,
BackendKind::AzureKeyVault,
BackendKind::VaultTransit,
BackendKind::OpenbaoTransit,
BackendKind::Pkcs11,
];
#[must_use]
pub fn name(self) -> &'static str {
match self {
BackendKind::AwsKms => "aws-kms",
BackendKind::GcpKms => "gcp-kms",
BackendKind::AzureKeyVault => "azure-key-vault",
BackendKind::VaultTransit => "vault-transit",
BackendKind::OpenbaoTransit => "openbao-transit",
BackendKind::Pkcs11 => "pkcs11",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<BackendKind> {
BackendKind::ALL.into_iter().find(|k| k.name() == name)
}
fn byte(self) -> u8 {
match self {
BackendKind::AwsKms => 1,
BackendKind::GcpKms => 2,
BackendKind::AzureKeyVault => 3,
BackendKind::VaultTransit => 4,
BackendKind::OpenbaoTransit => 5,
BackendKind::Pkcs11 => 6,
}
}
fn from_byte(byte: u8) -> Option<BackendKind> {
BackendKind::ALL.into_iter().find(|k| k.byte() == byte)
}
}
impl fmt::Display for BackendKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum BlobError {
Empty,
UnknownFormat(u8),
UnknownKind(u8),
Truncated,
TrailingBytes,
KeyRef,
Ciphertext,
RefText,
}
impl fmt::Display for BlobError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BlobError::Empty => f.write_str("a key-wrap blob is empty"),
BlobError::UnknownFormat(n) => {
write!(f, "key-wrap format {n} is not one this build knows")
}
BlobError::UnknownKind(n) => write!(
f,
"a key-wrap blob names key backend {n}, which this build does not know"
),
BlobError::Truncated => f.write_str("a key-wrap blob is cut short"),
BlobError::TrailingBytes => f.write_str("a key-wrap blob has bytes after its end"),
BlobError::KeyRef => write!(
f,
"a key reference is empty, longer than {MAX_KEY_REF} bytes, or not printable ASCII"
),
BlobError::Ciphertext => write!(
f,
"a wrapped key's ciphertext is empty or longer than {MAX_CIPHERTEXT} bytes"
),
BlobError::RefText => {
f.write_str("a key reference does not start with a key backend's name and a colon")
}
}
}
}
impl std::error::Error for BlobError {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WrapRef {
kind: BackendKind,
key: String,
}
impl WrapRef {
pub fn new(kind: BackendKind, key: impl Into<String>) -> Result<WrapRef, BlobError> {
let key = key.into();
if !valid_key(key.as_bytes()) {
return Err(BlobError::KeyRef);
}
Ok(WrapRef { kind, key })
}
pub fn parse(text: &str) -> Result<WrapRef, BlobError> {
let (name, key) = text.split_once(':').ok_or(BlobError::RefText)?;
let kind = BackendKind::from_name(name).ok_or(BlobError::RefText)?;
WrapRef::new(kind, key)
}
#[must_use]
pub fn kind(&self) -> BackendKind {
self.kind
}
#[must_use]
pub fn key(&self) -> &str {
&self.key
}
}
impl fmt::Display for WrapRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.kind, self.key)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Blob {
reference: WrapRef,
ciphertext: Vec<u8>,
}
impl Blob {
pub fn new(reference: WrapRef, ciphertext: Vec<u8>) -> Result<Blob, BlobError> {
if !(1..=MAX_CIPHERTEXT).contains(&ciphertext.len()) {
return Err(BlobError::Ciphertext);
}
Ok(Blob {
reference,
ciphertext,
})
}
#[must_use]
pub fn encode(&self) -> Vec<u8> {
let key = self.reference.key.as_bytes();
let key_len = u16::try_from(key.len()).unwrap_or(u16::MAX);
let ct_len = u32::try_from(self.ciphertext.len()).unwrap_or(u32::MAX);
let mut out = Vec::with_capacity(8 + key.len() + self.ciphertext.len());
out.push(FORMAT);
out.push(self.reference.kind.byte());
out.extend_from_slice(&key_len.to_be_bytes());
out.extend_from_slice(key);
out.extend_from_slice(&ct_len.to_be_bytes());
out.extend_from_slice(&self.ciphertext);
out
}
pub fn decode(bytes: &[u8]) -> Result<Blob, BlobError> {
let (&format, rest) = bytes.split_first().ok_or(BlobError::Empty)?;
if format != FORMAT {
return Err(BlobError::UnknownFormat(format));
}
let (&kind, rest) = rest.split_first().ok_or(BlobError::Truncated)?;
let kind = BackendKind::from_byte(kind).ok_or(BlobError::UnknownKind(kind))?;
let (key_len, rest) = take::<2>(rest)?;
let key_len = usize::from(u16::from_be_bytes(key_len));
if !(1..=MAX_KEY_REF).contains(&key_len) {
return Err(BlobError::KeyRef);
}
let (key, rest) = rest.split_at_checked(key_len).ok_or(BlobError::Truncated)?;
if !valid_key(key) {
return Err(BlobError::KeyRef);
}
let (ct_len, rest) = take::<4>(rest)?;
let ct_len = usize::try_from(u32::from_be_bytes(ct_len)).unwrap_or(usize::MAX);
if !(1..=MAX_CIPHERTEXT).contains(&ct_len) {
return Err(BlobError::Ciphertext);
}
let (ciphertext, rest) = rest.split_at_checked(ct_len).ok_or(BlobError::Truncated)?;
if !rest.is_empty() {
return Err(BlobError::TrailingBytes);
}
let key = String::from_utf8(key.to_vec()).map_err(|_| BlobError::KeyRef)?;
Ok(Blob {
reference: WrapRef { kind, key },
ciphertext: ciphertext.to_vec(),
})
}
#[must_use]
pub fn reference(&self) -> &WrapRef {
&self.reference
}
#[must_use]
pub fn ciphertext(&self) -> &[u8] {
&self.ciphertext
}
}
impl fmt::Debug for Blob {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Blob")
.field("reference", &self.reference)
.field("ciphertext_len", &self.ciphertext.len())
.finish()
}
}
fn valid_key(key: &[u8]) -> bool {
(1..=MAX_KEY_REF).contains(&key.len()) && key.iter().all(u8::is_ascii_graphic)
}
fn take<const N: usize>(bytes: &[u8]) -> Result<([u8; N], &[u8]), BlobError> {
let (head, rest) = bytes.split_at_checked(N).ok_or(BlobError::Truncated)?;
let head = head.try_into().map_err(|_| BlobError::Truncated)?;
Ok((head, rest))
}
#[cfg(test)]
mod tests;