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