mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 18:27:00 +01:00
975 lines
43 KiB
Rust
975 lines
43 KiB
Rust
//! The PDF standard security handler (ISO 32000-2 §7.6), for code that writes or edits PDF files.
|
||
//! The reader (`read`) decrypts on its own; this module also encrypts and creates encryption.
|
||
//!
|
||
//! Supports every revision of the standard handler:
|
||
//! - R2 (40-bit RC4), R3 (RC4 up to 128-bit), R4 (crypt filters: RC4 or AES-128);
|
||
//! - R5 (the deprecated AES-256 extension) and R6 (AES-256, PDF 2.0).
|
||
//!
|
||
//! It authenticates with the user or owner password (owner first, as viewers do) and derives
|
||
//! per-object keys. It decrypts and encrypts strings and streams, and honours crypt filters,
|
||
//! including `Identity` and embedded-file-only encryption. It can also *create* encryption
|
||
//! dictionaries, for an app's security settings and for test fixtures.
|
||
//!
|
||
//! The module knows nothing about a PDF object model. Callers pass in the values of the
|
||
//! `/Encrypt` dictionary and the first element of the trailer `/ID`.
|
||
|
||
mod aes_cbc;
|
||
mod rc4;
|
||
|
||
use md5::{Digest as _, Md5};
|
||
use sha2::{Sha256, Sha384, Sha512};
|
||
use zeroize::Zeroizing;
|
||
|
||
pub use aes_cbc::{aes_cbc_decrypt, aes_cbc_encrypt};
|
||
pub use rc4::rc4;
|
||
|
||
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
|
||
pub enum CryptError {
|
||
#[error("the password is incorrect")]
|
||
WrongPassword,
|
||
#[error("unsupported security handler: {0}")]
|
||
Unsupported(String),
|
||
#[error("malformed encryption dictionary: {0}")]
|
||
Malformed(String),
|
||
/// A crypt filter the document's strings, streams or embedded files use has a `/CFM` other
|
||
/// than `None`, `V2`, `AESV2` or `AESV3` (ISO 32000-2 Table 25: "Applications that encounter
|
||
/// other values shall report that the file is encrypted with an unsupported algorithm").
|
||
#[error("the file is encrypted with an unsupported algorithm: {0}")]
|
||
UnsupportedAlgorithm(String),
|
||
}
|
||
|
||
/// 32-byte padding string used by revisions 2–4 (§7.6.4.3.2, step a).
|
||
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,
|
||
];
|
||
|
||
/// How a crypt filter encrypts (`/CFM`).
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum Method {
|
||
/// `None` / the `Identity` filter: data is not encrypted.
|
||
Identity,
|
||
/// `V2`: RC4.
|
||
Rc4,
|
||
/// `AESV2`: AES-128-CBC.
|
||
Aes128,
|
||
/// `AESV3`: AES-256-CBC.
|
||
Aes256,
|
||
/// Any other `/CFM` (or one that isn't a name): a method this handler can't decrypt (ISO
|
||
/// 32000-2 Table 25 lists the only values to support). Data it encrypts is left as stored,
|
||
/// read and written alike, and [`SecurityHandler::open`] refuses a document whose strings,
|
||
/// streams or embedded files use it.
|
||
Unsupported,
|
||
}
|
||
|
||
/// The values of an `/Encrypt` dictionary that the handler needs.
|
||
#[derive(Clone, Debug, PartialEq, Default)]
|
||
pub struct EncryptDict {
|
||
/// `/Filter` (must be `Standard`).
|
||
pub filter: Vec<u8>,
|
||
pub v: i64,
|
||
pub r: i64,
|
||
/// File key length in bits: `/Length` (40 when absent, always 40 for `/V 1`), for `/V 4` the
|
||
/// crypt filter's (see `cos`). Revisions 2–4 clamp it to 40–128.
|
||
pub length_bits: i64,
|
||
pub o: Vec<u8>,
|
||
pub u: Vec<u8>,
|
||
pub oe: Vec<u8>,
|
||
pub ue: Vec<u8>,
|
||
pub perms: Vec<u8>,
|
||
pub p: i32,
|
||
pub encrypt_metadata: bool,
|
||
/// Crypt filters (`/CF`): name → (method, key length in bytes if given).
|
||
pub crypt_filters: Vec<(Vec<u8>, Method)>,
|
||
pub stm_f: Vec<u8>,
|
||
pub str_f: Vec<u8>,
|
||
pub ef_f: Vec<u8>,
|
||
}
|
||
|
||
/// Which password authenticated the document.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum Auth {
|
||
Owner,
|
||
User,
|
||
}
|
||
|
||
/// Permission flags from `/P`, read the way the handler's revision reads them (ISO 32000-1:2008,
|
||
/// Table 22). Owners have every permission.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub struct Permissions {
|
||
pub bits: i32,
|
||
pub owner: bool,
|
||
/// The `/R` value of the handler that read `bits`.
|
||
pub revision: i64,
|
||
}
|
||
|
||
impl Permissions {
|
||
fn bit(&self, n: u32) -> bool {
|
||
self.owner || (self.bits >> (n - 1)) & 1 == 1
|
||
}
|
||
/// Revision 3 and later read the full flag list of Table 22; revision 2 has its own.
|
||
fn is_revision_3_or_later(&self) -> bool {
|
||
self.revision >= 3
|
||
}
|
||
pub fn print(&self) -> bool {
|
||
self.bit(3)
|
||
}
|
||
/// Modify contents other than the operations below.
|
||
pub fn modify(&self) -> bool {
|
||
self.bit(4)
|
||
}
|
||
pub fn copy(&self) -> bool {
|
||
self.bit(5)
|
||
}
|
||
pub fn annotate(&self) -> bool {
|
||
self.bit(6)
|
||
}
|
||
pub fn fill_forms(&self) -> bool {
|
||
if self.is_revision_3_or_later() { self.bit(9) || self.bit(6) } else { self.bit(6) }
|
||
}
|
||
/// Revision 2 covers accessibility with the copy flag (bit 5); revision 3 and later with bit 10.
|
||
pub fn extract_for_accessibility(&self) -> bool {
|
||
if self.is_revision_3_or_later() { self.bit(10) } else { self.bit(5) }
|
||
}
|
||
/// Insert, rotate or delete pages; create bookmarks and thumbnails. Revision 3 and later grant
|
||
/// it by bit 11 alone. Table 22 defines bit 11 for those revisions only, so at revision 2 the
|
||
/// modify flag (bit 4) covers it.
|
||
pub fn assemble(&self) -> bool {
|
||
if self.is_revision_3_or_later() { self.bit(11) } else { self.bit(4) }
|
||
}
|
||
/// Take pages out into another document (Extract, Split, a source of Combine or Insert
|
||
/// Pages): [`Self::assemble`] and copying (bit 5), since the pages carry their text and
|
||
/// graphics into a new file without the document's protection (#5081). "Any except
|
||
/// extracting pages" sets bit 4 but not bit 11, so at revision 3 and later it grants neither.
|
||
pub fn extract_pages(&self) -> bool {
|
||
self.assemble() && self.copy()
|
||
}
|
||
/// Revision 3 and later need bit 3 as well as bit 12. Table 22 defines bit 12 for those
|
||
/// revisions only: at revision 2 the print flag (bit 3) is all there is.
|
||
pub fn print_high_quality(&self) -> bool {
|
||
if self.is_revision_3_or_later() { self.print() && self.bit(12) } else { self.print() }
|
||
}
|
||
}
|
||
|
||
/// What kind of stream is being decrypted (selects the crypt filter).
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum StreamKind<'a> {
|
||
Normal,
|
||
/// An embedded file stream (uses `/EFF`).
|
||
EmbeddedFile,
|
||
/// The stream names its own crypt filter (`/Filter [/Crypt …] /DecodeParms << /Name … >>`).
|
||
Named(&'a [u8]),
|
||
}
|
||
|
||
/// An authenticated security handler for one document.
|
||
#[derive(Clone, Debug)]
|
||
pub struct SecurityHandler {
|
||
dict: EncryptDict,
|
||
key: Zeroizing<Vec<u8>>,
|
||
auth: Auth,
|
||
recovered_user: Option<Zeroizing<Vec<u8>>>,
|
||
methods: Methods,
|
||
}
|
||
|
||
/// The crypt filter methods of a handler, resolved once: a document controls both the number of
|
||
/// filters and the number of strings, so a search of `/CF` per string would multiply them.
|
||
#[derive(Clone, Debug)]
|
||
struct Methods {
|
||
string: Method,
|
||
stream: Method,
|
||
embedded_file: Method,
|
||
named: std::collections::HashMap<Vec<u8>, Method>,
|
||
}
|
||
|
||
impl Methods {
|
||
fn new(dict: &EncryptDict) -> Self {
|
||
let mut named = std::collections::HashMap::with_capacity(dict.crypt_filters.len());
|
||
for (name, method) in &dict.crypt_filters {
|
||
#[cfg(test)]
|
||
tests::FILTER_COMPARES.with(|c| c.set(c.get() + 1));
|
||
// The first of two filters with one name wins, as a search would find it.
|
||
named.entry(name.clone()).or_insert(*method);
|
||
}
|
||
let mut methods = Methods { string: Method::Identity, stream: Method::Identity, embedded_file: Method::Identity, named };
|
||
methods.string = methods.get(&dict.str_f);
|
||
methods.stream = methods.get(&dict.stm_f);
|
||
methods.embedded_file = methods.get(if dict.ef_f.is_empty() { &dict.stm_f } else { &dict.ef_f });
|
||
methods
|
||
}
|
||
|
||
fn get(&self, name: &[u8]) -> Method {
|
||
if name == b"Identity" || name.is_empty() {
|
||
return Method::Identity;
|
||
}
|
||
#[cfg(test)]
|
||
tests::FILTER_COMPARES.with(|c| c.set(c.get() + 1));
|
||
self.named.get(name).copied().unwrap_or(Method::Identity)
|
||
}
|
||
}
|
||
|
||
impl SecurityHandler {
|
||
fn new(dict: EncryptDict, key: Zeroizing<Vec<u8>>, auth: Auth, recovered_user: Option<Zeroizing<Vec<u8>>>) -> Self {
|
||
let methods = Methods::new(&dict);
|
||
Self { dict, key, auth, recovered_user, methods }
|
||
}
|
||
|
||
/// Authenticate with `password` (tried as owner password, then user password). `None`
|
||
/// tries the empty password, which opens documents that only have an owner password.
|
||
pub fn open(dict: EncryptDict, id0: &[u8], password: Option<&str>) -> Result<Self, CryptError> {
|
||
if !dict.filter.is_empty() && dict.filter != b"Standard" {
|
||
return Err(CryptError::Unsupported(format!("/Filter /{}", String::from_utf8_lossy(&dict.filter))));
|
||
}
|
||
// Table 20: 1, 2 and 4 are the RC4/crypt-filter algorithms and 5 is AES-256; 0 (or no /V)
|
||
// reads as RC4 with /Length, as MuPDF and PDFium read it. 3 is unpublished and others are
|
||
// unknown: their data can't be decrypted.
|
||
if !matches!(dict.v, 0 | 1 | 2 | 4 | 5) {
|
||
return Err(CryptError::Unsupported(format!("/V {}", dict.v)));
|
||
}
|
||
// Before the password: no password reads data encrypted with a method this handler lacks.
|
||
if let Some(name) = unsupported_in_use(&dict) {
|
||
return Err(CryptError::UnsupportedAlgorithm(format!(
|
||
"crypt filter /{} has a /CFM other than None, V2, AESV2 or AESV3",
|
||
String::from_utf8_lossy(name)
|
||
)));
|
||
}
|
||
let pw = password.unwrap_or("");
|
||
let mut recovered_user = None;
|
||
// Every spelling as the owner password first, then every spelling as the user password:
|
||
// one typed password can be the user password in one spelling and the owner password in
|
||
// another.
|
||
let (key, auth) = match dict.r {
|
||
2..=4 => {
|
||
let candidates = legacy_candidates(pw);
|
||
if let Some((k, user)) = candidates.iter().find_map(|legacy| owner_key_r4(&dict, id0, legacy)) {
|
||
recovered_user = Some(user);
|
||
(k, Auth::Owner)
|
||
} else {
|
||
let user = candidates.iter().find_map(|legacy| user_key_r4(&dict, id0, legacy));
|
||
(user.ok_or(CryptError::WrongPassword)?, Auth::User)
|
||
}
|
||
}
|
||
5 | 6 => {
|
||
let candidates = aes256_candidates(pw);
|
||
if let Some(k) = first_key_r6(&dict, &candidates, true)? {
|
||
(k, Auth::Owner)
|
||
} else if let Some(k) = first_key_r6(&dict, &candidates, false)? {
|
||
(k, Auth::User)
|
||
} else {
|
||
return Err(CryptError::WrongPassword);
|
||
}
|
||
}
|
||
r => return Err(CryptError::Unsupported(format!("revision {r}"))),
|
||
};
|
||
Ok(Self::new(dict, key, auth, recovered_user))
|
||
}
|
||
|
||
/// A handler with no file key, for a document opened without a password whose strings and
|
||
/// streams aren't encrypted and whose encrypted crypt filters are all ones the caller found
|
||
/// authorised only when an embedded file is opened (`/AuthEvent /EFOpen`, ISO 32000-2 §7.6.6,
|
||
/// Table 25). Data such a filter encrypts is left as stored, read and written alike, so it
|
||
/// keeps its encrypted bytes; [`SecurityHandler::decrypts`] tells which. `None` when strings or
|
||
/// streams are encrypted, which needs the key, or the handler is older than crypt filters (V4).
|
||
pub fn without_key(dict: EncryptDict) -> Option<Self> {
|
||
if dict.v < 4 {
|
||
return None;
|
||
}
|
||
let methods = Methods::new(&dict);
|
||
if methods.string != Method::Identity || methods.stream != Method::Identity {
|
||
return None;
|
||
}
|
||
Some(Self { dict, key: Zeroizing::new(Vec::new()), auth: Auth::User, recovered_user: None, methods })
|
||
}
|
||
|
||
/// Whether the handler has the file key: false for [`SecurityHandler::without_key`].
|
||
pub fn has_key(&self) -> bool {
|
||
!self.key.is_empty()
|
||
}
|
||
|
||
/// Whether data of `kind` is encrypted, so that reading it needs the file key.
|
||
pub fn decrypts(&self, kind: StreamKind) -> bool {
|
||
self.method(Some(kind)) != Method::Identity
|
||
}
|
||
|
||
/// Whether data of `kind` is encrypted with a method this handler can't decrypt
|
||
/// ([`Method::Unsupported`]): only a stream naming such a crypt filter for itself, as
|
||
/// [`SecurityHandler::open`] refuses one its strings, streams or embedded files use. That data
|
||
/// is left as stored, and isn't what it encrypts.
|
||
pub fn cannot_decrypt(&self, kind: StreamKind) -> bool {
|
||
self.method(Some(kind)) == Method::Unsupported
|
||
}
|
||
|
||
/// Whether data left as stored by a handler without the key still decrypts after its object
|
||
/// is renumbered: only AES-256 with a 256-bit file key doesn't mix the object number into the
|
||
/// key (Algorithm 1.A).
|
||
pub fn survives_renumbering(&self) -> bool {
|
||
let direct = self.uses_file_key_directly();
|
||
[self.methods.string, self.methods.stream, self.methods.embedded_file]
|
||
.into_iter()
|
||
.chain(self.methods.named.values().copied())
|
||
.all(|m| m == Method::Identity || (m == Method::Aes256 && direct))
|
||
}
|
||
|
||
/// Whether `AESV3` data is encrypted with the file key itself (Algorithm 1.A, §7.6.3.3) rather
|
||
/// than a per-object key (Algorithm 1, §7.6.3.2): for `/V 5` (§7.6.3.1) and for a 256-bit file
|
||
/// key, the only kind Algorithm 1.A is for, which revisions 5 and 6 make (a handler without
|
||
/// the key goes by the revision). A `/V 4` handler of revision 4 or earlier that names
|
||
/// `/CFM /AESV3` (§7.6.4.1 allows only `V2` or `AESV2` at revision 4, and Table 25 asks for a
|
||
/// 256-bit key with `AESV3`) has a key of at most 128 bits. The files seen in practice derive
|
||
/// per-object keys from it as for `AESV2`, MD5 of the key, the object, the generation and
|
||
/// "sAlT", and qpdf and PDFium read them that way too.
|
||
fn uses_file_key_directly(&self) -> bool {
|
||
self.dict.v >= 5 || self.dict.r >= 5 || self.key.len() == 32
|
||
}
|
||
|
||
/// Upgrade to owner access with the owner (permissions) password, as when a restricted
|
||
/// document is unlocked after opening. The user password, or any other, is `WrongPassword`.
|
||
/// Both passwords unlock the same file key, so what was decrypted so far stays valid; a
|
||
/// different key is refused too.
|
||
pub fn authenticate_owner(&self, id0: &[u8], password: &str) -> Result<Self, CryptError> {
|
||
let owner = Self::open(self.dict.clone(), id0, Some(password))?;
|
||
if owner.auth != Auth::Owner || !same(owner.key.as_slice(), self.key.as_slice()) {
|
||
return Err(CryptError::WrongPassword);
|
||
}
|
||
Ok(owner)
|
||
}
|
||
|
||
pub fn auth(&self) -> Auth {
|
||
self.auth
|
||
}
|
||
|
||
/// For R2–R4 documents opened with the owner password: the user password, which owner
|
||
/// authentication recovers (Algorithm 7). Lets components that only accept user passwords
|
||
/// open the document too.
|
||
pub fn recovered_user_password(&self) -> Option<Zeroizing<Vec<u8>>> {
|
||
self.recovered_user.clone()
|
||
}
|
||
|
||
/// For R5/R6, `/P` is stored in clear and again in `/Perms`, encrypted with the file key
|
||
/// (Algorithm 13). Where the two differ, a permission counts only when both grant it, so an
|
||
/// edited `/P` grants nothing extra. Without a readable `/Perms`, `/P` applies as before.
|
||
pub fn permissions(&self) -> Permissions {
|
||
let bits = self.perms_p().map_or(self.dict.p, |p| self.dict.p & p);
|
||
Permissions { bits, owner: self.auth == Auth::Owner, revision: self.dict.r }
|
||
}
|
||
|
||
/// `/P` as `/Perms` holds it: AES-256 ECB of one block (= CBC with a zero IV), marked `adb`.
|
||
fn perms_p(&self) -> Option<i32> {
|
||
let plain = self.perms_block()?;
|
||
Some(i32::from_le_bytes(*plain.first_chunk::<4>()?))
|
||
}
|
||
|
||
/// `/Perms` decrypted (Algorithm 13 step a), when it is one block marked `adb` (bytes 9–11).
|
||
fn perms_block(&self) -> Option<Zeroizing<Vec<u8>>> {
|
||
if !matches!(self.dict.r, 5 | 6) || !self.has_key() {
|
||
return None;
|
||
}
|
||
let plain = Zeroizing::new(aes_cbc_decrypt(&self.key, &[0; 16], self.dict.perms.first_chunk::<16>()?, false));
|
||
(plain.get(9..12) == Some(&b"adb"[..])).then_some(plain)
|
||
}
|
||
|
||
/// Whether byte 8 of a readable `/Perms` isn't the `T` or `F` that `/EncryptMetadata` gives
|
||
/// (Algorithm 13 step a, ISO 32000-2 §7.6.4.4.12: it "should match"). A "should", so the
|
||
/// document still opens, metadata read as `/EncryptMetadata` says: qpdf warns of it, and MuPDF
|
||
/// and PDFium open such files. False when `/Perms` can't be read, which [`Self::permissions`]
|
||
/// already reads past.
|
||
pub fn perms_metadata_mismatch(&self) -> bool {
|
||
let expected = if self.dict.encrypt_metadata { b'T' } else { b'F' };
|
||
self.perms_block().is_some_and(|plain| plain.get(8) != Some(&expected))
|
||
}
|
||
|
||
pub fn dict(&self) -> &EncryptDict {
|
||
&self.dict
|
||
}
|
||
|
||
/// The file encryption key (for tests and diagnostics).
|
||
pub fn file_key(&self) -> &[u8] {
|
||
&self.key
|
||
}
|
||
|
||
/// Whether `/Metadata` streams are encrypted.
|
||
pub fn encrypts_metadata(&self) -> bool {
|
||
self.dict.encrypt_metadata
|
||
}
|
||
|
||
/// The method for strings or a kind of stream.
|
||
fn method(&self, stream: Option<StreamKind>) -> Method {
|
||
if self.dict.v < 4 {
|
||
return Method::Rc4;
|
||
}
|
||
match stream {
|
||
None => self.methods.string,
|
||
Some(StreamKind::Normal) => self.methods.stream,
|
||
Some(StreamKind::EmbeddedFile) => self.methods.embedded_file,
|
||
Some(StreamKind::Named(n)) => self.methods.get(n),
|
||
}
|
||
}
|
||
|
||
/// Algorithm 1 (§7.6.3.2): the key for one object. AES-256 with a 256-bit file key uses the
|
||
/// file key directly (Algorithm 1.A, §7.6.3.3); with a shorter one it is derived as for
|
||
/// AES-128 (see [`Self::uses_file_key_directly`]).
|
||
///
|
||
/// For an RC4 crypt filter under `/V 4`, a file key shorter than 16 bytes is first extended
|
||
/// to 16 bytes with zeros. The standard doesn't say so (Algorithm 1 takes the n-byte key as
|
||
/// it is), but that is how Acrobat writes and reads such files: a `/V 4` RC4 crypt filter
|
||
/// with a 40- or 48-bit key (pdf.js issue 19484). `hayro-syntax` (the `read` feature) reads them
|
||
/// the same way, so a page it shows is one this module can read and save. AES-128 keys are
|
||
/// left as they are: `AESV2` takes a 128-bit key (Table 25), and Acrobat's extension is only
|
||
/// seen with RC4. Every key [`create`] makes under `/V 4` is 16 bytes already.
|
||
fn object_key(&self, method: Method, num: u32, generation: u16) -> Zeroizing<Vec<u8>> {
|
||
if method == Method::Aes256 && self.uses_file_key_directly() {
|
||
return self.key.clone();
|
||
}
|
||
let mut key = self.key.clone();
|
||
if method == Method::Rc4 && self.dict.v == 4 && key.len() < 16 {
|
||
key.resize(16, 0);
|
||
}
|
||
let mut h = Md5::new();
|
||
h.update(&key);
|
||
h.update(&num.to_le_bytes()[..3]);
|
||
h.update(generation.to_le_bytes());
|
||
if matches!(method, Method::Aes128 | Method::Aes256) {
|
||
h.update(b"sAlT");
|
||
}
|
||
let mut digest = Zeroizing::new(h.finalize().to_vec());
|
||
digest.truncate((key.len() + 5).min(16));
|
||
digest
|
||
}
|
||
|
||
fn apply(&self, method: Method, num: u32, generation: u16, data: &[u8], encrypt: bool) -> Vec<u8> {
|
||
// Without the key, encrypted data stays as stored (see `without_key`).
|
||
if !self.has_key() {
|
||
return data.to_vec();
|
||
}
|
||
match method {
|
||
// Data whose method is unknown keeps the bytes it has, so a save writes it back as it was.
|
||
Method::Identity | Method::Unsupported => data.to_vec(),
|
||
Method::Rc4 => rc4(&self.object_key(method, num, generation), data),
|
||
Method::Aes128 | Method::Aes256 => {
|
||
let key = self.object_key(method, num, generation);
|
||
if encrypt {
|
||
// Deterministic IV derived from the key, object and content: saves are
|
||
// reproducible and no IV repeats for different plaintexts.
|
||
let mut h = Sha256::new();
|
||
h.update(&key);
|
||
h.update(num.to_le_bytes());
|
||
h.update(generation.to_le_bytes());
|
||
h.update(data);
|
||
let digest = h.finalize();
|
||
let mut iv = [0u8; 16];
|
||
for (d, s) in iv.iter_mut().zip(digest.iter()) {
|
||
*d = *s;
|
||
}
|
||
let mut out = iv.to_vec();
|
||
out.extend(aes_cbc_encrypt(&key, &iv, data, true));
|
||
out
|
||
} else {
|
||
let Some((iv, body)) = data.split_first_chunk::<16>() else {
|
||
return Vec::new(); // only (part of) an IV: empty plaintext
|
||
};
|
||
aes_cbc_decrypt(&key, iv, body, true)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
pub fn decrypt_string(&self, num: u32, generation: u16, data: &[u8]) -> Vec<u8> {
|
||
self.apply(self.method(None), num, generation, data, false)
|
||
}
|
||
|
||
pub fn encrypt_string(&self, num: u32, generation: u16, data: &[u8]) -> Vec<u8> {
|
||
self.apply(self.method(None), num, generation, data, true)
|
||
}
|
||
|
||
pub fn decrypt_stream(&self, num: u32, generation: u16, data: &[u8], kind: StreamKind) -> Vec<u8> {
|
||
self.apply(self.method(Some(kind)), num, generation, data, false)
|
||
}
|
||
|
||
pub fn encrypt_stream(&self, num: u32, generation: u16, data: &[u8], kind: StreamKind) -> Vec<u8> {
|
||
self.apply(self.method(Some(kind)), num, generation, data, true)
|
||
}
|
||
|
||
/// Whether strings are encrypted at all (false with `/StrF /Identity`).
|
||
pub fn encrypts_strings(&self) -> bool {
|
||
self.method(None) != Method::Identity
|
||
}
|
||
}
|
||
|
||
/// The name of a crypt filter `d`'s strings, streams or embedded files use (`/StrF`, `/StmF`,
|
||
/// `/EFF`, which defaults to `/StmF`) whose method is [`Method::Unsupported`]. Handlers older than
|
||
/// crypt filters (`/V` below 4) encrypt everything with RC4 whatever `/CF` says. A filter `/CF`
|
||
/// defines and nothing uses doesn't count: qpdf, MuPDF and PDFium all open such a file.
|
||
fn unsupported_in_use(d: &EncryptDict) -> Option<&[u8]> {
|
||
if d.v < 4 {
|
||
return None;
|
||
}
|
||
let ef = if d.ef_f.is_empty() { &d.stm_f } else { &d.ef_f };
|
||
[&d.str_f, &d.stm_f, ef].into_iter().map(Vec::as_slice).find(|name| {
|
||
*name != b"Identity" && d.crypt_filters.iter().find(|(n, _)| n.as_slice() == *name).is_some_and(|(_, m)| *m == Method::Unsupported)
|
||
})
|
||
}
|
||
|
||
// ── Passwords ──────────────────────────────────────────────────────────────────────────────────
|
||
|
||
/// PDFDocEncoding (ISO 32000-2 Annex D) where it differs from Latin-1: bytes 0x18–0x1F and
|
||
/// 0x80–0xA0 (0x9F is undefined). Here because R2–R4 passwords need it; an object layer that
|
||
/// decodes text strings can use it too.
|
||
const PDFDOC_LOW: [char; 8] = ['˘', 'ˇ', 'ˆ', '˙', '˝', '˛', '˚', '˜'];
|
||
const PDFDOC_HIGH: [char; 33] = [
|
||
'•', '†', '‡', '…', '—', '–', 'ƒ', '⁄', '‹', '›', '−', '‰', '„', '“', '”', '‘', '’', '‚', '™', 'fi', 'fl', 'Ł', 'Œ', 'Š', 'Ÿ', 'Ž', 'ı', 'ł', 'œ',
|
||
'š', 'ž', '\u{FFFD}', '€',
|
||
];
|
||
|
||
/// PDFDocEncoding → Unicode.
|
||
pub fn pdfdoc_char(c: u8) -> char {
|
||
match c {
|
||
0x18..=0x1F => PDFDOC_LOW[usize::from(c - 0x18)],
|
||
0x80..=0xA0 => PDFDOC_HIGH[usize::from(c - 0x80)],
|
||
_ => char::from(c),
|
||
}
|
||
}
|
||
|
||
/// Unicode → PDFDocEncoding, `None` for a character it lacks (ğ, ş, İ, Cyrillic, CJK, …).
|
||
pub fn pdfdoc_byte(c: char) -> Option<u8> {
|
||
let at = |table: &[char], base: u8| table.iter().position(|&t| t == c && t != '\u{FFFD}').and_then(|i| u8::try_from(i).ok()).map(|i| base + i);
|
||
at(&PDFDOC_LOW, 0x18).or_else(|| at(&PDFDOC_HIGH, 0x80)).or_else(|| match u32::from(c) {
|
||
0x18..=0x1F | 0x80..=0xA0 => None,
|
||
n => u8::try_from(n).ok(),
|
||
})
|
||
}
|
||
|
||
/// Revisions 2–4: the password in PDFDocEncoding (§7.6.4.3.2, Algorithm 2), at most 32 bytes.
|
||
/// Characters PDFDocEncoding lacks are dropped, as MuPDF drops them. U+FFFD stands for the byte
|
||
/// 0x9F, which PDFDocEncoding leaves undefined and [`pdfdoc_char`] reads as U+FFFD: a user
|
||
/// password with that byte, recovered with the owner password and handed on as text, reads back
|
||
/// to the same bytes.
|
||
fn legacy_password(pw: &str) -> Zeroizing<Vec<u8>> {
|
||
Zeroizing::new(pw.chars().filter_map(|c| if c == '\u{FFFD}' { Some(0x9F) } else { pdfdoc_byte(c) }).take(32).collect())
|
||
}
|
||
|
||
/// The bytes an R2–R4 password may have been written as: PDFDocEncoding, as the specification
|
||
/// asks; and for a password with any non-ASCII character, also its UTF-8 bytes. Tools write
|
||
/// those for a password with characters PDFDocEncoding lacks (ğ, ş, İ, …), and some for every
|
||
/// non-ASCII password, even one PDFDocEncoding holds (qpdf's `--password-mode=bytes` writes
|
||
/// "pässwört" as its UTF-8 bytes). An ASCII password is the same in both.
|
||
fn legacy_candidates(pw: &str) -> Vec<Zeroizing<Vec<u8>>> {
|
||
let mut out = vec![legacy_password(pw)];
|
||
if !pw.is_ascii() {
|
||
out.push(Zeroizing::new(pw.bytes().take(32).collect()));
|
||
}
|
||
out
|
||
}
|
||
|
||
/// The bytes an R5/R6 password may have been written as: its SASLprep form (Algorithm 2.A, step
|
||
/// a), and, where that differs, the password as typed, at most 127 bytes of UTF-8 each. qpdf,
|
||
/// MuPDF and PDFium key and read passwords without SASLprep, so a decomposed "café" or a no-break
|
||
/// space reaches the file as typed.
|
||
fn aes256_candidates(pw: &str) -> Vec<Zeroizing<Vec<u8>>> {
|
||
let prepared = sasl_password(pw);
|
||
let typed = Zeroizing::new(pw.as_bytes().get(..127).unwrap_or(pw.as_bytes()).to_vec());
|
||
if typed == prepared { vec![prepared] } else { vec![prepared, typed] }
|
||
}
|
||
|
||
/// Algorithm 2.A for each of `candidates` in turn: the first file key one of them unlocks.
|
||
fn first_key_r6(d: &EncryptDict, candidates: &[Zeroizing<Vec<u8>>], owner: bool) -> Result<Option<Zeroizing<Vec<u8>>>, CryptError> {
|
||
for pw in candidates {
|
||
if let Some(k) = key_r6(d, pw, owner)? {
|
||
return Ok(Some(k));
|
||
}
|
||
}
|
||
Ok(None)
|
||
}
|
||
|
||
/// Revisions 5–6: SASLprep (RFC 4013), UTF-8, at most 127 bytes.
|
||
fn sasl_password(pw: &str) -> Zeroizing<Vec<u8>> {
|
||
let prepped = Zeroizing::new(stringprep::saslprep(pw).map(|c| c.into_owned()).unwrap_or_else(|_| pw.to_string()));
|
||
let mut bytes = Zeroizing::new(prepped.as_bytes().to_vec());
|
||
bytes.truncate(127);
|
||
bytes
|
||
}
|
||
|
||
fn pad(pw: &[u8]) -> Zeroizing<[u8; 32]> {
|
||
let mut out = Zeroizing::new(PADDING);
|
||
let n = pw.len().min(32);
|
||
out[..n].copy_from_slice(&pw[..n]);
|
||
out[n..].copy_from_slice(&PADDING[..32 - n]);
|
||
out
|
||
}
|
||
|
||
/// The file key's length in bytes: `/Length` (in bits, 40 to 128). Algorithms 2 and 3 say 5 bytes
|
||
/// for revision 2 whatever `/Length` says, but qpdf, MuPDF and PDFium all take `/Length` at
|
||
/// revision 2 too (a `/V 2 /R 2 /Length 128` file opens in each of them only with a 16-byte key),
|
||
/// and so does this. `/V 1` is always 40 bits (Table 20), which the caller puts in `length_bits`.
|
||
fn key_len(d: &EncryptDict) -> usize {
|
||
// Provably in 5..=16 after the clamp, so the cast is lossless.
|
||
(d.length_bits.clamp(40, 128) / 8) as usize
|
||
}
|
||
|
||
// ── Revisions 2–4 ──────────────────────────────────────────────────────────────────────────────
|
||
|
||
/// Algorithm 2: file key from a (user) password.
|
||
fn file_key_r4(d: &EncryptDict, id0: &[u8], pw: &[u8]) -> Zeroizing<Vec<u8>> {
|
||
let n = key_len(d);
|
||
let mut h = Md5::new();
|
||
h.update(*pad(pw));
|
||
h.update(&d.o[..d.o.len().min(32)]);
|
||
h.update(d.p.to_le_bytes());
|
||
h.update(id0);
|
||
if d.r >= 4 && !d.encrypt_metadata {
|
||
h.update([0xFF; 4]);
|
||
}
|
||
let mut digest = Zeroizing::new(h.finalize().to_vec());
|
||
if d.r >= 3 {
|
||
for _ in 0..50 {
|
||
digest = Zeroizing::new(Md5::digest(&digest[..n]).to_vec());
|
||
}
|
||
}
|
||
digest.truncate(n);
|
||
digest
|
||
}
|
||
|
||
/// Algorithms 4/5: the `/U` value a key produces.
|
||
fn u_value_r4(d: &EncryptDict, id0: &[u8], key: &[u8]) -> Vec<u8> {
|
||
if d.r == 2 {
|
||
return rc4(key, &PADDING);
|
||
}
|
||
let mut h = Md5::new();
|
||
h.update(PADDING);
|
||
h.update(id0);
|
||
let mut x = rc4(key, &h.finalize());
|
||
for i in 1..=19u8 {
|
||
let k = Zeroizing::new(key.iter().map(|b| b ^ i).collect::<Vec<u8>>());
|
||
x = rc4(&k, &x);
|
||
}
|
||
x.extend_from_slice(&[0u8; 16]);
|
||
x
|
||
}
|
||
|
||
/// Whether `a` and `b` are equal, in time that depends only on their lengths: password-derived
|
||
/// digests, keys and verifiers are compared without stopping at the first differing byte.
|
||
fn same(a: &[u8], b: &[u8]) -> bool {
|
||
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||
}
|
||
|
||
/// Algorithm 6: authenticate a user password; returns the file key.
|
||
///
|
||
/// Some producers ignore `/EncryptMetadata false` when deriving the key (they omit the
|
||
/// `FF FF FF FF` of Algorithm 2, step f). Viewers open those files, so if the strict derivation
|
||
/// fails we retry the other way.
|
||
fn user_key_r4(d: &EncryptDict, id0: &[u8], pw: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
|
||
let check = |d: &EncryptDict| {
|
||
let key = file_key_r4(d, id0, pw);
|
||
let u = u_value_r4(d, id0, &key);
|
||
let n = if d.r == 2 { 32 } else { 16 };
|
||
(d.u.len() >= n && same(&u[..n], &d.u[..n])).then_some(key)
|
||
};
|
||
check(d).or_else(|| (d.r >= 4 && !d.encrypt_metadata).then(|| check(&EncryptDict { encrypt_metadata: true, ..d.clone() })).flatten())
|
||
}
|
||
|
||
/// The RC4 key derived from an owner password (Algorithm 3, steps a–d).
|
||
fn owner_rc4_key(d: &EncryptDict, owner_pw: &[u8]) -> Zeroizing<Vec<u8>> {
|
||
owner_rc4_key_hashing(d, owner_pw, 16)
|
||
}
|
||
|
||
/// Algorithm 3, steps a–d, with each of the 50 rehashes of step c taking the first `hashed` bytes
|
||
/// of the previous digest. The standard hashes the whole digest (16 bytes); some producers hash
|
||
/// only the first n bytes, as Algorithm 2 step h does (see [`owner_rc4_keys`]).
|
||
fn owner_rc4_key_hashing(d: &EncryptDict, owner_pw: &[u8], hashed: usize) -> Zeroizing<Vec<u8>> {
|
||
let n = key_len(d);
|
||
let mut digest = Zeroizing::new(Md5::digest(*pad(owner_pw)).to_vec());
|
||
if d.r >= 3 {
|
||
for _ in 0..50 {
|
||
let take = hashed.min(digest.len());
|
||
digest = Zeroizing::new(Md5::digest(digest.get(..take).unwrap_or(&digest)).to_vec());
|
||
}
|
||
}
|
||
digest.truncate(n);
|
||
digest
|
||
}
|
||
|
||
/// The RC4 keys an owner password may have been turned into. The first is Algorithm 3 as the
|
||
/// standard has it. For an R3 or R4 key shorter than 16 bytes some producers rehash only the first
|
||
/// n bytes in step c (as Algorithm 2 step h does for the file key), and qpdf and MuPDF accept an
|
||
/// owner password written that way, so it is tried too.
|
||
fn owner_rc4_keys(d: &EncryptDict, owner_pw: &[u8]) -> Vec<Zeroizing<Vec<u8>>> {
|
||
let n = key_len(d);
|
||
let mut keys = vec![owner_rc4_key(d, owner_pw)];
|
||
if d.r >= 3 && n < 16 {
|
||
keys.push(owner_rc4_key_hashing(d, owner_pw, n));
|
||
}
|
||
keys
|
||
}
|
||
|
||
type SecretBytes = Zeroizing<Vec<u8>>;
|
||
|
||
/// Algorithm 7: authenticate an owner password (recover the user password from `/O`).
|
||
/// Returns the file key and the recovered user password (padding removed).
|
||
fn owner_key_r4(d: &EncryptDict, id0: &[u8], pw: &[u8]) -> Option<(SecretBytes, SecretBytes)> {
|
||
owner_rc4_keys(d, pw).into_iter().find_map(|rk| owner_key_with(d, id0, &rk))
|
||
}
|
||
|
||
/// Algorithm 7 with one RC4 key from Algorithm 3, steps a–d.
|
||
fn owner_key_with(d: &EncryptDict, id0: &[u8], rk: &[u8]) -> Option<(SecretBytes, SecretBytes)> {
|
||
let mut user = Zeroizing::new(d.o[..d.o.len().min(32)].to_vec());
|
||
if d.r == 2 {
|
||
user = Zeroizing::new(rc4(rk, &user));
|
||
} else {
|
||
for i in (0..=19u8).rev() {
|
||
let k = Zeroizing::new(rk.iter().map(|b| b ^ i).collect::<Vec<u8>>());
|
||
user = Zeroizing::new(rc4(&k, &user));
|
||
}
|
||
}
|
||
let key = user_key_r4(d, id0, &user)?;
|
||
// The recovered value is the padded password: strip the padding suffix.
|
||
let len = (0..=32).find(|&i| user.len() >= 32 && user[i..32] == PADDING[..32 - i]).unwrap_or(user.len().min(32));
|
||
user.truncate(len);
|
||
Some((key, user))
|
||
}
|
||
|
||
// ── Revisions 5–6 ──────────────────────────────────────────────────────────────────────────────
|
||
|
||
/// The hash of a password for R5 (SHA-256) or R6 (Algorithm 2.B).
|
||
fn hash_r6(r: i64, pw: &[u8], salt: &[u8], udata: &[u8]) -> Zeroizing<Vec<u8>> {
|
||
let mut k = Zeroizing::new({
|
||
let mut h = Sha256::new();
|
||
h.update(pw);
|
||
h.update(salt);
|
||
h.update(udata);
|
||
h.finalize().to_vec()
|
||
});
|
||
if r == 5 {
|
||
return k;
|
||
}
|
||
let mut round = 0u32;
|
||
loop {
|
||
let mut k1 = Zeroizing::new(Vec::with_capacity(64 * (pw.len() + k.len() + udata.len())));
|
||
for _ in 0..64 {
|
||
k1.extend_from_slice(pw);
|
||
k1.extend_from_slice(&k);
|
||
k1.extend_from_slice(udata);
|
||
}
|
||
// `k` is always a SHA-2 digest (32, 48 or 64 bytes): key = its first 16 bytes, IV = the next 16.
|
||
let Some((key, rest)) = k.split_first_chunk::<16>() else { break };
|
||
let Some(iv) = rest.first_chunk::<16>() else { break };
|
||
let e = Zeroizing::new(aes_cbc_encrypt(key, iv, &k1, false));
|
||
let m = e.iter().take(16).map(|b| u32::from(*b)).sum::<u32>() % 3;
|
||
k = Zeroizing::new(match m {
|
||
0 => Sha256::digest(&*e).to_vec(),
|
||
1 => Sha384::digest(&*e).to_vec(),
|
||
_ => Sha512::digest(&*e).to_vec(),
|
||
});
|
||
round += 1;
|
||
if round >= 64 && e.last().is_none_or(|b| u32::from(*b) <= round - 32) {
|
||
break;
|
||
}
|
||
}
|
||
k.truncate(32);
|
||
k
|
||
}
|
||
|
||
/// Algorithm 2.A: authenticate as owner (`owner = true`) or user; returns the file key.
|
||
fn key_r6(d: &EncryptDict, pw: &[u8], owner: bool) -> Result<Option<Zeroizing<Vec<u8>>>, CryptError> {
|
||
if d.u.len() < 48 || d.o.len() < 48 {
|
||
return Err(CryptError::Malformed("/O and /U must be 48 bytes for R5/R6".into()));
|
||
}
|
||
let (hashed, encrypted, udata) = if owner { (&d.o[..48], &d.oe, &d.u[..48]) } else { (&d.u[..48], &d.ue, &[][..]) };
|
||
let verifier = hash_r6(d.r, pw, &hashed[32..40], udata);
|
||
if !same(verifier.as_slice(), &hashed[..32]) {
|
||
return Ok(None);
|
||
}
|
||
if encrypted.len() < 32 {
|
||
return Err(CryptError::Malformed("/OE or /UE must be 32 bytes".into()));
|
||
}
|
||
let k = hash_r6(d.r, pw, &hashed[40..48], udata);
|
||
Ok(Some(Zeroizing::new(aes_cbc_decrypt(&k, &[0; 16], &encrypted[..32], false))))
|
||
}
|
||
|
||
// ── Creating encryption ────────────────────────────────────────────────────────────────────────
|
||
|
||
/// Which encryption to create.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub enum Algorithm {
|
||
/// R2, 40-bit RC4 (legacy: [`create`] refuses it, [`create_legacy`] writes it).
|
||
Rc4_40,
|
||
/// R3, 128-bit RC4 (legacy: [`create`] refuses it, [`create_legacy`] writes it).
|
||
Rc4_128,
|
||
/// R4, AES-128 crypt filters.
|
||
Aes128,
|
||
/// R6, AES-256 (PDF 2.0; the default for new documents).
|
||
Aes256,
|
||
}
|
||
|
||
impl Algorithm {
|
||
/// Whether this is one of the broken legacy ciphers: read for compatibility, and refused for
|
||
/// new encryption by [`create`].
|
||
pub fn is_legacy(self) -> bool {
|
||
matches!(self, Algorithm::Rc4_40 | Algorithm::Rc4_128)
|
||
}
|
||
}
|
||
|
||
/// A password as [`create`] prepares it: for R2–R4 its PDFDocEncoding (characters it lacks
|
||
/// dropped), at most 32 bytes; for R6 its SASLprep (RFC 4013: soft hyphens and the like removed,
|
||
/// other spaces made plain, then NFKC; the password as given if SASLprep refuses it), in UTF-8,
|
||
/// at most 127 bytes.
|
||
fn prepared_password(algorithm: Algorithm, password: &str) -> Zeroizing<Vec<u8>> {
|
||
match algorithm {
|
||
Algorithm::Rc4_40 | Algorithm::Rc4_128 | Algorithm::Aes128 => legacy_password(password),
|
||
Algorithm::Aes256 => sasl_password(password),
|
||
}
|
||
}
|
||
|
||
/// The bytes new encryption with `algorithm` derives its keys from for `password`: for R2–R4 its
|
||
/// PDFDocEncoding cut or padded to exactly 32 bytes (Algorithm 2); for R6 its SASLprep (the
|
||
/// password as given if SASLprep refuses it), at most 127 bytes of UTF-8. Two passwords with the
|
||
/// same bytes are the same password to the file, and a password with the bytes of `""` opens it
|
||
/// without asking, so callers can refuse either before encrypting. Different bytes can still give
|
||
/// the same key (RC4-40 keeps 5 bytes of a hash). `create` still uses the user password for an
|
||
/// empty R2–R4 owner password.
|
||
pub fn effective_password(algorithm: Algorithm, password: &str) -> Vec<u8> {
|
||
let prepared = prepared_password(algorithm, password);
|
||
match algorithm {
|
||
Algorithm::Rc4_40 | Algorithm::Rc4_128 | Algorithm::Aes128 => pad(&prepared).to_vec(),
|
||
Algorithm::Aes256 => prepared.to_vec(),
|
||
}
|
||
}
|
||
|
||
/// Parameters for new encryption.
|
||
#[derive(Clone, Debug)]
|
||
pub struct NewEncryption<'a> {
|
||
pub algorithm: Algorithm,
|
||
pub user_password: &'a str,
|
||
pub owner_password: &'a str,
|
||
pub permissions: i32,
|
||
pub encrypt_metadata: bool,
|
||
/// 32 bytes of entropy for keys and salts (the caller supplies randomness, so this crate
|
||
/// needs no OS access and tests are deterministic).
|
||
pub seed: [u8; 32],
|
||
}
|
||
|
||
/// Expand `seed` into `n` bytes (SHA-256 in counter mode).
|
||
fn expand(seed: &[u8; 32], label: &[u8], n: usize) -> Vec<u8> {
|
||
let mut out = Vec::new();
|
||
let mut counter = 0u32;
|
||
while out.len() < n {
|
||
let mut h = Sha256::new();
|
||
h.update(seed);
|
||
h.update(label);
|
||
h.update(counter.to_le_bytes());
|
||
out.extend_from_slice(&h.finalize());
|
||
counter = counter.saturating_add(1);
|
||
}
|
||
out.truncate(n);
|
||
out
|
||
}
|
||
|
||
/// Sixteen bytes of file identifier from `seed` (SHA-256 in counter mode, label `id`).
|
||
///
|
||
/// `/ID` is written in the clear. Deriving it the same way as the file key keeps that public
|
||
/// value from being an unkeyed hash of the seed.
|
||
pub fn file_id(seed: &[u8; 32]) -> Vec<u8> {
|
||
expand(seed, b"id", 16)
|
||
}
|
||
|
||
/// Build the `/Encrypt` values and an authenticated (owner) handler for a new encryption.
|
||
///
|
||
/// The legacy RC4 schemes are refused, because RC4 is broken (`RFC 7465`) and a file written with
|
||
/// it protects nothing: [`create_legacy`] is the explicit way to write them.
|
||
pub fn create(params: &NewEncryption, id0: &[u8]) -> Result<SecurityHandler, CryptError> {
|
||
if params.algorithm.is_legacy() {
|
||
return Err(CryptError::Unsupported("RC4 encryption is legacy (RFC 7465); use create_legacy for a file an old reader must open".into()));
|
||
}
|
||
create_any(params, id0)
|
||
}
|
||
|
||
/// [`create`] without the RC4 gate: writes RC4-40 and RC4-128 too. For a file that must stay
|
||
/// readable by a reader without AES, and for tests that read and write every algorithm.
|
||
pub fn create_legacy(params: &NewEncryption, id0: &[u8]) -> Result<SecurityHandler, CryptError> {
|
||
create_any(params, id0)
|
||
}
|
||
|
||
fn create_any(params: &NewEncryption, id0: &[u8]) -> Result<SecurityHandler, CryptError> {
|
||
// R2 reserves bits 7-32; later revisions reserve bits 7-8 and 13-32.
|
||
// Reserved bits must be 1, and bits 1-2 must be 0 (§7.6.4.2).
|
||
let reserved = if params.algorithm == Algorithm::Rc4_40 { !0x3F } else { !0xFFF | 0xC0 };
|
||
let p = (params.permissions | reserved) & !0x3;
|
||
let mut d = EncryptDict { filter: b"Standard".to_vec(), p, encrypt_metadata: params.encrypt_metadata, ..Default::default() };
|
||
let user = prepared_password(params.algorithm, params.user_password);
|
||
let owner = prepared_password(params.algorithm, params.owner_password);
|
||
match params.algorithm {
|
||
Algorithm::Rc4_40 | Algorithm::Rc4_128 | Algorithm::Aes128 => {
|
||
(d.v, d.r, d.length_bits) = match params.algorithm {
|
||
Algorithm::Rc4_40 => (1, 2, 40),
|
||
Algorithm::Rc4_128 => (2, 3, 128),
|
||
_ => (4, 4, 128),
|
||
};
|
||
if params.algorithm == Algorithm::Aes128 {
|
||
d.crypt_filters = vec![(b"StdCF".to_vec(), Method::Aes128)];
|
||
d.stm_f = b"StdCF".to_vec();
|
||
d.str_f = b"StdCF".to_vec();
|
||
} else {
|
||
d.encrypt_metadata = true; // V < 4 always encrypts metadata
|
||
}
|
||
let owner = if params.owner_password.is_empty() { user.clone() } else { owner };
|
||
// Algorithm 3: /O
|
||
let rk = owner_rc4_key(&d, &owner);
|
||
let mut o = rc4(&rk, &*pad(&user));
|
||
if d.r >= 3 {
|
||
for i in 1..=19u8 {
|
||
let k = Zeroizing::new(rk.iter().map(|b| b ^ i).collect::<Vec<u8>>());
|
||
o = rc4(&k, &o);
|
||
}
|
||
}
|
||
d.o = o;
|
||
let key = file_key_r4(&d, id0, &user);
|
||
d.u = u_value_r4(&d, id0, &key);
|
||
Ok(SecurityHandler::new(d, key, Auth::Owner, Some(user)))
|
||
}
|
||
Algorithm::Aes256 => {
|
||
(d.v, d.r, d.length_bits) = (5, 6, 256);
|
||
d.crypt_filters = vec![(b"StdCF".to_vec(), Method::Aes256)];
|
||
d.stm_f = b"StdCF".to_vec();
|
||
d.str_f = b"StdCF".to_vec();
|
||
let key = Zeroizing::new(expand(¶ms.seed, b"file key", 32));
|
||
let salts = expand(¶ms.seed, b"salts", 32);
|
||
// Algorithm 8: /U, /UE
|
||
let mut u = hash_r6(6, &user, &salts[0..8], &[]).to_vec();
|
||
u.extend_from_slice(&salts[0..16]);
|
||
let uk = hash_r6(6, &user, &salts[8..16], &[]);
|
||
d.ue = aes_cbc_encrypt(&uk, &[0; 16], &key, false);
|
||
// Algorithm 9: /O, /OE
|
||
let mut o = hash_r6(6, &owner, &salts[16..24], &u).to_vec();
|
||
o.extend_from_slice(&salts[16..32]);
|
||
let ok = hash_r6(6, &owner, &salts[24..32], &u);
|
||
d.oe = aes_cbc_encrypt(&ok, &[0; 16], &key, false);
|
||
d.u = u;
|
||
d.o = o;
|
||
// Algorithm 10: /Perms
|
||
let mut perms = [0u8; 16];
|
||
perms[..4].copy_from_slice(&p.to_le_bytes());
|
||
perms[4..8].copy_from_slice(&[0xFF; 4]);
|
||
perms[8] = if d.encrypt_metadata { b'T' } else { b'F' };
|
||
perms[9..12].copy_from_slice(b"adb");
|
||
perms[12..16].copy_from_slice(&expand(¶ms.seed, b"perms", 4));
|
||
d.perms = aes_cbc_encrypt(&key, &[0; 16], &perms, false);
|
||
Ok(SecurityHandler::new(d, key, Auth::Owner, None))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Like [`create`], but only embedded file streams are encrypted (`/EFF` names the standard
|
||
/// filter; `/StmF` and `/StrF` are `/Identity`, §7.6.6). Needs crypt filters, so RC4-40 and
|
||
/// RC4-128 (V < 4) are refused rather than silently encrypting everything.
|
||
pub fn create_attachments_only(params: &NewEncryption, id0: &[u8]) -> Result<SecurityHandler, CryptError> {
|
||
if matches!(params.algorithm, Algorithm::Rc4_40 | Algorithm::Rc4_128) {
|
||
return Err(CryptError::Unsupported("encrypting only attachments needs AES (crypt filters)".into()));
|
||
}
|
||
let h = create(params, id0)?;
|
||
let mut dict = h.dict.clone();
|
||
dict.stm_f = b"Identity".to_vec();
|
||
dict.str_f = b"Identity".to_vec();
|
||
dict.ef_f = b"StdCF".to_vec();
|
||
Ok(SecurityHandler::new(dict, h.key, h.auth, h.recovered_user))
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests;
|