use crate::crypto::aes::{
KEY_LEN_256, decrypt_cbc_128, decrypt_cbc_256, encrypt_cbc_128, encrypt_cbc_256,
};
use crate::crypto::md5::{Md5, md5};
use crate::crypto::r5::{self, OE_UE_LEN, OU_LEN, PERMS_LEN, PermsCheck, PreparedPassword};
use crate::crypto::rc4::rc4;
use crate::object::{Dict, Name, ObjId, Object};
pub const PADDING: [u8; 32] = [
0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
];
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum EncryptionUnsupported {
#[error("security handler /{0} is not the standard password handler")]
Handler(String),
#[error("/Encrypt has no /Filter; Table 20 forbids any handler from decrypting this document")]
NoFilter,
#[error(
"/V {0} is an undocumented or unpublished algorithm that no conforming reader can open"
)]
UndocumentedAlgorithm(i64),
#[error(
"{0} encryption is not implemented yet (pdfcer reads RC4 40-128 bit, AES-128 and AES-256 at /R 5)"
)]
CipherNotImplemented(&'static str),
#[error("crypt filter method /{0} is not one of None, V2, AESV2, AESV3")]
UnknownCfm(String),
#[error("/Encrypt is malformed: {0}")]
Malformed(&'static str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cipher {
None,
Rc4,
Aes128,
Aes256,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Permissions {
pub raw: u32,
pub revision: u8,
}
impl Permissions {
fn bit(self, n: u32) -> bool {
self.raw & (1 << (n - 1)) != 0
}
#[must_use]
pub fn print(self) -> bool {
self.bit(3)
}
#[must_use]
pub fn modify_contents(self) -> bool {
self.bit(4)
}
#[must_use]
pub fn copy(self) -> bool {
self.bit(5)
}
#[must_use]
pub fn annotate(self) -> bool {
self.bit(6)
}
#[must_use]
pub fn fill_forms(self) -> bool {
self.revision >= 3 && self.bit(9)
}
#[must_use]
pub fn accessibility_extract(self) -> bool {
self.revision >= 3 && self.bit(10)
}
#[must_use]
pub fn assemble(self) -> bool {
self.revision >= 3 && self.bit(11)
}
#[must_use]
pub fn print_high_quality(self) -> bool {
self.revision >= 3 && self.bit(12)
}
#[must_use]
pub fn granted(self, bit: PermissionBit) -> Option<bool> {
if bit.applies_at(self.revision) {
Some(self.bit(bit.position()))
} else {
None
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PermissionBit {
Print,
PrintHighQuality,
ModifyContents,
Copy,
Annotate,
FillForms,
AccessibilityExtract,
Assemble,
}
impl PermissionBit {
#[must_use]
pub const fn all() -> [Self; 8] {
[
Self::Print,
Self::PrintHighQuality,
Self::ModifyContents,
Self::Copy,
Self::Annotate,
Self::FillForms,
Self::AccessibilityExtract,
Self::Assemble,
]
}
#[must_use]
pub const fn position(self) -> u32 {
match self {
Self::Print => 3,
Self::ModifyContents => 4,
Self::Copy => 5,
Self::Annotate => 6,
Self::FillForms => 9,
Self::AccessibilityExtract => 10,
Self::Assemble => 11,
Self::PrintHighQuality => 12,
}
}
#[must_use]
pub const fn applies_at(self, revision: u8) -> bool {
match self {
Self::Print | Self::ModifyContents | Self::Copy | Self::Annotate => true,
Self::FillForms
| Self::AccessibilityExtract
| Self::Assemble
| Self::PrintHighQuality => revision >= 3,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthKind {
EmptyUser,
User,
Owner,
}
#[derive(Debug, Clone)]
pub struct EncryptionConfig {
pub version: i64,
pub revision: u8,
pub key_len: usize,
pub o: Vec<u8>,
pub u: Vec<u8>,
pub p: u32,
pub encrypt_metadata: bool,
pub stream_cipher: Cipher,
pub string_cipher: Cipher,
pub aes256: Option<Aes256Keys>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Aes256Keys {
pub oe: [u8; OE_UE_LEN],
pub ue: [u8; OE_UE_LEN],
pub perms: [u8; PERMS_LEN],
}
impl EncryptionConfig {
#[must_use]
pub fn to_encrypt_dict(&self) -> Option<Object> {
self.aes256
.as_ref()
.map(|keys| self.encrypt_dict_with(keys))
}
pub(crate) fn encrypt_dict_with(&self, keys: &Aes256Keys) -> Object {
let mut stdcf = Dict::new();
stdcf.insert(Name(b"CFM".to_vec()), Object::Name(Name(b"AESV3".to_vec())));
stdcf.insert(
Name(b"AuthEvent".to_vec()),
Object::Name(Name(b"DocOpen".to_vec())),
);
stdcf.insert(Name(b"Length".to_vec()), Object::Integer(32));
let mut cf = Dict::new();
cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
let mut d = Dict::new();
d.insert(
Name(b"Filter".to_vec()),
Object::Name(Name(b"Standard".to_vec())),
);
d.insert(Name(b"V".to_vec()), Object::Integer(self.version));
d.insert(
Name(b"R".to_vec()),
Object::Integer(i64::from(self.revision)),
);
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
d.insert(
Name(b"Length".to_vec()),
Object::Integer((self.key_len as i64) * 8),
);
#[allow(clippy::cast_possible_wrap)]
d.insert(
Name(b"P".to_vec()),
Object::Integer(i64::from(self.p as i32)),
);
d.insert(Name(b"CF".to_vec()), Object::Dict(cf));
d.insert(
Name(b"StmF".to_vec()),
Object::Name(Name(b"StdCF".to_vec())),
);
d.insert(
Name(b"StrF".to_vec()),
Object::Name(Name(b"StdCF".to_vec())),
);
d.insert(Name(b"O".to_vec()), Object::String(self.o.clone()));
d.insert(Name(b"U".to_vec()), Object::String(self.u.clone()));
d.insert(Name(b"OE".to_vec()), Object::String(keys.oe.to_vec()));
d.insert(Name(b"UE".to_vec()), Object::String(keys.ue.to_vec()));
d.insert(Name(b"Perms".to_vec()), Object::String(keys.perms.to_vec()));
if !self.encrypt_metadata {
d.insert(Name(b"EncryptMetadata".to_vec()), Object::Boolean(false));
}
Object::Dict(d)
}
#[allow(clippy::indexing_slicing)]
pub fn parse(
dict: &Dict,
resolve: &dyn Fn(ObjId) -> Option<Object>,
) -> Result<Self, EncryptionUnsupported> {
let get = |key: &[u8]| -> Option<Object> {
match dict.get(key) {
Some(Object::Reference(id)) => resolve(*id),
Some(other) => Some(other.clone()),
None => None,
}
};
match get(b"Filter") {
Some(Object::Name(n)) => {
if n.as_bytes() != b"Standard" {
return Err(EncryptionUnsupported::Handler(
String::from_utf8_lossy(n.as_bytes()).into_owned(),
));
}
}
_ => return Err(EncryptionUnsupported::NoFilter),
}
let version = match get(b"V") {
Some(Object::Integer(v)) => v,
None => 0,
Some(_) => return Err(EncryptionUnsupported::Malformed("/V is not an integer")),
};
if version == 0 || version == 3 {
return Err(EncryptionUnsupported::UndocumentedAlgorithm(version));
}
let revision = match get(b"R") {
Some(Object::Integer(r)) if (2..=6).contains(&r) => r as u8,
Some(Object::Integer(r)) => {
return Err(EncryptionUnsupported::UndocumentedAlgorithm(r));
}
_ => {
return Err(EncryptionUnsupported::Malformed(
"/R is missing or not an integer",
));
}
};
let is_r5 = revision == 5 || revision == 6;
if is_r5 != (version == 5) {
return Err(EncryptionUnsupported::Malformed(
"/R 5 and /V 5 must appear together",
));
}
let key_len = if is_r5 {
KEY_LEN_256
} else if revision == 2 {
5
} else {
match get(b"Length") {
Some(Object::Integer(bits)) if (40..=128).contains(&bits) && bits % 8 == 0 => {
(bits / 8) as usize
}
None => 5,
Some(_) => {
return Err(EncryptionUnsupported::Malformed(
"/Length is not a multiple of 8 in 40..=128",
));
}
}
};
let ou_len = if is_r5 { OU_LEN } else { 32 };
let o = match get(b"O") {
Some(Object::String(s)) if s.len() >= ou_len => s[..ou_len].to_vec(),
Some(Object::String(_)) => {
return Err(EncryptionUnsupported::Malformed(
"/O is shorter than its revision requires (32 bytes at /R 2-4, 48 at /R 5)",
));
}
_ => {
return Err(EncryptionUnsupported::Malformed(
"/O is missing or not a string",
));
}
};
let u = match get(b"U") {
Some(Object::String(s)) if s.len() >= ou_len => s[..ou_len].to_vec(),
Some(Object::String(_)) => {
return Err(EncryptionUnsupported::Malformed(
"/U is shorter than its revision requires (32 bytes at /R 2-4, 48 at /R 5)",
));
}
_ => {
return Err(EncryptionUnsupported::Malformed(
"/U is missing or not a string",
));
}
};
let p = match get(b"P") {
Some(Object::Integer(v)) => v as i32 as u32,
_ => {
return Err(EncryptionUnsupported::Malformed(
"/P is missing or not an integer",
));
}
};
let encrypt_metadata = match get(b"EncryptMetadata") {
Some(Object::Boolean(b)) => b,
_ => true,
};
let (stream_cipher, string_cipher) = if version < 4 {
(Cipher::Rc4, Cipher::Rc4)
} else {
let cf = match get(b"CF") {
Some(Object::Dict(d)) => d,
_ => Dict::new(),
};
let named = |which: &[u8]| -> Result<Cipher, EncryptionUnsupported> {
let name = match get(which) {
Some(Object::Name(n)) => n.as_bytes().to_vec(),
_ => b"Identity".to_vec(),
};
if name == b"Identity" {
return Ok(Cipher::None);
}
let entry = match cf.get(&name) {
Some(Object::Reference(id)) => resolve(*id),
Some(other) => Some(other.clone()),
None => None,
};
let Some(Object::Dict(fd)) = entry else {
return Err(EncryptionUnsupported::Malformed(
"/StmF or /StrF names a crypt filter absent from /CF",
));
};
match fd.get(b"CFM") {
Some(Object::Name(n)) => match n.as_bytes() {
b"None" => Ok(Cipher::None),
b"V2" => Ok(Cipher::Rc4),
b"AESV2" => Ok(Cipher::Aes128),
b"AESV3" => Ok(Cipher::Aes256),
other => Err(EncryptionUnsupported::UnknownCfm(
String::from_utf8_lossy(other).into_owned(),
)),
},
_ => Ok(Cipher::None),
}
};
(named(b"StmF")?, named(b"StrF")?)
};
for c in [stream_cipher, string_cipher] {
let ok = match c {
Cipher::None => true,
Cipher::Rc4 | Cipher::Aes128 => !is_r5,
Cipher::Aes256 => is_r5,
};
if !ok {
return Err(EncryptionUnsupported::Malformed(
"/CFM does not match /V: version 4 takes V2 or AESV2, version 5 takes AESV3",
));
}
}
let aes256 = if is_r5 {
Some(Aes256Keys {
oe: fixed_string(
get(b"OE").as_ref(),
"/OE is missing, is not a string, or is not the 32 bytes /R 5 requires",
)?,
ue: fixed_string(
get(b"UE").as_ref(),
"/UE is missing, is not a string, or is not the 32 bytes /R 5 requires",
)?,
perms: fixed_string(
get(b"Perms").as_ref(),
"/Perms is missing, is not a string, or is not the 16 bytes /R 5 requires",
)?,
})
} else {
None
};
Ok(Self {
version,
revision,
key_len,
o,
u,
p,
encrypt_metadata,
stream_cipher,
string_cipher,
aes256,
})
}
fn is_r5(&self) -> bool {
self.revision == 5 || self.revision == 6
}
#[must_use]
pub fn permissions(&self) -> Permissions {
Permissions {
raw: self.p,
revision: self.revision,
}
}
#[allow(clippy::indexing_slicing)]
fn file_key_from_user_password(&self, password: &[u8], id0: &[u8]) -> Vec<u8> {
let mut h = Md5::new();
h.update(&pad_password(password)); h.update(&self.o); h.update(&self.p.to_le_bytes()); h.update(id0); if self.revision >= 4 && !self.encrypt_metadata {
h.update(&[0xFF, 0xFF, 0xFF, 0xFF]); }
let mut digest = h.finish();
if self.revision >= 3 {
for _ in 0..50 {
digest = md5(&digest[..self.key_len.min(digest.len())]);
}
}
digest[..self.key_len.min(digest.len())].to_vec() }
#[allow(clippy::indexing_slicing)]
fn owner_rc4_key(&self, owner_password: &[u8]) -> Vec<u8> {
let mut digest = md5(&pad_password(owner_password)); if self.revision >= 3 {
for _ in 0..50 {
digest = md5(&digest);
}
}
digest[..self.key_len.min(digest.len())].to_vec() }
fn expected_u(&self, file_key: &[u8], id0: &[u8]) -> Vec<u8> {
if self.revision == 2 {
rc4(file_key, &PADDING)
} else {
let mut h = Md5::new();
h.update(&PADDING);
h.update(id0);
let digest = h.finish();
let mut out = rc4(file_key, &digest);
for counter in 1u8..=19 {
let key: Vec<u8> = file_key.iter().map(|b| b ^ counter).collect();
out = rc4(&key, &out);
}
out
}
}
#[allow(clippy::indexing_slicing)]
fn try_user_password(&self, password: &[u8], id0: &[u8]) -> Option<Vec<u8>> {
let key = self.file_key_from_user_password(password, id0);
let expect = self.expected_u(&key, id0);
let n = if self.revision == 2 { 32 } else { 16 };
if self.u.len() >= n && expect.len() >= n && expect[..n] == self.u[..n] {
Some(key)
} else {
None
}
}
fn try_owner_password(&self, password: &[u8], id0: &[u8]) -> Option<Vec<u8>> {
let key = self.owner_rc4_key(password);
let user_pw = if self.revision == 2 {
rc4(&key, &self.o)
} else {
let mut data = self.o.clone();
for counter in (0u8..=19).rev() {
let k: Vec<u8> = key.iter().map(|b| b ^ counter).collect();
data = rc4(&k, &data);
}
data
};
self.try_user_password(&user_pw, id0)
}
fn authenticate_r5(&self, password: &[u8]) -> Option<(Vec<u8>, AuthKind)> {
let keys = self.aes256.as_ref()?;
let o: &[u8; OU_LEN] = self.o.as_slice().try_into().ok()?;
let u: &[u8; OU_LEN] = self.u.as_slice().try_into().ok()?;
let prepared = PreparedPassword::new(password);
let hasher = if self.revision == 6 {
r5::Hasher::R6(crate::crypto::r6::A13Reading::default())
} else {
r5::Hasher::Sha256
};
if r5::authenticates_as_user(&prepared, u, hasher) {
let key = r5::file_key_from_user_password(&prepared, u, &keys.ue, hasher)?;
let kind = if password.is_empty() {
AuthKind::EmptyUser
} else {
AuthKind::User
};
return Some((key.to_vec(), kind));
}
if r5::authenticates_as_owner(&prepared, o, u, hasher) {
let key = r5::file_key_from_owner_password(&prepared, o, u, &keys.oe, hasher)?;
return Some((key.to_vec(), AuthKind::Owner));
}
None
}
#[must_use]
pub fn password_may_need_normalisation(&self, password: &[u8]) -> bool {
self.is_r5() && PreparedPassword::new(password).needs_saslprep()
}
#[must_use]
pub fn check_perms(&self, key: &FileKey) -> PermsCheck {
let Some(keys) = self.aes256.as_ref() else {
return PermsCheck::NotApplicable;
};
let Ok(file_key) = <[u8; KEY_LEN_256]>::try_from(key.key.as_slice()) else {
return PermsCheck::MarkerMissing;
};
r5::validate_perms(&file_key, &keys.perms, self.p, self.encrypt_metadata)
}
#[must_use]
pub fn authenticate(&self, password: Option<&[u8]>, id0: &[u8]) -> Option<(FileKey, AuthKind)> {
let make = |key: Vec<u8>, kind: AuthKind| {
Some((
FileKey {
key,
version: self.version,
stream_cipher: self.stream_cipher,
string_cipher: self.string_cipher,
},
kind,
))
};
if self.is_r5() {
if let Some((key, kind)) = self.authenticate_r5(b"") {
if password.is_none_or(<[u8]>::is_empty) {
return make(key, kind);
}
if let Some(pw) = password
&& let Some((okey, AuthKind::Owner)) = self.authenticate_r5(pw)
{
return make(okey, AuthKind::Owner);
}
return make(key, kind);
}
let pw = password?;
let (key, kind) = self.authenticate_r5(pw)?;
return make(key, kind);
}
if let Some(key) = self.try_user_password(b"", id0) {
if password.is_none_or(<[u8]>::is_empty) {
return make(key, AuthKind::EmptyUser);
}
if let Some(pw) = password
&& let Some(okey) = self.try_owner_password(pw, id0)
{
return make(okey, AuthKind::Owner);
}
return make(key, AuthKind::EmptyUser);
}
let pw = password?;
if let Some(key) = self.try_user_password(pw, id0) {
return make(key, AuthKind::User);
}
if let Some(key) = self.try_owner_password(pw, id0) {
return make(key, AuthKind::Owner);
}
None
}
}
#[derive(Debug, Clone)]
pub struct FileKey {
key: Vec<u8>,
version: i64,
stream_cipher: Cipher,
string_cipher: Cipher,
}
impl FileKey {
#[must_use]
pub fn raw_key(&self) -> &[u8] {
&self.key
}
#[must_use]
#[allow(clippy::indexing_slicing)]
pub fn object_key(&self, id: ObjId, cipher: Cipher) -> Vec<u8> {
if self.version >= 5 {
return self.key.clone();
}
let mut h = Md5::new();
h.update(&self.key);
let num = id.num.to_le_bytes();
h.update(&num[..3]); let generation = id.generation.to_le_bytes();
h.update(&generation[..2]); if cipher == Cipher::Aes128 {
h.update(b"sAlT");
}
let digest = h.finish();
let n = (self.key.len() + 5).min(16);
digest[..n].to_vec()
}
#[must_use]
pub fn decrypt_string(&self, id: ObjId, data: &[u8]) -> Vec<u8> {
match self.string_cipher {
Cipher::None => data.to_vec(),
Cipher::Rc4 => rc4(&self.object_key(id, Cipher::Rc4), data),
Cipher::Aes128 => decrypt_cbc_128(&self.object_key(id, Cipher::Aes128), data),
Cipher::Aes256 => decrypt_cbc_256(&self.object_key(id, Cipher::Aes256), data),
}
}
#[must_use]
pub fn decrypt_stream(&self, id: ObjId, data: &[u8]) -> Vec<u8> {
match self.stream_cipher {
Cipher::None => data.to_vec(),
Cipher::Rc4 => rc4(&self.object_key(id, Cipher::Rc4), data),
Cipher::Aes128 => decrypt_cbc_128(&self.object_key(id, Cipher::Aes128), data),
Cipher::Aes256 => decrypt_cbc_256(&self.object_key(id, Cipher::Aes256), data),
}
}
#[must_use]
pub fn encrypt_string(&self, id: ObjId, data: &[u8], iv: &[u8; 16]) -> Vec<u8> {
self.encrypt_with(self.string_cipher, id, data, iv)
}
#[must_use]
pub fn encrypt_stream(&self, id: ObjId, data: &[u8], iv: &[u8; 16]) -> Vec<u8> {
self.encrypt_with(self.stream_cipher, id, data, iv)
}
#[must_use]
pub fn string_cipher(&self) -> Cipher {
self.string_cipher
}
#[must_use]
pub fn stream_cipher(&self) -> Cipher {
self.stream_cipher
}
fn encrypt_with(&self, cipher: Cipher, id: ObjId, data: &[u8], iv: &[u8; 16]) -> Vec<u8> {
let key = self.object_key(id, cipher);
match cipher {
Cipher::None => data.to_vec(),
Cipher::Rc4 => rc4(&key, data),
Cipher::Aes128 => <[u8; 16]>::try_from(key.as_slice())
.map_or_else(|_| Vec::new(), |k| encrypt_cbc_128(&k, iv, data)),
Cipher::Aes256 => <[u8; 32]>::try_from(key.as_slice())
.map_or_else(|_| Vec::new(), |k| encrypt_cbc_256(&k, iv, data)),
}
}
#[must_use]
pub fn strings_encrypted(&self) -> bool {
self.string_cipher != Cipher::None
}
#[must_use]
pub fn streams_encrypted(&self) -> bool {
self.stream_cipher != Cipher::None
}
}
fn fixed_string<const N: usize>(
value: Option<&Object>,
message: &'static str,
) -> Result<[u8; N], EncryptionUnsupported> {
match value {
Some(Object::String(s)) => {
<[u8; N]>::try_from(s.as_slice()).map_err(|_| EncryptionUnsupported::Malformed(message))
}
_ => Err(EncryptionUnsupported::Malformed(message)),
}
}
#[must_use]
#[allow(clippy::indexing_slicing)]
pub fn pad_password(password: &[u8]) -> [u8; 32] {
let mut out = [0u8; 32];
let take = password.len().min(32);
out[..take].copy_from_slice(&password[..take]);
out[take..].copy_from_slice(&PADDING[..32 - take]);
out
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
use crate::object::Name;
#[test]
fn empty_password_is_the_padding_string() {
assert_eq!(pad_password(b""), PADDING);
}
#[test]
fn short_password_takes_the_padding_prefix() {
let p = pad_password(b"abc");
assert_eq!(&p[..3], b"abc");
assert_eq!(&p[3..], &PADDING[..29]);
}
#[test]
fn long_password_is_truncated_not_hashed() {
let long = vec![b'x'; 100];
assert_eq!(pad_password(&long), [b'x'; 32]);
let exact = vec![b'y'; 32];
assert_eq!(pad_password(&exact), [b'y'; 32]);
}
#[test]
fn p_is_hashed_as_unsigned_little_endian() {
let p = -44i64 as i32 as u32;
assert_eq!(p, 0xFFFF_FFD4);
assert_eq!(p.to_le_bytes(), [0xD4, 0xFF, 0xFF, 0xFF]);
}
#[test]
fn reserved_bits_report_none_rather_than_false() {
let raw = -44i64 as i32 as u32;
let r2 = Permissions { raw, revision: 2 };
let r3 = Permissions { raw, revision: 3 };
for bit in [
PermissionBit::FillForms,
PermissionBit::AccessibilityExtract,
PermissionBit::Assemble,
PermissionBit::PrintHighQuality,
] {
assert_eq!(r2.granted(bit), None, "{bit:?} is reserved at R2");
assert_eq!(r3.granted(bit), Some(true), "{bit:?} is set at R3");
}
for bit in [
PermissionBit::Print,
PermissionBit::ModifyContents,
PermissionBit::Copy,
PermissionBit::Annotate,
] {
assert!(
r2.granted(bit).is_some(),
"{bit:?} applies at every revision"
);
assert_eq!(r2.granted(bit), r3.granted(bit));
}
}
#[test]
fn permission_bit_positions_are_table_22() {
let all = PermissionBit::all();
assert_eq!(all.len(), 8, "Table 22 defines eight meaningful bits");
let mut seen: Vec<u32> = Vec::new();
for bit in all {
let p = bit.position();
assert!((3..=12).contains(&p), "{bit:?} at {p} is outside Table 22");
assert!(!seen.contains(&p), "two permissions claim bit {p}");
seen.push(p);
}
assert!(
!seen.contains(&7) && !seen.contains(&8),
"bits 7 and 8 are reserved"
);
}
#[test]
fn minus_44_grants_more_at_r3_than_at_r2() {
let raw = -44i64 as i32 as u32;
let r2 = Permissions { raw, revision: 2 };
let r4 = Permissions { raw, revision: 4 };
assert!(r2.print() && r4.print());
assert!(r2.copy() && r4.copy());
assert!(!r2.modify_contents() && !r4.modify_contents());
assert!(!r2.annotate() && !r4.annotate());
assert!(!r2.fill_forms() && r4.fill_forms());
assert!(!r2.accessibility_extract() && r4.accessibility_extract());
assert!(!r2.assemble() && r4.assemble());
assert!(!r2.print_high_quality() && r4.print_high_quality());
}
#[test]
fn object_key_truncates_object_number_to_three_bytes() {
let fk = FileKey {
key: vec![1, 2, 3, 4, 5],
version: 2,
stream_cipher: Cipher::Rc4,
string_cipher: Cipher::Rc4,
};
let a = fk.object_key(ObjId::new(1, 0), Cipher::Rc4);
let b = fk.object_key(ObjId::new(0x0100_0001, 0), Cipher::Rc4);
assert_eq!(a, b, "bits above 2^24 must not affect the key");
let c = fk.object_key(ObjId::new(2, 0), Cipher::Rc4);
assert_ne!(a, c);
assert_eq!(a.len(), 10);
}
#[test]
fn object_key_length_is_capped_at_sixteen() {
let fk = FileKey {
key: vec![0u8; 16],
version: 4,
stream_cipher: Cipher::Rc4,
string_cipher: Cipher::Rc4,
};
assert_eq!(fk.object_key(ObjId::new(1, 0), Cipher::Rc4).len(), 16);
}
#[test]
fn aes_salt_changes_value_not_length() {
let fk = FileKey {
key: vec![9u8; 16],
version: 4,
stream_cipher: Cipher::Rc4,
string_cipher: Cipher::Rc4,
};
let plain = fk.object_key(ObjId::new(7, 0), Cipher::Rc4);
let salted = fk.object_key(ObjId::new(7, 0), Cipher::Aes128);
assert_eq!(plain.len(), salted.len());
assert_ne!(plain, salted);
}
fn name(s: &str) -> Object {
Object::Name(Name(s.as_bytes().to_vec()))
}
fn nothing(_: ObjId) -> Option<Object> {
None
}
fn minimal_encrypt(entries: Vec<(&str, Object)>) -> Dict {
let mut d = Dict::new();
d.insert(Name(b"Filter".to_vec()), name("Standard"));
d.insert(Name(b"O".to_vec()), Object::String(vec![0u8; 32]));
d.insert(Name(b"U".to_vec()), Object::String(vec![0u8; 32]));
d.insert(Name(b"P".to_vec()), Object::Integer(-44));
for (k, v) in entries {
d.insert(Name(k.as_bytes().to_vec()), v);
}
d
}
#[test]
fn hostile_encrypt_dictionaries_never_panic() {
let strings = [0usize, 1, 31, 32, 33, 47, 48, 49, 4096];
let ints = [
i64::MIN,
-1,
0,
1,
2,
3,
4,
5,
6,
7,
8,
39,
41,
127,
129,
256,
i64::MAX,
];
let mut dicts = Vec::new();
for v in [1i64, 2, 4, 5] {
for r in [2i64, 3, 4, 5, 6] {
for len in ints {
dicts.push(minimal_encrypt(vec![
("V", Object::Integer(v)),
("R", Object::Integer(r)),
("Length", Object::Integer(len)),
]));
}
for n in strings {
for key in ["O", "U", "OE", "UE", "Perms"] {
dicts.push(minimal_encrypt(vec![
("V", Object::Integer(v)),
("R", Object::Integer(r)),
(key, Object::String(vec![7u8; n])),
]));
}
}
for key in [
"V",
"R",
"Length",
"P",
"O",
"U",
"CF",
"StmF",
"EncryptMetadata",
] {
dicts.push(minimal_encrypt(vec![
("V", Object::Integer(v)),
("R", Object::Integer(r)),
(key, Object::Real(f64::NAN)),
]));
}
}
}
for v in ints {
dicts.push(minimal_encrypt(vec![
("V", Object::Integer(v)),
("R", Object::Integer(v)),
]));
}
for d in &dicts {
if let Ok(c) = EncryptionConfig::parse(d, ¬hing) {
for id0 in [&[][..], &[1u8; 16][..], &[2u8; 300][..]] {
for pw in [None, Some(&b""[..]), Some(&[0xFFu8; 200][..])] {
let _ = c.authenticate(pw, id0);
}
}
}
}
}
#[test]
fn refuses_undocumented_algorithms() {
for v in [0i64, 3] {
let d = minimal_encrypt(vec![("V", Object::Integer(v)), ("R", Object::Integer(3))]);
assert_eq!(
EncryptionConfig::parse(&d, ¬hing).unwrap_err(),
EncryptionUnsupported::UndocumentedAlgorithm(v)
);
}
let d = minimal_encrypt(vec![("R", Object::Integer(3))]);
assert_eq!(
EncryptionConfig::parse(&d, ¬hing).unwrap_err(),
EncryptionUnsupported::UndocumentedAlgorithm(0)
);
}
#[test]
fn refuses_missing_filter_as_a_conformance_matter() {
let mut d = minimal_encrypt(vec![("V", Object::Integer(2)), ("R", Object::Integer(3))]);
d.remove(b"Filter");
assert_eq!(
EncryptionConfig::parse(&d, ¬hing).unwrap_err(),
EncryptionUnsupported::NoFilter
);
}
#[test]
fn refuses_public_key_handler_by_name() {
let mut d = minimal_encrypt(vec![("V", Object::Integer(2)), ("R", Object::Integer(3))]);
d.insert(Name(b"Filter".to_vec()), name("Adobe.PubSec"));
assert!(matches!(
EncryptionConfig::parse(&d, ¬hing),
Err(EncryptionUnsupported::Handler(h)) if h == "Adobe.PubSec"
));
}
fn r5_encrypt(overrides: Vec<(&str, Object)>) -> Dict {
let mut cf = Dict::new();
let mut stdcf = Dict::new();
stdcf.insert(Name(b"CFM".to_vec()), name("AESV3"));
cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
let mut d = Dict::new();
d.insert(Name(b"Filter".to_vec()), name("Standard"));
d.insert(Name(b"V".to_vec()), Object::Integer(5));
d.insert(Name(b"R".to_vec()), Object::Integer(5));
d.insert(Name(b"Length".to_vec()), Object::Integer(256));
d.insert(Name(b"P".to_vec()), Object::Integer(-4));
d.insert(Name(b"O".to_vec()), Object::String(vec![0u8; 48]));
d.insert(Name(b"U".to_vec()), Object::String(vec![0u8; 48]));
d.insert(Name(b"OE".to_vec()), Object::String(vec![0u8; 32]));
d.insert(Name(b"UE".to_vec()), Object::String(vec![0u8; 32]));
d.insert(Name(b"Perms".to_vec()), Object::String(vec![0u8; 16]));
d.insert(Name(b"CF".to_vec()), Object::Dict(cf));
d.insert(Name(b"StmF".to_vec()), name("StdCF"));
d.insert(Name(b"StrF".to_vec()), name("StdCF"));
for (k, v) in overrides {
d.insert(Name(k.as_bytes().to_vec()), v);
}
d
}
#[test]
fn r5_parses_and_ignores_length_entirely() {
for length in [Object::Integer(256), Object::Integer(32)] {
let d = r5_encrypt(vec![("Length", length.clone())]);
let c = EncryptionConfig::parse(&d, ¬hing).expect("/R 5 is implemented");
assert_eq!(c.revision, 5);
assert_eq!(c.key_len, 32, "with /Length {length:?}");
assert_eq!(c.stream_cipher, Cipher::Aes256);
assert_eq!(c.string_cipher, Cipher::Aes256);
assert_eq!(c.o.len(), 48, "/O is 48 bytes at /R 5");
assert_eq!(c.u.len(), 48);
assert!(c.aes256.is_some());
}
let mut d = r5_encrypt(vec![]);
d.remove(b"Length");
assert_eq!(
EncryptionConfig::parse(&d, ¬hing)
.expect("supported")
.key_len,
32
);
}
#[test]
fn r6_parses_like_r5_now_that_algorithm_2b_is_sourced() {
let r6 = r5_encrypt(vec![("R", Object::Integer(6))]);
let cfg = EncryptionConfig::parse(&r6, ¬hing).expect("/R 6 parses");
assert_eq!(cfg.revision, 6);
assert_eq!(cfg.stream_cipher, Cipher::Aes256);
let mut broken = r5_encrypt(vec![("R", Object::Integer(6))]);
broken.remove(b"UE");
assert!(
EncryptionConfig::parse(&broken, ¬hing).is_err(),
"a structurally broken /R 6 dictionary is still refused"
);
assert!(EncryptionConfig::parse(&r5_encrypt(vec![]), ¬hing).is_ok());
}
#[test]
fn v5_and_r5_must_appear_together() {
for (v, r) in [(4i64, 5i64), (5, 4), (5, 3), (2, 5)] {
let d = r5_encrypt(vec![("V", Object::Integer(v)), ("R", Object::Integer(r))]);
assert!(
matches!(
EncryptionConfig::parse(&d, ¬hing),
Err(EncryptionUnsupported::Malformed(_))
),
"/V {v} with /R {r} must be refused"
);
}
}
#[test]
fn cfm_must_match_the_version_in_both_directions() {
let mut cf = Dict::new();
let mut stdcf = Dict::new();
stdcf.insert(Name(b"CFM".to_vec()), name("AESV3"));
cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
let v4_aesv3 = minimal_encrypt(vec![
("V", Object::Integer(4)),
("R", Object::Integer(4)),
("Length", Object::Integer(128)),
("CF", Object::Dict(cf)),
("StmF", name("StdCF")),
("StrF", name("StdCF")),
]);
assert!(
matches!(
EncryptionConfig::parse(&v4_aesv3, ¬hing),
Err(EncryptionUnsupported::Malformed(_))
),
"/AESV3 under /V 4 must be refused"
);
let mut cf = Dict::new();
let mut stdcf = Dict::new();
stdcf.insert(Name(b"CFM".to_vec()), name("AESV2"));
cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
let v5_aesv2 = r5_encrypt(vec![("CF", Object::Dict(cf))]);
assert!(
matches!(
EncryptionConfig::parse(&v5_aesv2, ¬hing),
Err(EncryptionUnsupported::Malformed(_))
),
"/AESV2 under /V 5 must be refused"
);
let identity = r5_encrypt(vec![("StrF", name("Identity"))]);
let c = EncryptionConfig::parse(&identity, ¬hing).expect("/Identity is legal at /V 5");
assert_eq!(c.string_cipher, Cipher::None);
assert_eq!(c.stream_cipher, Cipher::Aes256);
}
#[test]
fn r5_key_strings_are_required_at_exactly_their_lengths() {
for key in ["OE", "UE", "Perms"] {
let mut d = r5_encrypt(vec![]);
d.remove(key.as_bytes());
assert!(
matches!(
EncryptionConfig::parse(&d, ¬hing),
Err(EncryptionUnsupported::Malformed(_))
),
"a missing /{key} must be refused"
);
}
for len in [31usize, 33] {
let d = r5_encrypt(vec![("UE", Object::String(vec![0u8; len]))]);
assert!(
matches!(
EncryptionConfig::parse(&d, ¬hing),
Err(EncryptionUnsupported::Malformed(_))
),
"/UE of {len} bytes must be refused"
);
}
}
#[test]
fn r5_with_a_32_byte_o_is_refused_rather_than_guessed() {
let d = r5_encrypt(vec![("O", Object::String(vec![0u8; 32]))]);
assert!(matches!(
EncryptionConfig::parse(&d, ¬hing),
Err(EncryptionUnsupported::Malformed(_))
));
}
#[test]
fn r2_ignores_length() {
let d = minimal_encrypt(vec![
("V", Object::Integer(1)),
("R", Object::Integer(2)),
("Length", Object::Integer(128)),
]);
let c = EncryptionConfig::parse(&d, ¬hing).expect("R2 RC4 is supported");
assert_eq!(c.key_len, 5);
}
#[test]
fn absent_length_defaults_to_forty_bits() {
let d = minimal_encrypt(vec![("V", Object::Integer(2)), ("R", Object::Integer(3))]);
let c = EncryptionConfig::parse(&d, ¬hing).expect("R3 RC4 is supported");
assert_eq!(c.key_len, 5);
}
#[test]
fn encrypt_metadata_defaults_true() {
let d = minimal_encrypt(vec![("V", Object::Integer(2)), ("R", Object::Integer(3))]);
let c = EncryptionConfig::parse(&d, ¬hing).expect("supported");
assert!(c.encrypt_metadata);
}
#[test]
fn aesv2_resolves_to_the_aes_128_cipher() {
let mut cf = Dict::new();
let mut stdcf = Dict::new();
stdcf.insert(Name(b"CFM".to_vec()), name("AESV2"));
cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
let d = minimal_encrypt(vec![
("V", Object::Integer(4)),
("R", Object::Integer(4)),
("Length", Object::Integer(128)),
("CF", Object::Dict(cf)),
("StmF", name("StdCF")),
("StrF", name("StdCF")),
]);
let c = EncryptionConfig::parse(&d, ¬hing).expect("AES-128 is implemented");
assert_eq!(c.stream_cipher, Cipher::Aes128);
assert_eq!(c.string_cipher, Cipher::Aes128);
}
#[test]
fn v4_v2_filter_is_supported_and_stmf_strf_are_independent() {
let mut cf = Dict::new();
let mut stdcf = Dict::new();
stdcf.insert(Name(b"CFM".to_vec()), name("V2"));
cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
let d = minimal_encrypt(vec![
("V", Object::Integer(4)),
("R", Object::Integer(4)),
("Length", Object::Integer(128)),
("CF", Object::Dict(cf)),
("StmF", name("StdCF")),
("StrF", name("Identity")),
]);
let c = EncryptionConfig::parse(&d, ¬hing).expect("V2 crypt filter is supported");
assert_eq!(c.stream_cipher, Cipher::Rc4);
assert_eq!(c.string_cipher, Cipher::None);
assert_eq!(c.key_len, 16);
}
#[test]
fn refuses_stmf_naming_an_absent_crypt_filter() {
let d = minimal_encrypt(vec![
("V", Object::Integer(4)),
("R", Object::Integer(4)),
("CF", Object::Dict(Dict::new())),
("StmF", name("StdCF")),
]);
assert!(matches!(
EncryptionConfig::parse(&d, ¬hing),
Err(EncryptionUnsupported::Malformed(_))
));
}
#[test]
fn unknown_cfm_is_named() {
let mut cf = Dict::new();
let mut f = Dict::new();
f.insert(Name(b"CFM".to_vec()), name("Whirlpool"));
cf.insert(Name(b"StdCF".to_vec()), Object::Dict(f));
let d = minimal_encrypt(vec![
("V", Object::Integer(4)),
("R", Object::Integer(4)),
("CF", Object::Dict(cf)),
("StmF", name("StdCF")),
]);
assert!(matches!(
EncryptionConfig::parse(&d, ¬hing),
Err(EncryptionUnsupported::UnknownCfm(n)) if n == "Whirlpool"
));
}
}