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