laminapdf_syntax/crypt/mod.rs
1//! Standard security handler decryption (ISO 32000-2 §7.6; ISO 32000-1 §7.6.3 for R2–R4):
2//! password authentication for revisions 2–6 and string/stream decryption with RC4,
3//! AES-128-CBC and AES-256-CBC.
4//!
5//! **Read only.** RC4 and MD5 are broken primitives that Lamina PDF only ever *reads*: nothing here
6//! encrypts. Writing encrypted files is full-editor E11 (AES-256 / R6 only).
7//!
8//! The file structure layer (`laminapdf-cos`) parses `/Encrypt`, fills a [`StandardSecurity`],
9//! calls [`authenticate`] and then [`decrypt`]s each string and stream with the
10//! [`FileKey`] it gets back.
11//!
12//! ```
13//! use laminapdf_syntax::crypt::{Cipher, decrypt, FileKey};
14//!
15//! // `/Identity` passes data through unchanged.
16//! let key = FileKey::from_bytes(vec![0; 16]);
17//! let out = decrypt(Cipher::Identity, &key, 1, 0, b"plain");
18//! assert_eq!((out.data.as_slice(), out.well_formed), (&b"plain"[..], true));
19//! ```
20//!
21//! Sources: research ch. 04 §7 (`docs/research/pdf/04-interactive-security.md`), the spec
22//! sections named on each item.
23
24mod aes;
25mod auth;
26mod key;
27mod perms;
28mod rc4;
29mod write;
30
31use std::fmt;
32
33pub use perms::Permissions;
34pub use write::{Entropy, Grant, Handler, NewHandler, PrintRight, SeededEntropy, encrypt, new_handler};
35
36/// A crypt filter method (`/CFM`, ISO 32000-2 Table 25) or the pre-V4 implicit cipher.
37///
38/// Added in 0.2.0.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub enum Cipher {
42 /// `/Identity` (or `/CFM /None`): the data is not encrypted.
43 Identity,
44 /// RC4 with a per-object key (`/V2`, and every V1/V2 handler). Deprecated.
45 Rc4,
46 /// AES-128-CBC with a per-object key (`/AESV2`). Deprecated in PDF 2.0.
47 Aes128,
48 /// AES-256-CBC with the file key (`/AESV3`, V5).
49 Aes256,
50}
51
52impl Cipher {
53 /// A short stable name: `"identity"`, `"rc4"`, `"aes-128"` or `"aes-256"`.
54 ///
55 /// Added in 0.2.0.
56 #[must_use]
57 pub const fn name(&self) -> &'static str {
58 match self {
59 Self::Identity => "identity",
60 Self::Rc4 => "rc4",
61 Self::Aes128 => "aes-128",
62 Self::Aes256 => "aes-256",
63 }
64 }
65}
66
67/// Which password authenticated the document.
68///
69/// Added in 0.2.0.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub enum PasswordKind {
72 /// The user ("open") password, possibly the empty one.
73 User,
74 /// The owner ("permissions") password.
75 Owner,
76}
77
78/// The values of a standard security handler's `/Encrypt` dictionary that authentication needs
79/// (ISO 32000-2 Table 21). The caller extracts them; byte strings are taken as stored.
80///
81/// Added in 0.2.0.
82#[derive(Clone, Copy, PartialEq, Eq)]
83pub struct StandardSecurity<'a> {
84 /// `/R`, 2–6.
85 pub revision: u8,
86 /// The file key length in bytes (`/Length` / 8): 5–16 for R2–R4 (R2 is always 5); ignored for
87 /// R5/R6, whose key is 32 bytes.
88 pub key_length: usize,
89 /// `/O` (32 bytes for R2–R4, 48 for R5/R6).
90 pub owner: &'a [u8],
91 /// `/U` (32 bytes for R2–R4, 48 for R5/R6).
92 pub user: &'a [u8],
93 /// `/OE` (R5/R6, 32 bytes; empty otherwise).
94 pub owner_encryption: &'a [u8],
95 /// `/UE` (R5/R6, 32 bytes; empty otherwise).
96 pub user_encryption: &'a [u8],
97 /// `/Perms` (R5/R6, 16 bytes), if present.
98 pub perms: Option<&'a [u8]>,
99 /// `/P` as an unsigned 32-bit value (see [`Permissions`]).
100 pub permissions: u32,
101 /// The first element of the trailer's `/ID` (empty when absent).
102 pub id0: &'a [u8],
103 /// `/EncryptMetadata` (default true).
104 pub encrypt_metadata: bool,
105}
106
107impl StandardSecurity<'_> {
108 /// The R2–R4 file key length in bytes, clamped to the 5–16 the spec allows.
109 fn key_bytes(&self) -> usize {
110 if self.revision == 2 {
111 5
112 } else {
113 self.key_length.clamp(5, 16)
114 }
115 }
116}
117
118impl fmt::Debug for StandardSecurity<'_> {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 f.debug_struct("StandardSecurity")
121 .field("revision", &self.revision)
122 .field("key_length", &self.key_length)
123 .field("permissions", &self.permissions)
124 .field("encrypt_metadata", &self.encrypt_metadata)
125 .finish_non_exhaustive()
126 }
127}
128
129/// The file encryption key. Its bytes are never printed.
130///
131/// Added in 0.2.0.
132#[derive(Clone, PartialEq, Eq)]
133pub struct FileKey(Vec<u8>);
134
135impl FileKey {
136 /// A key from raw bytes (5–16 for RC4/AES-128 handlers, 32 for AES-256).
137 ///
138 /// Added in 0.2.0.
139 #[must_use]
140 pub const fn from_bytes(bytes: Vec<u8>) -> Self {
141 Self(bytes)
142 }
143
144 /// The key length in bits.
145 ///
146 /// Added in 0.2.0.
147 #[must_use]
148 pub fn bits(&self) -> usize {
149 self.0.len().saturating_mul(8)
150 }
151}
152
153impl Drop for FileKey {
154 fn drop(&mut self) {
155 zeroize::Zeroize::zeroize(&mut self.0);
156 }
157}
158
159impl fmt::Debug for FileKey {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 write!(f, "FileKey(<{} bits redacted>)", self.bits())
162 }
163}
164
165/// A successful [`authenticate`].
166///
167/// Added in 0.2.0.
168#[derive(Debug, Clone, PartialEq, Eq)]
169#[non_exhaustive]
170pub struct Authenticated {
171 /// The file key.
172 pub key: FileKey,
173 /// Which password matched.
174 pub matched: PasswordKind,
175 /// R5/R6 with `/Perms`: whether it decrypted to a value consistent with `/P` and
176 /// `/EncryptMetadata` (ISO 32000-2 Algorithm 13). `None` when there is nothing to check.
177 pub perms_valid: Option<bool>,
178}
179
180/// SASLprep's mapping step (RFC 4013 §2.1): the non-ASCII spaces of RFC 3454 table C.1.2
181/// become U+0020 and the characters of table B.1 ("commonly mapped to nothing") are removed.
182/// The tables are a handful of code points, so this runs in every build.
183#[cfg(any(not(feature = "saslprep"), test))]
184fn saslprep_mapping(text: &str) -> String {
185 const SPACES: [char; 17] = [
186 '\u{00A0}', '\u{1680}', '\u{2000}', '\u{2001}', '\u{2002}', '\u{2003}', '\u{2004}', '\u{2005}', '\u{2006}',
187 '\u{2007}', '\u{2008}', '\u{2009}', '\u{200A}', '\u{200B}', '\u{202F}', '\u{205F}', '\u{3000}',
188 ];
189 let to_nothing = |c: char| {
190 matches!(
191 c,
192 '\u{00AD}'
193 | '\u{034F}'
194 | '\u{1806}'
195 | '\u{180B}'..='\u{180D}'
196 | '\u{200C}'
197 | '\u{200D}'
198 | '\u{2060}'
199 | '\u{FE00}'..='\u{FE0F}'
200 | '\u{FEFF}'
201 )
202 };
203 text.chars()
204 .filter_map(|c| {
205 if SPACES.contains(&c) {
206 Some(' ')
207 } else if to_nothing(c) {
208 None
209 } else {
210 Some(c)
211 }
212 })
213 .collect()
214}
215
216/// The password byte strings to try for `password` at `revision`.
217///
218/// R2–R4 passwords are PDFDocEncoding bytes: the input as given, then (if it is UTF-8 text with
219/// non-ASCII characters that all fit in Latin-1) its Latin-1 bytes, which PDFDocEncoding
220/// shares for most of the range. R5/R6 passwords are UTF-8 after SASLprep (RFC 4013), truncated
221/// to 127 bytes (ISO 32000-2 §7.6.4.3.3); input that isn't UTF-8 or that SASLprep rejects is
222/// tried as given.
223///
224/// Without the `saslprep` feature (the WASM modules, ADR 0016 §7), only SASLprep's mapping
225/// step (RFC 4013 §2.1: non-ASCII spaces to U+0020, characters "commonly mapped to nothing"
226/// removed) is applied; NFKC normalisation and the prohibited-character and bidi checks are
227/// left out, so a password that differs from its NFKC form must be normalised by the caller
228/// (`@laminapdf/sdk` does), and a password SASLprep would reject is tried mapped.
229fn candidates(password: &[u8], revision: u8) -> Vec<Vec<u8>> {
230 let text = std::str::from_utf8(password).ok();
231 if revision >= 5 {
232 // The prepared form is moved, not copied, out of the owned string it was built in, and
233 // overwritten when dropped.
234 #[cfg(feature = "saslprep")]
235 let prepared = zeroize::Zeroizing::new(match text.and_then(|t| stringprep::saslprep(t).ok()) {
236 Some(std::borrow::Cow::Owned(p)) => p.into_bytes(),
237 Some(std::borrow::Cow::Borrowed(p)) => p.as_bytes().to_vec(),
238 None => password.to_vec(),
239 });
240 // Without SASLprep the password is tried as given (feature `saslprep`).
241 #[cfg(not(feature = "saslprep"))]
242 let prepared =
243 zeroize::Zeroizing::new(text.map_or_else(|| password.to_vec(), |t| saslprep_mapping(t).into_bytes()));
244 let mut out = vec![key::prefix(&prepared, 127).to_vec()];
245 let raw = key::prefix(password, 127).to_vec();
246 if !out.contains(&raw) {
247 out.push(raw);
248 }
249 return out;
250 }
251 let mut out = vec![password.to_vec()];
252 if let Some(text) = text
253 && !text.is_ascii()
254 && let Some(latin1) = text
255 .chars()
256 .map(|c| u8::try_from(u32::from(c)).ok())
257 .collect::<Option<Vec<u8>>>()
258 {
259 out.push(latin1);
260 }
261 out
262}
263
264/// Authenticates `password` as the user then the owner password for R2–R4, owner first for R5/R6
265/// (ISO 32000-1
266/// Algorithms 6–7 for R2–R4; ISO 32000-2 Algorithms 11–12 with 2.A/2.B for R6; the single
267/// SHA-256 of Adobe Extension Level 3 for R5, which was never standardised and is read only).
268///
269/// Returns `None` when neither matches, or for a revision outside 2–6 or byte strings too
270/// short for it.
271///
272/// Added in 0.2.0.
273#[must_use]
274pub fn authenticate(sec: &StandardSecurity<'_>, password: &[u8]) -> Option<Authenticated> {
275 authenticate_as(sec, password, false)
276}
277
278/// Authenticates `password` as the owner password only (ISO 32000-1 Algorithm 7, ISO 32000-2
279/// Algorithm 12): for a password given as the permissions password. Unlike [`authenticate`],
280/// a password that is also the user password is found to be the owner's at R2–R4 too, whose
281/// user-first order would report it as the user's.
282///
283/// Returns `None` when it isn't the owner password, or for a revision outside 2–6.
284///
285/// Added in 0.7.0.
286#[must_use]
287pub fn authenticate_owner(sec: &StandardSecurity<'_>, password: &[u8]) -> Option<Authenticated> {
288 authenticate_as(sec, password, true)
289}
290
291/// [`authenticate`], or with `owner_only` [`authenticate_owner`]. The password candidates are
292/// overwritten before they are dropped.
293fn authenticate_as(sec: &StandardSecurity<'_>, password: &[u8], owner_only: bool) -> Option<Authenticated> {
294 let modern = match sec.revision {
295 2..=4 => false,
296 5 | 6 => true,
297 _ => return None,
298 };
299 let user = |pw: &[u8]| {
300 if modern {
301 auth::user_r5_r6(sec, pw)
302 } else {
303 auth::user_r2_r4(sec, pw)
304 }
305 };
306 let owner = |pw: &[u8]| {
307 if modern {
308 auth::owner_r5_r6(sec, pw)
309 } else {
310 auth::owner_r2_r4(sec, pw)
311 }
312 };
313 let mut candidates = candidates(password, sec.revision);
314 let as_user = || {
315 candidates
316 .iter()
317 .find_map(|pw| user(pw).map(|k| (k, PasswordKind::User)))
318 };
319 let as_owner = || {
320 candidates
321 .iter()
322 .find_map(|pw| owner(pw).map(|k| (k, PasswordKind::Owner)))
323 };
324 // ISO 32000-2 Algorithm 2.A checks the owner password first, so a password that is both is
325 // reported as the owner's; R2–R4 keep the user-first order of ISO 32000-1 §7.6.3.4.
326 let found = if owner_only {
327 as_owner()
328 } else if modern {
329 as_owner().or_else(as_user)
330 } else {
331 as_user().or_else(as_owner)
332 };
333 zeroize::Zeroize::zeroize(&mut candidates);
334 let (key, matched) = found?;
335 let perms_valid = (sec.revision >= 5)
336 .then_some(sec.perms)
337 .flatten()
338 .map(|perms| perms::perms_match(&key, perms, sec.permissions, sec.encrypt_metadata));
339 Some(Authenticated {
340 key: FileKey(key),
341 matched,
342 perms_valid,
343 })
344}
345
346/// Decrypted data and whether the input was well-formed for its cipher.
347///
348/// Added in 0.2.0.
349#[derive(Debug, Clone, PartialEq, Eq)]
350#[non_exhaustive]
351pub struct Decrypted {
352 /// The plaintext (or, for malformed AES input, the bytes as they were; see `well_formed`).
353 pub data: Vec<u8>,
354 /// False for AES data that was not `IV ‖ whole blocks` (kept as is) or had invalid PKCS#5
355 /// padding (decrypted, kept unstripped). The reader reports it as `aes-padding-invalid`.
356 pub well_formed: bool,
357}
358
359/// Decrypts the string or stream data of object `num gen` (ISO 32000-1 §7.6.2 Algorithm 1 for
360/// the per-object keys of RC4 and AES-128; AES-256 uses the file key itself).
361///
362/// Added in 0.2.0.
363#[must_use]
364pub fn decrypt(cipher: Cipher, key: &FileKey, num: u32, gen_nr: u16, data: &[u8]) -> Decrypted {
365 let plain = match cipher {
366 Cipher::Identity => aes::Plain {
367 data: data.to_vec(),
368 valid: true,
369 },
370 Cipher::Rc4 => aes::Plain {
371 data: rc4::apply(&key::object_key(&key.0, num, gen_nr, false), data),
372 valid: true,
373 },
374 Cipher::Aes128 => aes::decrypt(&key::object_key(&key.0, num, gen_nr, true), data),
375 Cipher::Aes256 => aes::decrypt(&key.0, data),
376 };
377 Decrypted {
378 data: plain.data,
379 well_formed: plain.valid,
380 }
381}
382
383#[cfg(test)]
384mod tests;