mod aes;
mod auth;
mod key;
mod perms;
mod rc4;
mod write;
use std::fmt;
pub use perms::Permissions;
pub use write::{Entropy, Grant, Handler, NewHandler, PrintRight, SeededEntropy, encrypt, new_handler};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Cipher {
Identity,
Rc4,
Aes128,
Aes256,
}
impl Cipher {
#[must_use]
pub const fn name(&self) -> &'static str {
match self {
Self::Identity => "identity",
Self::Rc4 => "rc4",
Self::Aes128 => "aes-128",
Self::Aes256 => "aes-256",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PasswordKind {
User,
Owner,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct StandardSecurity<'a> {
pub revision: u8,
pub key_length: usize,
pub owner: &'a [u8],
pub user: &'a [u8],
pub owner_encryption: &'a [u8],
pub user_encryption: &'a [u8],
pub perms: Option<&'a [u8]>,
pub permissions: u32,
pub id0: &'a [u8],
pub encrypt_metadata: bool,
}
impl StandardSecurity<'_> {
fn key_bytes(&self) -> usize {
if self.revision == 2 {
5
} else {
self.key_length.clamp(5, 16)
}
}
}
impl fmt::Debug for StandardSecurity<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StandardSecurity")
.field("revision", &self.revision)
.field("key_length", &self.key_length)
.field("permissions", &self.permissions)
.field("encrypt_metadata", &self.encrypt_metadata)
.finish_non_exhaustive()
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct FileKey(Vec<u8>);
impl FileKey {
#[must_use]
pub const fn from_bytes(bytes: Vec<u8>) -> Self {
Self(bytes)
}
#[must_use]
pub fn bits(&self) -> usize {
self.0.len().saturating_mul(8)
}
}
impl Drop for FileKey {
fn drop(&mut self) {
zeroize::Zeroize::zeroize(&mut self.0);
}
}
impl fmt::Debug for FileKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "FileKey(<{} bits redacted>)", self.bits())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Authenticated {
pub key: FileKey,
pub matched: PasswordKind,
pub perms_valid: Option<bool>,
}
#[cfg(any(not(feature = "saslprep"), test))]
fn saslprep_mapping(text: &str) -> String {
const SPACES: [char; 17] = [
'\u{00A0}', '\u{1680}', '\u{2000}', '\u{2001}', '\u{2002}', '\u{2003}', '\u{2004}', '\u{2005}', '\u{2006}',
'\u{2007}', '\u{2008}', '\u{2009}', '\u{200A}', '\u{200B}', '\u{202F}', '\u{205F}', '\u{3000}',
];
let to_nothing = |c: char| {
matches!(
c,
'\u{00AD}'
| '\u{034F}'
| '\u{1806}'
| '\u{180B}'..='\u{180D}'
| '\u{200C}'
| '\u{200D}'
| '\u{2060}'
| '\u{FE00}'..='\u{FE0F}'
| '\u{FEFF}'
)
};
text.chars()
.filter_map(|c| {
if SPACES.contains(&c) {
Some(' ')
} else if to_nothing(c) {
None
} else {
Some(c)
}
})
.collect()
}
fn candidates(password: &[u8], revision: u8) -> Vec<Vec<u8>> {
let text = std::str::from_utf8(password).ok();
if revision >= 5 {
#[cfg(feature = "saslprep")]
let prepared = zeroize::Zeroizing::new(match text.and_then(|t| stringprep::saslprep(t).ok()) {
Some(std::borrow::Cow::Owned(p)) => p.into_bytes(),
Some(std::borrow::Cow::Borrowed(p)) => p.as_bytes().to_vec(),
None => password.to_vec(),
});
#[cfg(not(feature = "saslprep"))]
let prepared =
zeroize::Zeroizing::new(text.map_or_else(|| password.to_vec(), |t| saslprep_mapping(t).into_bytes()));
let mut out = vec![key::prefix(&prepared, 127).to_vec()];
let raw = key::prefix(password, 127).to_vec();
if !out.contains(&raw) {
out.push(raw);
}
return out;
}
let mut out = vec![password.to_vec()];
if let Some(text) = text
&& !text.is_ascii()
&& let Some(latin1) = text
.chars()
.map(|c| u8::try_from(u32::from(c)).ok())
.collect::<Option<Vec<u8>>>()
{
out.push(latin1);
}
out
}
#[must_use]
pub fn authenticate(sec: &StandardSecurity<'_>, password: &[u8]) -> Option<Authenticated> {
authenticate_as(sec, password, false)
}
#[must_use]
pub fn authenticate_owner(sec: &StandardSecurity<'_>, password: &[u8]) -> Option<Authenticated> {
authenticate_as(sec, password, true)
}
fn authenticate_as(sec: &StandardSecurity<'_>, password: &[u8], owner_only: bool) -> Option<Authenticated> {
let modern = match sec.revision {
2..=4 => false,
5 | 6 => true,
_ => return None,
};
let user = |pw: &[u8]| {
if modern {
auth::user_r5_r6(sec, pw)
} else {
auth::user_r2_r4(sec, pw)
}
};
let owner = |pw: &[u8]| {
if modern {
auth::owner_r5_r6(sec, pw)
} else {
auth::owner_r2_r4(sec, pw)
}
};
let mut candidates = candidates(password, sec.revision);
let as_user = || {
candidates
.iter()
.find_map(|pw| user(pw).map(|k| (k, PasswordKind::User)))
};
let as_owner = || {
candidates
.iter()
.find_map(|pw| owner(pw).map(|k| (k, PasswordKind::Owner)))
};
let found = if owner_only {
as_owner()
} else if modern {
as_owner().or_else(as_user)
} else {
as_user().or_else(as_owner)
};
zeroize::Zeroize::zeroize(&mut candidates);
let (key, matched) = found?;
let perms_valid = (sec.revision >= 5)
.then_some(sec.perms)
.flatten()
.map(|perms| perms::perms_match(&key, perms, sec.permissions, sec.encrypt_metadata));
Some(Authenticated {
key: FileKey(key),
matched,
perms_valid,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Decrypted {
pub data: Vec<u8>,
pub well_formed: bool,
}
#[must_use]
pub fn decrypt(cipher: Cipher, key: &FileKey, num: u32, gen_nr: u16, data: &[u8]) -> Decrypted {
let plain = match cipher {
Cipher::Identity => aes::Plain {
data: data.to_vec(),
valid: true,
},
Cipher::Rc4 => aes::Plain {
data: rc4::apply(&key::object_key(&key.0, num, gen_nr, false), data),
valid: true,
},
Cipher::Aes128 => aes::decrypt(&key::object_key(&key.0, num, gen_nr, true), data),
Cipher::Aes256 => aes::decrypt(&key.0, data),
};
Decrypted {
data: plain.data,
well_formed: plain.valid,
}
}
#[cfg(test)]
mod tests;