Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / pdf / src / main / rust / src / decrypt_part1.rs

decrypt_part1.rs317 lines · 14.1 KiBRaw
1/// Expand every `/Type /ObjStm` into its contained objects.
2///
3/// lopdf skips object-stream expansion at load time when the trailer has `/Encrypt`
4/// (reader.rs: `if stream.dict.has_type(b"ObjStm") && !is_encrypted`) because the bytes
5/// are still ciphertext, and it only auto-decrypts for the EMPTY password. So a document
6/// with a real password reached this point with every ObjStm-contained object missing —
7/// including `/Root`, `/Pages` and the page dictionaries, which is where §7.5.7 puts them
8/// for essentially every modern encrypted PDF. The result was a correct password opening
9/// a document with zero pages.
10fn expand_object_streams(doc: &mut Document) {
11 let mut recovered: Vec<(ObjectId, Object)> = Vec::new();
12 for (_, object) in doc.objects.iter() {
13 let Ok(stream) = object.as_stream() else {
14 continue;
15 };
16 if !stream.dict.has_type(b"ObjStm") {
17 continue;
18 }
19 let mut stream = stream.clone();
20 if let Ok(obj_stream) = lopdf::ObjectStream::new(&mut stream) {
21 recovered.extend(obj_stream.objects);
22 }
23 }
24 // Only add, never replace: a top-level definition supersedes one inside an ObjStm.
25 for (id, obj) in recovered {
26 doc.objects.entry(id).or_insert(obj);
27 }
28}
29
30/// Which standard-security-handler algorithm to write on save.
31#[derive(Clone, Copy, PartialEq)]
32pub(crate) enum EncryptAlgo {
33 /// RC4-128, revision 3 (V2/R3).
34 Rc4_128,
35 /// AES-128, revision 4 (V4/R4, AESV2).
36 Aes128,
37 /// AES-256, revision 6 (V5/R6, AESV3).
38 Aes256,
39}
40
41/// Cryptographically-secure random bytes for salts/IVs, sourced from the OS
42/// CSPRNG. Falls back to md5-based mixing (seed + wall clock) only if the OS
43/// RNG is unavailable, preserving the no-panic invariant.
44fn rand_bytes<const N: usize>(seed: &[u8]) -> [u8; N] {
45 use rand_core::TryRng;
46 let mut out = [0u8; N];
47 if rand::rngs::SysRng.try_fill_bytes(&mut out).is_ok() {
48 return out;
49 }
50 use md5::{Digest, Md5};
51 let t = std::time::SystemTime::now()
52 .duration_since(std::time::UNIX_EPOCH)
53 .map(|d| d.as_nanos())
54 .unwrap_or(0);
55 let mut ctr: u64 = 0;
56 let mut filled = 0;
57 while filled < N {
58 let mut m = Md5::new();
59 m.update(seed);
60 m.update(t.to_le_bytes());
61 m.update(ctr.to_le_bytes());
62 let d: [u8; 16] = m.finalize().into();
63 let take = d.len().min(N - filled);
64 out[filled..filled + take].copy_from_slice(&d[..take]);
65 filled += take;
66 ctr += 1;
67 }
68 out
69}
70
71/// Serialize `handle` encrypted with the given passwords, defaulting to AES-128
72/// (V4/R4) — modern and widely supported.
73pub(crate) fn save_encrypted(handle: i64, user_pw: &[u8], owner_pw: &[u8]) -> Option<Vec<u8>> {
74 let bytes = save_document(handle)?;
75 encrypt_doc_bytes(&bytes, user_pw, owner_pw, EncryptAlgo::Aes128)
76}
77
78/// Encrypt a serialized PDF (`bytes`) with `algo` and the given passwords,
79/// returning the re-serialized encrypted document. Testable without the registry.
80pub(crate) fn encrypt_doc_bytes(
81 bytes: &[u8],
82 user_pw: &[u8],
83 owner_pw: &[u8],
84 algo: EncryptAlgo,
85) -> Option<Vec<u8>> {
86 let mut doc = Document::load_mem(bytes).ok()?;
87 // Ensure an /ID exists (used by RC4/AES-128 key derivation).
88 let id0 = ensure_trailer_id(&mut doc, bytes);
89 let owner = if owner_pw.is_empty() { user_pw } else { owner_pw };
90 let p: i32 = -4; // allow all operations
91
92 // Build the /Encrypt dict and per-object cipher factory.
93 let (enc, make_apply): (Dictionary, CryptFnFactory) =
94 match algo {
95 EncryptAlgo::Rc4_128 => {
96 let (n, rev) = (16usize, 3u8);
97 let o = crypto::compute_o(owner, user_pw, n, rev);
98 let key = crypto::compute_key(user_pw, &o, p, &id0, n, rev, true);
99 let u = crypto::compute_u(&key, &id0, rev);
100 let mut enc = Dictionary::new();
101 enc.set("Filter", name_obj("Standard"));
102 enc.set("V", Object::Integer(2));
103 enc.set("R", Object::Integer(3));
104 enc.set("Length", Object::Integer(128));
105 enc.set("P", Object::Integer(p as i64));
106 enc.set("O", Object::String(o, lopdf::StringFormat::Literal));
107 enc.set("U", Object::String(u, lopdf::StringFormat::Literal));
108 let key2 = key.clone();
109 let make = move |id: ObjectId| -> CryptFn {
110 let okey = crypto::object_key(&key2, id.0, id.1, n);
111 Box::new(move |d: &[u8]| crypto::rc4(&okey, d))
112 };
113 (enc, Box::new(make))
114 }
115 EncryptAlgo::Aes128 => {
116 let (n, rev) = (16usize, 4u8);
117 let o = crypto::compute_o(owner, user_pw, n, rev);
118 let key = crypto::compute_key(user_pw, &o, p, &id0, n, rev, true);
119 let u = crypto::compute_u(&key, &id0, rev);
120 let mut cf = Dictionary::new();
121 let mut stdcf = Dictionary::new();
122 stdcf.set("CFM", name_obj("AESV2"));
123 stdcf.set("Length", Object::Integer(16));
124 cf.set("StdCF", Object::Dictionary(stdcf));
125 let mut enc = Dictionary::new();
126 enc.set("Filter", name_obj("Standard"));
127 enc.set("V", Object::Integer(4));
128 enc.set("R", Object::Integer(4));
129 enc.set("Length", Object::Integer(128));
130 enc.set("P", Object::Integer(p as i64));
131 enc.set("CF", Object::Dictionary(cf));
132 enc.set("StmF", name_obj("StdCF"));
133 enc.set("StrF", name_obj("StdCF"));
134 enc.set("O", Object::String(o, lopdf::StringFormat::Literal));
135 enc.set("U", Object::String(u, lopdf::StringFormat::Literal));
136 let key2 = key.clone();
137 let seed = id0.clone();
138 let make = move |id: ObjectId| -> CryptFn {
139 let okey = crypto::object_key_aes(&key2, id.0, id.1, n);
140 let seed = seed.clone();
141 Box::new(move |d: &[u8]| {
142 let iv = rand_bytes::<16>(&[&seed[..], d.get(..8).unwrap_or(d)].concat());
143 crypto::aes_cbc_encrypt(&okey, &iv, d).unwrap_or_default()
144 })
145 };
146 (enc, Box::new(make))
147 }
148 EncryptAlgo::Aes256 => {
149 let rev = 6u8;
150 let file_key = rand_bytes::<32>(&id0);
151 let salt_bytes = rand_bytes::<32>(&[&id0[..], b"salts"].concat());
152 // Split the random salt bytes into four 8-byte salts (derived from
153 // salt_bytes, so no hard-coded array flows into the KDF).
154 let salts: [[u8; 8]; 4] = std::array::from_fn(|i| {
155 let mut s = [0u8; 8];
156 s.copy_from_slice(&salt_bytes[i * 8..i * 8 + 8]);
157 s
158 });
159 let (u, ue, o, oe) = crypto::compute_v5(user_pw, owner, &file_key, &salts, rev)?;
160 let perms = crypto::compute_perms_v5(&file_key, p)?;
161 let mut cf = Dictionary::new();
162 let mut stdcf = Dictionary::new();
163 stdcf.set("CFM", name_obj("AESV3"));
164 stdcf.set("Length", Object::Integer(32));
165 cf.set("StdCF", Object::Dictionary(stdcf));
166 let mut enc = Dictionary::new();
167 enc.set("Filter", name_obj("Standard"));
168 enc.set("V", Object::Integer(5));
169 enc.set("R", Object::Integer(6));
170 enc.set("Length", Object::Integer(256));
171 enc.set("P", Object::Integer(p as i64));
172 enc.set("CF", Object::Dictionary(cf));
173 enc.set("StmF", name_obj("StdCF"));
174 enc.set("StrF", name_obj("StdCF"));
175 enc.set("O", Object::String(o, lopdf::StringFormat::Literal));
176 enc.set("U", Object::String(u, lopdf::StringFormat::Literal));
177 enc.set("OE", Object::String(oe, lopdf::StringFormat::Literal));
178 enc.set("UE", Object::String(ue, lopdf::StringFormat::Literal));
179 enc.set("Perms", Object::String(perms, lopdf::StringFormat::Literal));
180 let fk = file_key;
181 let seed = id0.clone();
182 let make = move |_id: ObjectId| -> CryptFn {
183 // AESV3 uses the file key directly (no per-object key).
184 let seed = seed.clone();
185 Box::new(move |d: &[u8]| {
186 let iv = rand_bytes::<16>(&[&seed[..], d.get(..8).unwrap_or(d)].concat());
187 crypto::aes_cbc_encrypt(&fk, &iv, d).unwrap_or_default()
188 })
189 };
190 (enc, Box::new(make))
191 }
192 };
193
194 let enc_id = doc.add_object(enc);
195 let ids: Vec<ObjectId> = doc.objects.keys().copied().collect();
196 for id in ids {
197 if id == enc_id {
198 continue;
199 }
200 let apply = make_apply(id);
201 if let Some(obj) = doc.objects.get_mut(&id) {
202 crypt_object(obj, &apply);
203 }
204 }
205 doc.trailer.set("Encrypt", Object::Reference(enc_id));
206
207 let mut out = Vec::new();
208 doc.save_to(&mut out).ok()?;
209 Some(out)
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 /// §7.6.3.3 Algorithm 2 step (d): /P is hashed as 32 bits, so the signed and
217 /// unsigned spellings of the same flags must derive the same file key.
218 #[test]
219 fn permissions_p_reads_both_spellings_of_the_same_flags() {
220 let signed = dictionary! { "P" => Object::Integer(-3904) };
221 let unsigned = dictionary! { "P" => Object::Integer(4_294_963_392) };
222 assert_eq!(permissions_p(&signed), -3904);
223 assert_eq!(
224 permissions_p(&unsigned),
225 -3904,
226 "the unsigned spelling is the same 32 bits, not i32::MAX"
227 );
228 // The four bytes Algorithm 2 actually hashes.
229 assert_eq!(
230 (permissions_p(&unsigned) as u32).to_le_bytes(),
231 (permissions_p(&signed) as u32).to_le_bytes()
232 );
233 // A missing /P still reads as zero rather than panicking.
234 assert_eq!(permissions_p(&Dictionary::new()), 0);
235 }
236
237 /// §7.6.5 Table 20: /Identity is the reserved crypt-filter name for data that is
238 /// NOT encrypted, and Table 25 gives /CFM /None the same meaning. Decrypting
239 /// either turns plaintext into noise for the whole document.
240 #[test]
241 fn identity_crypt_filters_select_no_cipher() {
242 let mut cf = Dictionary::new();
243 cf.set("StdCF", dictionary! { "CFM" => name_obj("AESV2") });
244 cf.set("NoneCF", dictionary! { "CFM" => name_obj("None") });
245 cf.set("Rc4CF", dictionary! { "CFM" => name_obj("V2") });
246 let cf = Some(&cf);
247
248 assert!(crypt_filter_method(cf, b"Identity", CryptMethod::AesV2).is_none());
249 assert!(crypt_filter_method(cf, b"NoneCF", CryptMethod::AesV2).is_none());
250 assert!(matches!(
251 crypt_filter_method(cf, b"StdCF", CryptMethod::Rc4),
252 Some(CryptMethod::AesV2)
253 ));
254 // A crypt filter may differ from the default: /StmF and /StrF are independent.
255 assert!(matches!(
256 crypt_filter_method(cf, b"Rc4CF", CryptMethod::AesV2),
257 Some(CryptMethod::Rc4)
258 ));
259 // An unresolvable name keeps the previous behaviour: fall back to the default,
260 // so no file that never mentions /Identity changes path.
261 assert!(matches!(
262 crypt_filter_method(cf, b"MissingCF", CryptMethod::AesV3),
263 Some(CryptMethod::AesV3)
264 ));
265 assert!(matches!(
266 crypt_filter_method(None, b"StdCF", CryptMethod::Rc4),
267 Some(CryptMethod::Rc4)
268 ));
269 }
270
271 /// §7.6.5: streams and strings have SEPARATE crypt filters, so one of them being
272 /// /Identity must not stop the other being decrypted - and must not decrypt it.
273 #[test]
274 fn a_stream_identity_filter_leaves_the_body_but_not_the_strings() {
275 let flip = |d: &[u8]| d.iter().map(|b| b ^ 0xFF).collect::<Vec<u8>>();
276 let mut obj = Object::Stream(Stream::new(
277 dictionary! { "Author" => Object::String(b"abc".to_vec(), lopdf::StringFormat::Literal) },
278 b"body".to_vec(),
279 ));
280 crypt_object_split(&mut obj, Some(&flip), None);
281 let Object::Stream(s) = &obj else { panic!("expected a stream") };
282 assert_eq!(s.content, b"body", "an /Identity /StmF must not touch the body");
283 let Ok(Object::String(a, _)) = s.dict.get(b"Author") else {
284 panic!("expected a string")
285 };
286 assert_eq!(a, &flip(b"abc"), "/StrF still applies to the dictionary strings");
287
288 // And the mirror case: /StrF /Identity with a real /StmF.
289 let mut obj = Object::Stream(Stream::new(
290 dictionary! { "Author" => Object::String(b"abc".to_vec(), lopdf::StringFormat::Literal) },
291 b"body".to_vec(),
292 ));
293 crypt_object_split(&mut obj, None, Some(&flip));
294 let Object::Stream(s) = &obj else { panic!("expected a stream") };
295 assert_eq!(s.content, flip(b"body"));
296 let Ok(Object::String(a, _)) = s.dict.get(b"Author") else {
297 panic!("expected a string")
298 };
299 assert_eq!(a, b"abc", "an /Identity /StrF must not touch the strings");
300 }
301
302 /// `crypt_object` (the encrypt-on-save path) must keep applying one transform to
303 /// both, unchanged by the split above.
304 #[test]
305 fn crypt_object_still_applies_to_strings_and_streams_alike() {
306 let flip = |d: &[u8]| d.iter().map(|b| b ^ 0xFF).collect::<Vec<u8>>();
307 let mut obj = Object::Array(vec![
308 Object::String(b"s".to_vec(), lopdf::StringFormat::Literal),
309 Object::Stream(Stream::new(Dictionary::new(), b"c".to_vec())),
310 ]);
311 crypt_object(&mut obj, &flip);
312 let Object::Array(a) = &obj else { panic!() };
313 assert_eq!(a[0], Object::String(flip(b"s"), lopdf::StringFormat::Literal));
314 let Object::Stream(s) = &a[1] else { panic!() };
315 assert_eq!(s.content, flip(b"c"));
316 }
317}