Skip to main content

pdfcer_model/crypto/
apply.rs

1//! Applying a file key to a loaded document — the never-encrypted list.
2//!
3//! [`crate::crypto::standard`] answers "what key?". This module answers
4//! "**to which bytes?**", and that question is where the correctness surface
5//! actually lives: ISO 32000-1's exception list is spread across four clauses,
6//! §7.6.1's own bullet list stops at three items, and every omission is a
7//! *silent* failure that presents as a corrupt document rather than as a
8//! decryption error.
9//!
10//! # Why decryption happens in the retained buffer
11//!
12//! [`Stream`](crate::object::Stream) does not own its bytes — it holds a
13//! [`ByteSpan`](crate::span::ByteSpan) into the buffer the document retains
14//! for its lifetime. That would normally make in-place decryption awkward, and
15//! for AES it will be: CBC output is 16 bytes of IV plus padding, so plaintext
16//! is *shorter* than ciphertext and cannot be written back over it.
17//!
18//! **RC4 is a stream cipher and preserves length exactly.** So the decrypted
19//! bytes fit precisely where the ciphertext was, and every span, offset,
20//! `/Length` and provenance record in the document stays true without a single
21//! change to the object model. That is not a lucky accident to lean on
22//! silently — it is the reason this increment could be built without touching
23//! `Stream`, and the reason the AES increment will have to.
24//!
25//! Strings are different: [`Object::String`] owns its bytes, so a string is
26//! decrypted in the *parsed object* and the buffer keeps the ciphertext. The
27//! two halves therefore disagree after load, which is exactly why
28//! [`Document::save_full`](crate::document::Document::save_full) and
29//! [`save_incremental`](crate::document::Document::save_incremental) **refuse**
30//! a decrypted document in this increment (see their docs). Writing encrypted
31//! documents is a separate piece of work; half-writing one is a corrupt file.
32//!
33//! # The never-encrypted list, and why it is not §7.6.1's bullet list
34//!
35//! §7.6.1 gives three bullets. The full set is **eight**, three of which live
36//! in other clauses entirely, and one of which (**E9**) exists only in ISO
37//! 32000-2. Applied here:
38//!
39//! | | Never decrypted | Where enforced |
40//! |---|---|---|
41//! | **E1** | trailer `/ID` strings | never reaches this module — the trailer is not an object |
42//! | **E2** | strings inside `/Encrypt` | [`skip`] — by object number, since `/Encrypt` may be indirect |
43//! | **E3** | the `/Encrypt` dictionary itself | same |
44//! | **E4** | strings inside an object stream | **by construction** — see below |
45//! | **E5** | cross-reference streams | [`skip`] — `/Type /XRef` |
46//! | **E6** | external stream data (`/F`) | [`skip`] — no bytes in this file to decrypt |
47//! | **E7** | non-string, non-stream types | by construction — the walk only touches strings and streams |
48//! | **E8** | `/Metadata` when `/EncryptMetadata false`, **or** `/Crypt`+`/Identity` | [`skip`] — both spellings |
49//!
50//! **E4 is the one that would destroy every modern file, and it is handled by
51//! ordering rather than by a check.** Strings inside an object stream are not
52//! separately encrypted: the container's *data* was encrypted once, and the
53//! objects inside it were serialized into that plaintext. So the walk runs
54//! **after phase 1 and before phase 2** of the document load — file-level
55//! objects are decrypted, which makes each object stream's data plaintext, and
56//! phase 2 then parses objects out of it that need no decryption at all. A
57//! design that decrypted after phase 2 would re-apply Algorithm 1 per contained
58//! object and corrupt every string in the document (**T4**).
59//!
60//! # What a wrong answer looks like
61//!
62//! None of these fail loudly. Decrypting a cross-reference stream produces
63//! garbage that fails to inflate, and the error surfaces as a broken xref two
64//! layers away from the cause. Missing `/EncryptMetadata false` produces a
65//! `/Metadata` stream of noise that only an XMP reader ever notices. That is
66//! why each skip below cites the clause that grants it rather than describing
67//! what it does.
68
69use crate::crypto::standard::FileKey;
70use crate::object::{Dict, IndirectObject, ObjId, Object};
71
72/// Why an object's bytes are left alone.
73///
74/// Returned rather than a bare `bool` so the reason can be asserted in tests
75/// and reported in diagnostics — "this stream was skipped" is not a useful
76/// fact without "because it is a cross-reference stream".
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum Skip {
79    /// **E3/E2** — this *is* the `/Encrypt` dictionary. §7.6.1: the encryption
80    /// dictionary "shall not" be encrypted, and neither are its strings; it has
81    /// to be readable before any key exists.
82    EncryptDict,
83    /// **E5** — a cross-reference stream. §7.5.8.2 exempts it because the
84    /// bootstrap order (xref → trailer → `/Encrypt` → authenticate → decrypt)
85    /// means nothing on the path to the key may itself require the key
86    /// (**T6**).
87    XrefStream,
88    /// **E6** — the data is in another file (`/F`), so there are no bytes here.
89    /// Note the asymmetry: an *embedded* file stream **is** encrypted.
90    ExternalStream,
91    /// **E8** — the document metadata stream, left in the clear by
92    /// `/EncryptMetadata false`. This changes the *key* as well (Algorithm 2
93    /// step (f), **T11**), so the two must agree or nothing decrypts.
94    ClearMetadata,
95    /// **E8, second spelling** — a `/Crypt` filter naming `/Identity`. Unlike
96    /// `/EncryptMetadata`, this does *not* change the file key (**T23**); both
97    /// mechanisms exist and a document may use either.
98    IdentityCryptFilter,
99}
100
101/// Should this object's bytes be left alone, and why?
102///
103/// `encrypt_dict_id` is the object number of an indirect `/Encrypt` dictionary,
104/// if the document has one. The `/Encrypt` dictionary is *usually* direct in
105/// the trailer, in which case it never appears as an object at all — but it may
106/// be indirect, and then its `/O` and `/U` strings would be decrypted with a
107/// key derived from themselves. That produces an authentication that succeeded
108/// followed by a document of noise.
109#[must_use]
110pub fn skip(
111    obj: &IndirectObject,
112    encrypt_dict_id: Option<u32>,
113    encrypt_metadata: bool,
114) -> Option<Skip> {
115    skip_value(obj.id.num, &obj.value, encrypt_dict_id, encrypt_metadata)
116}
117
118/// [`skip`] for a value not (yet) held as an [`IndirectObject`] — the write
119/// side asks it of a replacement value, so a write exempts exactly what a
120/// read would not decrypt.
121#[must_use]
122pub fn skip_value(
123    num: u32,
124    value: &Object,
125    encrypt_dict_id: Option<u32>,
126    encrypt_metadata: bool,
127) -> Option<Skip> {
128    if Some(num) == encrypt_dict_id {
129        return Some(Skip::EncryptDict);
130    }
131
132    let Object::Stream(stream) = value else {
133        // Non-stream objects can only carry strings, and the only string-level
134        // exemptions are the trailer `/ID` (not an object) and `/Encrypt`
135        // (handled above).
136        return None;
137    };
138    let dict = &stream.dict;
139
140    if matches!(dict.get(b"Type"), Some(Object::Name(n)) if n.as_bytes() == b"XRef") {
141        return Some(Skip::XrefStream);
142    }
143    if dict.contains_key(b"F") {
144        return Some(Skip::ExternalStream);
145    }
146    if !encrypt_metadata
147        && matches!(dict.get(b"Type"), Some(Object::Name(n)) if n.as_bytes() == b"Metadata")
148    {
149        return Some(Skip::ClearMetadata);
150    }
151    if has_identity_crypt_filter(dict) {
152        return Some(Skip::IdentityCryptFilter);
153    }
154    None
155}
156
157/// Does this stream's `/Filter` chain begin with a `/Crypt` filter naming
158/// `/Identity`?
159///
160/// §7.4.10 requires `/Crypt` to be **first** in the `/Filter` array (**W13**)
161/// and makes it a *routing annotation* rather than a decoder (**T22**) — it
162/// says which crypt filter applies, and the filter pipeline strips it. The
163/// only value pdfcer can act on without a handler-private algorithm is
164/// `/Identity`, which means "do not decrypt this stream".
165///
166/// `/Name` defaults to `/Identity` when absent (Table 14), so a bare `/Crypt`
167/// filter with no `/DecodeParms` is the identity case.
168fn has_identity_crypt_filter(dict: &Dict) -> bool {
169    let is_crypt = |o: &Object| matches!(o, Object::Name(n) if n.as_bytes() == b"Crypt");
170
171    let first_is_crypt = match dict.get(b"Filter") {
172        Some(o @ Object::Name(_)) => is_crypt(o),
173        Some(Object::Array(items)) => items.first().is_some_and(is_crypt),
174        _ => false,
175    };
176    if !first_is_crypt {
177        return false;
178    }
179
180    // The parameter dictionary sits at the matching position in
181    // /DecodeParms — index 0, since /Crypt shall be first.
182    let parms = match dict.get(b"DecodeParms") {
183        Some(Object::Dict(d)) => Some(d),
184        Some(Object::Array(items)) => match items.first() {
185            Some(Object::Dict(d)) => Some(d),
186            _ => None,
187        },
188        _ => None,
189    };
190    match parms.and_then(|d| d.get(b"Name")) {
191        Some(Object::Name(n)) => n.as_bytes() == b"Identity",
192        // Table 14: /Name defaults to /Identity.
193        _ => true,
194    }
195}
196
197/// Whether `dict` is a signature dictionary (§12.8.1) — `/Type /Sig` or
198/// `/DocTimeStamp`, or carrying a `/ByteRange` — whose `/Contents` string is
199/// never encrypted (ISO 32000-2 §7.6.2's fourth exception; ETSI EN 319 142-1
200/// §5.5 states it for the ISO 32000-1 baseline). The digest covers the file
201/// as stored, so encrypting the signature value would make it unverifiable.
202#[must_use]
203pub fn is_signature_dict(dict: &Dict) -> bool {
204    dict.get(b"ByteRange").is_some()
205        || matches!(dict.get(b"Type"), Some(Object::Name(n))
206            if n.as_bytes() == b"Sig" || n.as_bytes() == b"DocTimeStamp")
207}
208
209/// Decrypt every string in `value`, keyed on the containing object `id`.
210///
211/// **T3** — a string is keyed on the *containing indirect object's* identity
212/// at **any nesting depth**. A string four dictionaries deep inside object
213/// `12 0` uses object `12 0`'s key, not anything nearer. The recursion
214/// therefore threads one `id` all the way down and never recomputes it.
215///
216/// References are not followed: an [`Object::Reference`] is a pointer, and the
217/// object it names is decrypted on its own turn with its own key.
218pub fn decrypt_strings(value: &mut Object, id: ObjId, key: &FileKey) {
219    match value {
220        Object::String(bytes) => {
221            *bytes = key.decrypt_string(id, bytes);
222        }
223        Object::Array(items) => {
224            for item in items {
225                decrypt_strings(item, id, key);
226            }
227        }
228        Object::Dict(dict) => {
229            let signature = is_signature_dict(dict);
230            for (k, v) in &mut dict.0 {
231                if !(signature && k.as_bytes() == b"Contents") {
232                    decrypt_strings(v, id, key);
233                }
234            }
235        }
236        Object::Stream(stream) => {
237            // A stream's *dictionary* carries ordinary encrypted strings —
238            // §7.6.5's own EXAMPLE confirms it for `/Info`-style entries. The
239            // stream *data* is handled separately, in the buffer.
240            for (_, v) in &mut stream.dict.0 {
241                decrypt_strings(v, id, key);
242            }
243        }
244        // E7: every other type is unencrypted by nature.
245        Object::Null
246        | Object::Boolean(_)
247        | Object::Integer(_)
248        | Object::Real(_)
249        | Object::Name(_)
250        | Object::Reference(_) => {}
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use crate::object::{Name, Provenance, Stream};
258    use crate::span::ByteSpan;
259
260    fn name(s: &str) -> Object {
261        Object::Name(Name(s.as_bytes().to_vec()))
262    }
263
264    fn stream_obj(num: u32, entries: Vec<(&str, Object)>) -> IndirectObject {
265        let mut d = Dict::new();
266        for (k, v) in entries {
267            d.insert(Name(k.as_bytes().to_vec()), v);
268        }
269        IndirectObject {
270            id: ObjId::new(num, 0),
271            value: Object::Stream(Stream {
272                dict: d,
273                data_span: ByteSpan::new(0, 0),
274            }),
275            provenance: Provenance::File(ByteSpan::new(0, 0)),
276        }
277    }
278
279    /// E5 — a cross-reference stream is never encrypted. Decrypting one
280    /// produces bytes that fail to inflate, and the error surfaces as a
281    /// broken cross-reference table rather than as an encryption problem.
282    #[test]
283    fn xref_streams_are_skipped() {
284        let o = stream_obj(4, vec![("Type", name("XRef"))]);
285        assert_eq!(skip(&o, None, true), Some(Skip::XrefStream));
286    }
287
288    /// E6 — `/F` means the data lives in another file. There is nothing here
289    /// to decrypt. The asymmetry is worth stating: an *embedded* file stream
290    /// (`/EF`) has its data in this file and **is** encrypted.
291    #[test]
292    fn external_streams_are_skipped() {
293        let o = stream_obj(5, vec![("F", Object::String(b"other.dat".to_vec()))]);
294        assert_eq!(skip(&o, None, true), Some(Skip::ExternalStream));
295    }
296
297    /// E8 — `/Metadata` is skipped only when `/EncryptMetadata` is false.
298    /// With the default `true` it is an ordinary encrypted stream, and
299    /// skipping it would leave XMP as ciphertext.
300    #[test]
301    fn metadata_is_skipped_only_when_declared_clear() {
302        let o = stream_obj(6, vec![("Type", name("Metadata"))]);
303        assert_eq!(skip(&o, None, false), Some(Skip::ClearMetadata));
304        assert_eq!(skip(&o, None, true), None);
305    }
306
307    /// E2/E3 — an indirect `/Encrypt` dictionary is matched by object number.
308    /// Its `/O` and `/U` are the inputs to the key derivation; decrypting them
309    /// with a key derived from themselves gives a successful authentication
310    /// followed by a document of noise.
311    #[test]
312    fn indirect_encrypt_dict_is_skipped_by_number() {
313        let mut d = Dict::new();
314        d.insert(Name(b"O".to_vec()), Object::String(vec![0; 32]));
315        let o = IndirectObject {
316            id: ObjId::new(9, 0),
317            value: Object::Dict(d),
318            provenance: Provenance::File(ByteSpan::new(0, 0)),
319        };
320        assert_eq!(skip(&o, Some(9), true), Some(Skip::EncryptDict));
321        // A different object number is not exempt.
322        assert_eq!(skip(&o, Some(10), true), None);
323    }
324
325    /// T23 — `/Crypt` + `/Identity` is the *other* way to leave a stream in
326    /// the clear, and it does not change the file key the way
327    /// `/EncryptMetadata false` does. Both spellings exist; implementing only
328    /// one leaves a class of files broken.
329    #[test]
330    fn identity_crypt_filter_is_skipped() {
331        // Bare /Crypt with no parameters: /Name defaults to /Identity.
332        let bare = stream_obj(7, vec![("Filter", name("Crypt"))]);
333        assert_eq!(skip(&bare, None, true), Some(Skip::IdentityCryptFilter));
334
335        // Explicit /Name /Identity in an array-form filter chain.
336        let mut parms = Dict::new();
337        parms.insert(Name(b"Name".to_vec()), name("Identity"));
338        let explicit = stream_obj(
339            8,
340            vec![
341                (
342                    "Filter",
343                    Object::Array(vec![name("Crypt"), name("FlateDecode")]),
344                ),
345                (
346                    "DecodeParms",
347                    Object::Array(vec![Object::Dict(parms), Object::Null]),
348                ),
349            ],
350        );
351        assert_eq!(skip(&explicit, None, true), Some(Skip::IdentityCryptFilter));
352    }
353
354    /// A `/Crypt` filter naming a *real* crypt filter is not the identity
355    /// case and must still be decrypted — treating every `/Crypt` as
356    /// "skip" would leave real content as ciphertext.
357    #[test]
358    fn named_crypt_filter_is_not_identity() {
359        let mut parms = Dict::new();
360        parms.insert(Name(b"Name".to_vec()), name("StdCF"));
361        let o = stream_obj(
362            11,
363            vec![
364                ("Filter", Object::Array(vec![name("Crypt")])),
365                ("DecodeParms", Object::Array(vec![Object::Dict(parms)])),
366            ],
367        );
368        assert_eq!(skip(&o, None, true), None);
369    }
370
371    /// W13 — `/Crypt` "shall be first". A `/Crypt` appearing later in the
372    /// chain is malformed, and reading it as an identity exemption would let
373    /// a malformed file suppress decryption of real content.
374    #[test]
375    fn crypt_filter_not_first_is_ignored() {
376        let o = stream_obj(
377            12,
378            vec![(
379                "Filter",
380                Object::Array(vec![name("FlateDecode"), name("Crypt")]),
381            )],
382        );
383        assert_eq!(skip(&o, None, true), None);
384    }
385
386    /// An ordinary content stream is decrypted — the negative case, without
387    /// which every assertion above would also pass on a function that
388    /// returned `Some` unconditionally.
389    #[test]
390    fn ordinary_streams_are_not_skipped() {
391        let o = stream_obj(13, vec![("Length", Object::Integer(42))]);
392        assert_eq!(skip(&o, None, true), None);
393    }
394}