use sha2::{Digest, Sha256};
use crate::crypto::aes::{KEY_LEN_256, decrypt_ecb_256_block, unwrap_key_cbc_256};
pub const OU_LEN: usize = 48;
pub const OE_UE_LEN: usize = KEY_LEN_256;
pub const PERMS_LEN: usize = 16;
const HASH: std::ops::Range<usize> = 0..32;
const VALIDATION_SALT: std::ops::Range<usize> = 32..40;
const KEY_SALT: std::ops::Range<usize> = 40..48;
pub const MAX_PASSWORD_LEN: usize = 127;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Hasher {
Sha256,
R6(super::r6::A13Reading),
}
impl Hasher {
#[must_use]
pub fn hash(self, input_parts: &[&[u8]], password: &[u8], u: Option<&[u8]>) -> [u8; 32] {
match self {
Self::Sha256 => {
let mut h = Sha256::new();
for p in input_parts {
h.update(p);
}
if let Some(u) = u {
h.update(u);
}
h.finalize().into()
}
Self::R6(reading) => {
let mut input: Vec<u8> = input_parts.concat();
if let Some(u) = u {
input.extend_from_slice(u);
}
super::r6::hash_2b(&input, password, u, reading)
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedPassword {
bytes: Vec<u8>,
needs_saslprep: bool,
truncated: bool,
}
impl PreparedPassword {
#[must_use]
pub fn new(password: &[u8]) -> Self {
let needs_saslprep = password
.iter()
.any(|&b| b >= 0x80 || (b.is_ascii_control() && b != b' '));
let take = password.len().min(MAX_PASSWORD_LEN);
Self {
bytes: password.get(..take).unwrap_or_default().to_vec(),
needs_saslprep,
truncated: password.len() > MAX_PASSWORD_LEN,
}
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
#[must_use]
pub fn needs_saslprep(&self) -> bool {
self.needs_saslprep
}
#[must_use]
pub fn was_truncated(&self) -> bool {
self.truncated
}
}
#[must_use]
pub fn authenticates_as_user(
password: &PreparedPassword,
u: &[u8; OU_LEN],
hasher: Hasher,
) -> bool {
#[allow(clippy::indexing_slicing)]
let (expect, salt) = (&u[HASH], &u[VALIDATION_SALT]);
hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), None) == expect
}
#[must_use]
pub fn authenticates_as_owner(
password: &PreparedPassword,
o: &[u8; OU_LEN],
u: &[u8; OU_LEN],
hasher: Hasher,
) -> bool {
#[allow(clippy::indexing_slicing)]
let (expect, salt) = (&o[HASH], &o[VALIDATION_SALT]);
hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), Some(u)) == expect
}
#[must_use]
pub fn file_key_from_user_password(
password: &PreparedPassword,
u: &[u8; OU_LEN],
ue: &[u8; OE_UE_LEN],
hasher: Hasher,
) -> Option<[u8; KEY_LEN_256]> {
#[allow(clippy::indexing_slicing)]
let salt = &u[KEY_SALT];
let unwrap_key = hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), None);
unwrap_key_cbc_256(&unwrap_key, ue).try_into().ok()
}
#[must_use]
pub fn file_key_from_owner_password(
password: &PreparedPassword,
o: &[u8; OU_LEN],
u: &[u8; OU_LEN],
oe: &[u8; OE_UE_LEN],
hasher: Hasher,
) -> Option<[u8; KEY_LEN_256]> {
#[allow(clippy::indexing_slicing)]
let salt = &o[KEY_SALT];
let unwrap_key = hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), Some(u));
unwrap_key_cbc_256(&unwrap_key, oe).try_into().ok()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermsCheck {
NotApplicable,
Match,
Mismatch {
perms_p: u32,
dict_p: u32,
perms_encrypt_metadata: Option<bool>,
dict_encrypt_metadata: bool,
},
MarkerMissing,
}
#[must_use]
#[allow(clippy::indexing_slicing)]
pub fn validate_perms(
file_key: &[u8; KEY_LEN_256],
perms: &[u8; PERMS_LEN],
dict_p: u32,
dict_encrypt_metadata: bool,
) -> PermsCheck {
let out = decrypt_ecb_256_block(file_key, perms);
if &out[9..12] != b"adb" {
return PermsCheck::MarkerMissing;
}
let perms_p = u32::from_le_bytes([out[0], out[1], out[2], out[3]]);
let perms_encrypt_metadata = match out[8] {
b'T' => Some(true),
b'F' => Some(false),
_ => None,
};
if perms_p == dict_p && perms_encrypt_metadata == Some(dict_encrypt_metadata) {
PermsCheck::Match
} else {
PermsCheck::Mismatch {
perms_p,
dict_p,
perms_encrypt_metadata,
dict_encrypt_metadata,
}
}
}
#[cfg(test)]
#[allow(
clippy::indexing_slicing,
clippy::unwrap_used,
clippy::expect_used,
clippy::panic
)]
mod tests {
use super::*;
const U: [u8; OU_LEN] = [
0x58, 0xc0, 0x57, 0x8f, 0xec, 0x62, 0x7b, 0x8b, 0x9b, 0x8d, 0xd4, 0x26, 0xb6, 0xc2, 0x95,
0x4d, 0x76, 0xa0, 0x92, 0x1c, 0xa6, 0x5e, 0xfb, 0xb9, 0xa9, 0xa5, 0xc6, 0xbb, 0x9d, 0xe7,
0x81, 0x8b, 0xa7, 0x7e, 0x79, 0xcc, 0x0a, 0x4b, 0xd1, 0x28, 0x99, 0xbd, 0xb1, 0x12, 0x8f,
0x4b, 0xc7, 0x99,
];
const O: [u8; OU_LEN] = [
0xf8, 0xd6, 0xbf, 0xa3, 0x1b, 0x64, 0x5d, 0x37, 0x7e, 0xf8, 0xbd, 0x6e, 0xd5, 0x34, 0xb0,
0x28, 0xa5, 0x8d, 0xd9, 0x7e, 0xdf, 0x16, 0xfe, 0xf0, 0xe4, 0x57, 0x19, 0x58, 0x5c, 0x7d,
0x32, 0xda, 0xbb, 0xd6, 0x0d, 0xd2, 0x65, 0xc7, 0xd3, 0xd0, 0x77, 0xde, 0xbe, 0x35, 0x54,
0xb5, 0xfb, 0x0f,
];
const UE: [u8; OE_UE_LEN] = [
0xe2, 0x24, 0xdc, 0x92, 0x32, 0x71, 0x44, 0xdf, 0x5a, 0xb4, 0x75, 0xa1, 0x00, 0x8b, 0x1d,
0x37, 0xef, 0x90, 0xe7, 0x8a, 0x85, 0x36, 0x58, 0xe5, 0xf7, 0x77, 0x06, 0xc2, 0x1e, 0x90,
0xb3, 0x8a,
];
const OE: [u8; OE_UE_LEN] = [
0xde, 0xd9, 0x20, 0x92, 0x7c, 0x17, 0xc9, 0xc0, 0x8d, 0x47, 0x09, 0x68, 0xd6, 0x4f, 0xae,
0x44, 0xb6, 0x85, 0x8b, 0x08, 0xca, 0xcf, 0x51, 0x11, 0x52, 0xd4, 0x3f, 0xcd, 0x61, 0xf8,
0x85, 0x1f,
];
const PERMS: [u8; PERMS_LEN] = [
0x71, 0x6a, 0xf6, 0xa5, 0x5e, 0xa2, 0xaf, 0xb6, 0xa9, 0xb8, 0x8a, 0xe3, 0x6e, 0x38, 0xb5,
0xe1,
];
const FILE_KEY: [u8; KEY_LEN_256] = [
0x9c, 0x41, 0xcb, 0x1c, 0x02, 0x13, 0x80, 0x48, 0x96, 0x0d, 0x57, 0xf4, 0x8a, 0x21, 0x22,
0xf8, 0xfe, 0xbf, 0x4a, 0x68, 0xdd, 0x03, 0x18, 0x62, 0xaf, 0x90, 0xba, 0xc8, 0x20, 0x51,
0xf6, 0x0c,
];
const DICT_P: u32 = 0xFFFF_FFFC;
fn pw(s: &[u8]) -> PreparedPassword {
PreparedPassword::new(s)
}
#[test]
fn user_validation_accepts_only_the_user_password() {
assert!(authenticates_as_user(&pw(b"userpw"), &U, Hasher::Sha256));
assert!(!authenticates_as_user(&pw(b"ownerpw"), &U, Hasher::Sha256));
assert!(!authenticates_as_user(&pw(b""), &U, Hasher::Sha256));
assert!(!authenticates_as_user(&pw(b"userpw "), &U, Hasher::Sha256));
}
#[test]
fn owner_validation_accepts_only_the_owner_password() {
assert!(authenticates_as_owner(
&pw(b"ownerpw"),
&O,
&U,
Hasher::Sha256
));
assert!(!authenticates_as_owner(
&pw(b"userpw"),
&O,
&U,
Hasher::Sha256
));
}
#[test]
fn truncating_u_to_its_hash_breaks_owner_validation_only() {
let truncated = Hasher::Sha256.hash(
&[b"ownerpw", &O[VALIDATION_SALT], &U[HASH]],
b"ownerpw",
None,
);
assert_ne!(
truncated, O[HASH],
"hashing U's 32-byte hash instead of the whole 48-byte string must \
NOT validate — if this ever passes, T26 has stopped being a trap \
and the whole-string requirement can be relaxed"
);
assert!(authenticates_as_owner(
&pw(b"ownerpw"),
&O,
&U,
Hasher::Sha256
));
}
#[test]
fn both_password_branches_recover_the_same_file_encryption_key() {
let from_user = file_key_from_user_password(&pw(b"userpw"), &U, &UE, Hasher::Sha256)
.expect("UE unwraps to 32 bytes");
let from_owner = file_key_from_owner_password(&pw(b"ownerpw"), &O, &U, &OE, Hasher::Sha256)
.expect("OE unwraps to 32 bytes");
assert_eq!(from_user, FILE_KEY);
assert_eq!(from_owner, FILE_KEY);
}
#[test]
fn transposing_the_two_salts_yields_a_different_key() {
let right = Hasher::Sha256.hash(&[b"userpw".as_slice(), &U[KEY_SALT]], b"userpw", None);
let wrong = Hasher::Sha256.hash(
&[b"userpw".as_slice(), &U[VALIDATION_SALT]],
b"userpw",
None,
);
assert_ne!(right, wrong);
assert_ne!(
unwrap_key_cbc_256(&wrong, &UE),
FILE_KEY.to_vec(),
"the validation salt must not produce the file encryption key"
);
assert_eq!(unwrap_key_cbc_256(&right, &UE), FILE_KEY.to_vec());
}
#[test]
fn unwrapping_with_a_wrong_password_yields_a_wrong_key_not_an_error() {
let bad = file_key_from_user_password(&pw(b"not the password"), &U, &UE, Hasher::Sha256)
.expect("32 bytes of nonsense is still 32 bytes");
assert_ne!(bad, FILE_KEY);
}
#[test]
fn perms_validates_against_the_dictionary() {
assert_eq!(
validate_perms(&FILE_KEY, &PERMS, DICT_P, true),
PermsCheck::Match
);
}
#[test]
fn a_tampered_p_is_reported_with_both_values() {
match validate_perms(&FILE_KEY, &PERMS, 0xFFFF_FFFF, true) {
PermsCheck::Mismatch {
perms_p,
dict_p,
perms_encrypt_metadata,
dict_encrypt_metadata,
} => {
assert_eq!(perms_p, DICT_P, "the encrypted copy is unchanged");
assert_eq!(dict_p, 0xFFFF_FFFF, "the plaintext copy is what moved");
assert_eq!(perms_encrypt_metadata, Some(true));
assert!(dict_encrypt_metadata);
}
other => panic!("expected a mismatch, got {other:?}"),
}
}
#[test]
fn a_flipped_encrypt_metadata_is_a_mismatch() {
assert!(matches!(
validate_perms(&FILE_KEY, &PERMS, DICT_P, false),
PermsCheck::Mismatch { .. }
));
}
#[test]
fn a_corrupt_perms_block_reports_the_missing_marker() {
let mut damaged = PERMS;
damaged[0] ^= 0xFF;
assert_eq!(
validate_perms(&FILE_KEY, &damaged, DICT_P, true),
PermsCheck::MarkerMissing
);
}
#[test]
fn perms_decrypted_as_chained_cbc_loses_its_marker() {
let mut chained = [0u8; 32];
chained[..16].copy_from_slice(&[0xAA; 16]);
chained[16..].copy_from_slice(&PERMS);
let out = unwrap_key_cbc_256(&FILE_KEY, &chained);
assert_eq!(out.len(), 32);
assert_ne!(
&out[16 + 9..16 + 12],
b"adb",
"chaining must corrupt the marker; if it does not, this test is \
not observing the difference it claims to"
);
assert_eq!(&decrypt_ecb_256_block(&FILE_KEY, &PERMS)[9..12], b"adb");
}
#[test]
fn matches_qpdfs_published_file_encryption_key() {
const QPDF_O: [u8; OU_LEN] = [
0x58, 0x4a, 0x53, 0x53, 0xc4, 0x24, 0xc1, 0xf9, 0x63, 0xb6, 0xb5, 0xf0, 0xa0, 0x92,
0xd7, 0x20, 0xf0, 0x7b, 0xf1, 0x20, 0xeb, 0x32, 0x9a, 0xdd, 0x86, 0x63, 0xfe, 0x33,
0xa8, 0x58, 0x9a, 0xdc, 0xad, 0x4f, 0xca, 0x26, 0x53, 0x79, 0x3d, 0x09, 0x94, 0x94,
0x8f, 0x7f, 0x6f, 0x30, 0xa0, 0x35,
];
const QPDF_U: [u8; OU_LEN] = [
0xd7, 0x7c, 0xd8, 0x82, 0xaf, 0x29, 0xe7, 0xbe, 0xc7, 0x57, 0x91, 0x57, 0x18, 0x76,
0x16, 0xc3, 0x24, 0xa6, 0xa0, 0x0e, 0x8b, 0x90, 0xf0, 0x95, 0x9e, 0x6b, 0x01, 0xf8,
0x39, 0x72, 0x06, 0x5e, 0xc5, 0xb7, 0xc4, 0x51, 0x21, 0xf5, 0x96, 0x34, 0x30, 0xff,
0xe0, 0x3a, 0x06, 0xa2, 0x23, 0x01,
];
const QPDF_OE: [u8; OE_UE_LEN] = [
0x50, 0xb2, 0x41, 0x5e, 0x8d, 0xc2, 0x04, 0x23, 0x5c, 0x83, 0x7e, 0x85, 0xb6, 0xa3,
0x36, 0xae, 0x85, 0x7b, 0x36, 0x6e, 0xde, 0x9e, 0x9c, 0xc7, 0xd3, 0x06, 0x57, 0xdb,
0x00, 0x03, 0x3e, 0xc3,
];
const QPDF_UE: [u8; OE_UE_LEN] = [
0x86, 0x56, 0x0d, 0x35, 0xa1, 0x5c, 0x06, 0x74, 0x57, 0xdc, 0xbf, 0xb5, 0x7e, 0xdd,
0x49, 0x5c, 0xb0, 0xf5, 0xc2, 0xc1, 0xce, 0x77, 0xc9, 0xcf, 0x46, 0x2a, 0x49, 0x6c,
0xe4, 0x84, 0xcc, 0xfd,
];
const QPDF_PERMS: [u8; PERMS_LEN] = [
0x89, 0x71, 0x9c, 0xe2, 0x26, 0xa7, 0x30, 0xc2, 0x18, 0x99, 0x60, 0xbb, 0x53, 0x34,
0x50, 0xad,
];
const QPDF_KEY: [u8; KEY_LEN_256] = [
0x35, 0xea, 0x16, 0xa4, 0x8b, 0x6a, 0x30, 0x45, 0x13, 0x3b, 0x69, 0xac, 0x09, 0x06,
0xc2, 0xe8, 0xfb, 0x0a, 0x2c, 0xc9, 0x79, 0x03, 0xae, 0x17, 0xb5, 0x1a, 0x57, 0x86,
0xeb, 0xdb, 0xa0, 0x20,
];
const QPDF_P: u32 = 0xFFFF_F7FC;
assert!(authenticates_as_user(
&pw(b"user3"),
&QPDF_U,
Hasher::Sha256
));
assert!(authenticates_as_owner(
&pw(b"owner3"),
&QPDF_O,
&QPDF_U,
Hasher::Sha256
));
assert_eq!(
file_key_from_user_password(&pw(b"user3"), &QPDF_U, &QPDF_UE, Hasher::Sha256),
Some(QPDF_KEY),
"the user branch must reach the key qpdf publishes for this file"
);
assert_eq!(
file_key_from_owner_password(
&pw(b"owner3"),
&QPDF_O,
&QPDF_U,
&QPDF_OE,
Hasher::Sha256
),
Some(QPDF_KEY),
"and so must the owner branch — one key, two wrapped copies"
);
assert_eq!(
validate_perms(&QPDF_KEY, &QPDF_PERMS, QPDF_P, true),
PermsCheck::Match
);
}
#[test]
fn passwords_are_truncated_to_127_bytes_and_say_so() {
let short = PreparedPassword::new(b"userpw");
assert_eq!(short.as_bytes(), b"userpw");
assert!(!short.was_truncated());
let long = vec![b'x'; 200];
let p = PreparedPassword::new(&long);
assert_eq!(p.as_bytes().len(), MAX_PASSWORD_LEN);
assert!(p.was_truncated());
assert!(!PreparedPassword::new(&[b'x'; 127]).was_truncated());
assert!(PreparedPassword::new(&[b'x'; 128]).was_truncated());
let a = PreparedPassword::new(&[vec![b'a'; 127], vec![b'1']].concat());
let b = PreparedPassword::new(&[vec![b'a'; 127], vec![b'2']].concat());
assert_eq!(a.as_bytes(), b.as_bytes());
}
#[test]
fn saslprep_relevance_is_reported_for_non_ascii_only() {
for exact in [
&b"userpw"[..],
b"",
b"a very long ASCII passphrase with spaces",
b"!@#$%^&*()_+-={}|[]\\:\";'<>?,./",
] {
assert!(
!PreparedPassword::new(exact).needs_saslprep(),
"SASLprep is the identity on ASCII graphics: {exact:?}"
);
}
for inexact in [
"pässwörd".as_bytes(),
"パスワード".as_bytes(),
"a\u{00A0}b".as_bytes(),
&[b'a', 0x01, b'b'],
&[0xFF, 0xFE],
] {
assert!(
PreparedPassword::new(inexact).needs_saslprep(),
"must be flagged: {inexact:?}"
);
}
}
}