From febd6dc2b65d683d1599f15f6bcecdd6c2107808 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:36:32 -0500 Subject: [PATCH] fix(sign): an unlisted body or an entry that leads nowhere is no permitted change (#6754) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this changes Fixes #6754. A revision appended after signing could change what a signed page shows while `classify_changes` reported only permitted changes. The update carried a new body for the page's content stream that no cross-reference section lists, plus an entry, named from the trailer, that points at no object. cos kept reading the signed content object (its entry had not changed), and read the new number as null, which `classify` drops. The renderer instead rebuilds its object index from the file's `N G obj` headers when an entry leads to no object (`vendor/hayro-syntax/src/xref.rs`, `repair` / `fallback_xref_map_inner`), and there the last header for a number wins, so the page drew the unlisted body. `crates/sign/src/pdf/changes.rs` now refuses both halves, each on its own: - **An entry that does not locate its own object.** Every object whose place changed since signing must have an entry that `xref_entry_is_exact` accepts, whatever the object reads as. Before, this was checked only when the content equalled the signed object's. Reported as `other changes`. - **A body the reader does not read.** `unlisted_bodies` scans the bytes after the signed revision for `N G obj` headers. For each number and generation, the last header there must be where the current entry for that number points. Otherwise the renderer's rebuilt index may draw it. Reported as `page content` when the number had a signed page role, else `other changes`. This holds whatever triggers the rebuild, including a damaged entry the signed file already had. The scan is linear and bounded: past 2^20 distinct headers the appended bytes are not judged and the change is refused. The scan finds more headers than the renderer's (it does not skip dictionaries or check that an object follows), so it errs towards refusing. A writer that lists what it writes is unaffected. ## How you verified it - `cargo fmt --check -p pdfcraft-sign` - `cargo clippy -p pdfcraft-sign --all-targets -- -D warnings` - `cargo test -p pdfcraft-sign --test it`: 144 passed, 2 ignored. - `cargo test -p pdfcraft-sign --lib`: 116 passed, 1 ignored. `shared_annotation_arrays_are_judged_in_bounded_time` (30,000 rewritten pages, 20 s budget) took 11.6 s and 14.4 s with the fix and 13.2 s with `changes.rs` at `main`, on the same machine under similar load: the scan and the extra entry check cost nothing measurable there. New test `an_unlisted_object_body_or_an_entry_that_points_at_no_object_is_not_permitted` in `crates/sign/tests/it/pdf.rs`, for a P=1 certification and an approval signature: - the issue's shape (unlisted content body, plus an entry for `/Info 60 0 R` that points at the section's own `xref` keyword) is Invalid, `page content`; - the entry alone is Invalid, `other changes`; - the unlisted body beside an honestly listed object is Invalid, `page content`; - an honest revision that lists what it adds stays Valid. **Seen failing before the fix:** with `changes.rs` at `main`, the test fails on its first case with `Allowed([])` and status Valid. ## Never-crash - [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests - [x] No indexing or slicing with input-derived positions (`get` throughout); offsets use checked or saturating arithmetic; the header map is capped - [x] No `unsafe` - [x] Not a crash fix ## Provenance - [x] No assets, fonts or copied code - [x] Behaviour from ISO 32000-2 §7.5 and §12.8.2.2, and from observing the vendored renderer's repair path ## Anything a reviewer should look at first - **What is still not modelled.** The renderer's repair scan also files the members of any `/Type /ObjStm` stream it meets (last one wins, unless a plain header exists for the number), attributes a headerless object-stream dictionary to the last header it saw, and keeps the last trailer-like dictionary whose `/Root` has `/Pages`. An appended object stream holding a forged member for an object the signed file kept only in an object stream, or a trailing `<< /Root … >>`, could still diverge once something else makes the renderer rebuild. This PR closes the issue's trigger (an entry that leads nowhere) and the unlisted plain body. The general fix, as the issue says, is to judge changes with the renderer's own object resolution. I have not covered those here, to keep this to the issue; they need their own issue. - **Kind for a misplaced entry.** It stays `other changes`, as the existing `a_cross_reference_entry_that_misses_its_object_is_not_an_unchanged_object` expects, even for a signed page's content object: what the renderer draws there is unknown, not known to be new content. --- crates/sign/src/pdf/changes.rs | 247 ++++++++++++++++++++++++++++++++- crates/sign/tests/it/pdf.rs | 166 ++++++++++++++++++++++ 2 files changed, 407 insertions(+), 6 deletions(-) diff --git a/crates/sign/src/pdf/changes.rs b/crates/sign/src/pdf/changes.rs index ce7349e2ad..01e6b90889 100644 --- a/crates/sign/src/pdf/changes.rs +++ b/crates/sign/src/pdf/changes.rs @@ -116,6 +116,7 @@ pub(super) fn classify_changes(doc: &Document, old: Option, p: Option< disallowed.push(what); } } + refuse_unlisted_bodies(doc, &old, &signed_role, &mut disallowed); // The trailer chooses the catalog. A later revision that points it at another catalog (one // already in the signed file, so no object changes) shows another document. if doc.root() != old.root() { @@ -165,16 +166,23 @@ pub(super) fn classify_changes(doc: &Document, old: Option, p: Option< } continue; } + // A new place for the object. What is read there is what the renderer reads only when + // the entry locates the object itself: where this reader had to search for it, another + // reader may arrive at a different body, and an entry that leads to no object at all + // (which this reader reads as null, and so as nothing) makes the renderer rebuild its + // object index from the file's headers (#6754). Whatever the object reads as here, no + // writer has a reason to write such an entry after signing. + if !doc.is_edited(num) && !doc.xref_entry_is_exact(num) { + if !disallowed.contains(&kind::OTHER) { + disallowed.push(kind::OTHER); + } + continue; + } let r = ObjRef { num, generation: doc.generation(num) }; let new = doc.get(r); let before = old.try_get(num).ok().filter(|o| !matches!(**o, Object::Null)); if before.as_deref().is_some_and(|b| same_object(b, &new)) { - // The same content at a new place. That is true for the renderer as well only when - // the entry locates the object itself: where this reader had to search for the - // object, another reader may arrive at a different one. - if !doc.is_edited(num) && !doc.xref_entry_is_exact(num) && !disallowed.contains(&kind::OTHER) { - disallowed.push(kind::OTHER); - } + // The same content at a new place. continue; } // A resource of a signed page is page content whatever keys its new version carries @@ -632,6 +640,168 @@ fn references(doc: &Document) -> Option> { doc.trailer().iter().all(|(_, v)| walk(v, 0, &mut found)).then_some(found) } +/// When an entry it follows leads to no object, the renderer rebuilds its object index from the +/// `N G obj` headers in the file, and there the last header for a number wins. A body appended +/// after signing that is not where this reader reads its number can then be drawn in place of +/// the object compared: a new body for a signed page's content that no section lists, or a +/// revision written back to an earlier body (#6754). No writer leaves one, so each is refused, +/// as page content when the number had a signed role (`signed_role`). +fn refuse_unlisted_bodies(doc: &Document, old: &Document, signed_role: &dyn Fn(u32) -> bool, disallowed: &mut Vec<&'static str>) { + let refused: Vec<&'static str> = match unlisted_bodies(doc, old) { + Some(nums) => nums.into_iter().map(|num| if signed_role(num) { kind::PAGE_CONTENT } else { kind::OTHER }).collect(), + None => vec![kind::OTHER], + }; + for what in refused { + if !disallowed.contains(&what) { + disallowed.push(what); + } + } +} + +/// The object numbers with a body in the bytes appended after the signed revision `old` that +/// `doc` does not read for them: for each number and generation, the last `N G obj` header there +/// must be where `doc`'s cross-reference entry for that number points, with that generation. A +/// renderer that rebuilds its object index from the file's headers takes the last one, so any +/// other body is one it may draw while this reader compares another. `None` past a bound on the +/// headers found, or on the work spent finding them, when the appended bytes cannot be judged. +/// +/// The scan finds more headers than a renderer's would (it does not skip dictionaries or check +/// that an object follows), so it errs towards refusing. +fn unlisted_bodies(doc: &Document, old: &Document) -> Option> { + const MAX_HEADERS: usize = 1 << 20; + let data = doc.bytes(); + let start = old.bytes().len(); + let Some(appended) = data.get(start..) else { return Some(Vec::new()) }; + // Each candidate header may read a comment, a generation token or white space to its end, and + // later ones can start inside or before it (`%1%1%1…`, `1 +1+1+1…`, `1+1+1…` before long + // white space): without a bound, that is quadratic in the appended bytes. Ordinary bytes, + // binary stream data included, spend a small fraction of it. + let mut work = appended.len().saturating_mul(16).saturating_add(1 << 20); + let mut last: HashMap<(u32, u16), usize> = HashMap::new(); + let mut i = 0; + while let Some(b) = appended.get(i) { + if work == 0 { + return None; + } + let starts_number = b.is_ascii_digit() && i.checked_sub(1).and_then(|p| appended.get(p)).is_none_or(|p| !p.is_ascii_digit()); + if let Some((num, generation, end)) = starts_number.then(|| object_header(appended, i, &mut work)).flatten() { + last.insert((num, generation), start.saturating_add(i)); + if last.len() > MAX_HEADERS { + return None; + } + i = end; + } else { + i += 1; + } + } + // Where an entry's offset leads, past any white space before the header, that white space + // spent from `work`: many entries can point before one long run of it. Offsets may count from + // a `%PDF-` header that does not start the file. + let header_at = |offset: u64, work: &mut usize| -> Vec { + let Ok(offset) = usize::try_from(offset) else { return Vec::new() }; + let shifted = (doc.header_offset() != 0).then(|| offset.checked_add(doc.header_offset())).flatten(); + let mut found = Vec::new(); + for at in [Some(offset), shifted].into_iter().flatten() { + let Some(rest) = data.get(at..).filter(|_| *work > 0) else { continue }; + let blank = rest.iter().take_while(|b| is_white_space(**b)).count(); + *work = work.saturating_sub(blank); + found.push(at.saturating_add(blank)); + } + found + }; + // A revision's own cross-reference stream with no row for itself, as many writers leave it + // (ISO 32000-2 §7.5.8.3 asks for one; readers do without): the section this reader followed + // from `startxref` or `/Prev`, so the object there is that stream. Exempt only at exactly + // where such a section starts, and only under a number that names nothing else: the signed + // revision has no entry for it, this one lists none, and nothing refers to it. A stream + // numbered as a signed object, or one a page lists as an annotation, is judged as any body. + let sections = xref_stream_sections(doc); + let referenced = OnceCell::new(); + let own_section = |num: u32, at: usize| { + sections.contains(&at) + && old.xref_entry(num).is_none() + && referenced.get_or_init(|| references(doc)).as_ref().is_some_and(|found: &HashSet| !found.iter().any(|r| r.num == num)) + }; + let mut unlisted: Vec = last + .into_iter() + .filter(|((num, generation), at)| match doc.xref_entry(*num) { + Some(pdfcraft_cos::XrefEntry::InFile { offset, generation: g }) => g != *generation || !header_at(offset, &mut work).contains(at), + None => !own_section(*num, *at), + _ => true, + }) + .map(|((num, _), _)| num) + .collect(); + if work == 0 { + return None; + } + unlisted.sort_unstable(); + unlisted.dedup(); + Some(unlisted) +} + +/// Where each of `doc`'s cross-reference stream sections starts in the file: the header of the +/// stream object the reader followed from `startxref` or a `/Prev`, past any white space before it. +fn xref_stream_sections(doc: &Document) -> Vec { + let data = doc.bytes(); + doc.revisions() + .iter() + .filter(|r| r.is_stream) + .filter_map(|r| { + let offset = usize::try_from(r.xref_offset).ok()?; + // An offset may count from a `%PDF-` header that does not start the file. + let offset = if r.header_relative { offset.checked_add(doc.header_offset())? } else { offset }; + data.get(offset..).map(|rest| offset.saturating_add(rest.iter().take_while(|b| is_white_space(**b)).count())) + }) + .collect() +} + +/// PDF white space (ISO 32000-2 §7.2.3, Table 1). +fn is_white_space(b: u8) -> bool { + matches!(b, b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' ') +} + +/// An `N G obj` header starting at `at` in `bytes`: its number, its generation (0 when it is no +/// generation number, as a renderer rebuilding its index reads it) and where it ends. White space +/// and comments may separate the parts, and the generation may be any number. The white space, +/// comment and generation bytes read are spent from `work`. +fn object_header(bytes: &[u8], at: usize, work: &mut usize) -> Option<(u32, u16, usize)> { + let number_end = at.checked_add(count_while(bytes, at, |c| c.is_ascii_digit()))?; + let num = std::str::from_utf8(bytes.get(at..number_end)?).ok()?.parse::().ok()?; + let generation_at = skip_space_and_comments(bytes, number_end, work); + let generation_len = count_while(bytes, generation_at, |c| c.is_ascii_digit() || matches!(c, b'.' | b'+' | b'-')); + *work = work.saturating_sub(generation_len); + if generation_len == 0 { + return None; + } + let generation_end = generation_at.checked_add(generation_len)?; + let generation = std::str::from_utf8(bytes.get(generation_at..generation_end)?).ok().and_then(|g| g.parse::().ok()).unwrap_or(0); + let keyword = skip_space_and_comments(bytes, generation_end, work); + (bytes.get(keyword..keyword.checked_add(3)?)? == b"obj").then_some((num, generation, keyword + 3)) +} + +/// How many bytes from `from` on `accept` takes. +fn count_while(bytes: &[u8], from: usize, accept: fn(u8) -> bool) -> usize { + bytes.get(from..).map_or(0, |rest| rest.iter().take_while(|b| accept(**b)).count()) +} + +/// Where the white space and comments from `from` end, every byte passed spent from `work`: many +/// candidate headers can end in the same long run of white space, as in `1+1+1…` before it. +fn skip_space_and_comments(bytes: &[u8], mut from: usize, work: &mut usize) -> usize { + while let Some(b) = bytes.get(from) { + if is_white_space(*b) { + *work = work.saturating_sub(1); + from = from.saturating_add(1); + } else if *b == b'%' { + let comment = count_while(bytes, from.saturating_add(1), |c| c != b'\n' && c != b'\r').saturating_add(1); + *work = work.saturating_sub(comment); + from = from.saturating_add(comment); + } else { + break; + } + } + from +} + fn refs(doc: &Document, o: Option<&Object>) -> Vec { o.map(|o| doc.resolve(o)).and_then(|a| a.as_array().map(|a| a.iter().filter_map(Object::as_ref).collect())).unwrap_or_default() } @@ -1146,4 +1316,69 @@ mod tests { other => panic!("the certification's /Perms changed in place under P=1: {other:?}"), } } + + /// `signed` with a revision appended that writes `before` and then object 3, listed where its + /// header is. + fn append_object_3(signed: &[u8], before: &[u8]) -> Vec { + let at = signed.windows(9).rposition(|w| w == b"startxref").unwrap() + 9; + let prev: String = + signed.get(at..).unwrap().iter().skip_while(|b| b.is_ascii_whitespace()).take_while(|b| b.is_ascii_digit()).map(|b| *b as char).collect(); + let mut bytes = signed.to_vec(); + bytes.extend_from_slice(before); + let object = bytes.len(); + bytes.extend_from_slice(b"3 0 obj\n(x)\nendobj\n"); + let section = bytes.len(); + bytes.extend_from_slice( + format!("xref\n3 1\n{object:010} 00000 n \ntrailer\n<< /Size 4 /Root 1 0 R /Prev {prev} >>\nstartxref\n{section}\n%%EOF\n").as_bytes(), + ); + bytes + } + + /// A comment of digits (`%1%1%1…`), a run of signed numbers (`1 +1+1+1…`), or a short one + /// before long white space, appended after signing, would make the header scan start at each + /// digit and read to the end of the run every time, quadratic in the appended bytes. Past a + /// bound on that work the appended bytes are not judged; an ordinary revision is. + #[test] + fn the_header_scan_is_bounded_on_runs_that_restart_it() { + let signed = pdf(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"], ""); + let old = Document::open(Arc::new(signed.clone())).unwrap(); + let comment = [b"%".to_vec(), b"1%".repeat(50_000), b"\n".to_vec()].concat(); + let numbers = [b"1 ".to_vec(), b"+1".repeat(50_000), b"\n".to_vec()].concat(); + // Each start reads the short run of numbers, then the same long white space after it. + let spaced = [b"1".to_vec(), b"+1".repeat(2_000), b" ".repeat(1 << 20), b"\n".to_vec()].concat(); + for (what, run) in [("a comment of digits", comment), ("a run of signed numbers", numbers), ("signed numbers before white space", spaced)] { + let doc = Document::open(Arc::new(append_object_3(&signed, &run))).unwrap(); + assert_eq!(unlisted_bodies(&doc, &old), None, "{what}"); + } + let doc = Document::open(Arc::new(append_object_3(&signed, b"% an ordinary comment 1 2 3\n"))).unwrap(); + assert_eq!(unlisted_bodies(&doc, &old), Some(Vec::new())); + } + + /// Many entries of an appended section that point at one place before a long run of white + /// space would make matching each header to its entry read that run again every time. Past + /// the same bound on work, the appended bytes are not judged. + #[test] + fn matching_headers_to_their_entries_is_bounded_too() { + let signed = pdf(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"], ""); + let old = Document::open(Arc::new(signed.clone())).unwrap(); + let at = signed.windows(9).rposition(|w| w == b"startxref").unwrap() + 9; + let prev: String = + signed.get(at..).unwrap().iter().skip_while(|b| b.is_ascii_whitespace()).take_while(|b| b.is_ascii_digit()).map(|b| *b as char).collect(); + let mut bytes = signed.clone(); + let blank = bytes.len(); + bytes.extend_from_slice(&b" ".repeat(1 << 20)); + bytes.push(b'\n'); + let count = 2_000u32; + for num in 3..3 + count { + bytes.extend_from_slice(format!("{num} 0 obj\n(x)\nendobj\n").as_bytes()); + } + let section = bytes.len(); + bytes.extend_from_slice(format!("xref\n3 {count}\n").as_bytes()); + for _ in 0..count { + bytes.extend_from_slice(format!("{blank:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R /Prev {prev} >>\nstartxref\n{section}\n%%EOF\n", 3 + count).as_bytes()); + let doc = Document::open(Arc::new(bytes)).unwrap(); + assert_eq!(unlisted_bodies(&doc, &old), None); + } } diff --git a/crates/sign/tests/it/pdf.rs b/crates/sign/tests/it/pdf.rs index fd2ec6e240..0805357e05 100644 --- a/crates/sign/tests/it/pdf.rs +++ b/crates/sign/tests/it/pdf.rs @@ -3165,6 +3165,172 @@ fn a_cross_reference_entry_that_misses_its_object_is_not_an_unchanged_object() { assert_eq!(s.status, Status::Valid, "{:?}", s.details); } +/// `signed` with one more revision appended by hand: `bodies` written as they are, then a +/// cross-reference table section whose subsections `xref` writes, given where each body starts +/// and where the section's own `xref` keyword is. `trailer_extra` goes into its trailer, which +/// continues the signed chain. +fn append_revision(signed: &[u8], bodies: &[&str], trailer_extra: &str, xref: impl Fn(&[usize], usize) -> String) -> Vec { + let at = signed.windows(9).rposition(|w| w == b"startxref").unwrap() + 9; + let prev: String = signed[at..].iter().skip_while(|b| b.is_ascii_whitespace()).take_while(|b| b.is_ascii_digit()).map(|b| *b as char).collect(); + let mut out = signed.to_vec(); + let mut starts = Vec::new(); + for body in bodies { + starts.push(out.len()); + out.extend_from_slice(body.as_bytes()); + } + let section = out.len(); + out.extend_from_slice( + format!("xref\n{}trailer\n<< /Size 61 /Root 1 0 R /Prev {prev} {trailer_extra} >>\nstartxref\n{section}\n%%EOF\n", xref(&starts, section)) + .as_bytes(), + ); + out +} + +/// When an entry it follows leads to no object, the renderer rebuilds its object index from the +/// `N G obj` headers in the file, and there the last header for a number wins. So a revision +/// appended after signing can carry a new body for the page's content stream that no section +/// lists, plus an entry, named from the trailer, that points at no object: the page draws the +/// unlisted body while every object the signed revision had still reads as signed. Neither is a +/// permitted change, apart or together, under a certification or an approval signature. An +/// honest revision that lists what it adds stays permitted. +#[test] +fn an_unlisted_object_body_or_an_entry_that_points_at_no_object_is_not_permitted() { + let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap(); + let trust = TrustStore { certs: vec![id.certificate.clone()] }; + let text = "BT /F1 14 Tf 20 250 Td (Forged text) Tj ET"; + let forged = format!("4 0 obj\n<< /Length {} >>\nstream\n{text}\nendstream\nendobj\n", text.len()); + let unused = "60 0 obj\n(unused)\nendobj\n"; + // Object 60's entry points at the section's own `xref` keyword. + let nowhere = |_: &[usize], section: usize| format!("60 1\n{}", xref_entry(section)); + let listed = |starts: &[usize], _: usize| format!("60 1\n{}", xref_entry(*starts.last().unwrap())); + for certify in [Some(1), None] { + let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify, ..opts() }).unwrap(); + let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap(); + type Subsections<'a> = &'a dyn Fn(&[usize], usize) -> String; + let attacks: [(&str, Vec<&str>, &str, Subsections, &str); 3] = [ + ("an unlisted body and an entry that points at no object", vec![&forged], "/Info 60 0 R", &nowhere, kind::PAGE_CONTENT), + ("an entry that points at no object", vec![], "/Info 60 0 R", &nowhere, kind::OTHER), + ("an unlisted body beside a listed one", vec![&forged, unused], "", &listed, kind::PAGE_CONTENT), + ]; + for (name, bodies, trailer, xref, what) in attacks { + let edited = append_revision(&signed, &bodies, trailer, xref); + let s = check(&edited); + assert_eq!(s.status, Status::Invalid, "{certify:?}, {name}: {:?}", s.modification); + assert!(matches!(&s.modification, Modification::Disallowed(k) if k.contains(&what)), "{certify:?}, {name}: {:?}", s.modification); + } + let honest = append_revision(&signed, &[unused], "", listed); + let s = check(&honest); + assert_eq!(s.status, Status::Valid, "{certify:?}, an honest revision: {:?}", s.modification); + } +} + +/// `signed` (one page, object 3) with a revision appended by hand that signs it again, as many +/// writers do: it adds signature field 61, listed in the catalog's `/Fields` and on page 3, whose +/// value 62 is a signature dictionary over that revision, and ends with a cross-reference stream, +/// object `xref_num`, that lists 1, 3, 61 and 62 but has no row for itself. ISO 32000-2 §7.5.8.3 +/// asks for that row; readers do without it. `annot_extra` is listed on page 3 as well. +fn append_signature_with_unlisted_xref_stream(signed: &[u8], xref_num: u32, annot_extra: Option) -> Vec { + let doc = open(signed); + let at = signed.windows(9).rposition(|w| w == b"startxref").unwrap() + 9; + let prev: i64 = std::str::from_utf8(&signed[at..]).unwrap().split_whitespace().next().unwrap().parse().unwrap(); + let r = |num: u32| ObjRef { num, generation: 0 }; + let mut catalog = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap(); + if let Some(Object::Dict(form)) = catalog.get_mut(b"AcroForm") + && let Some(Object::Array(fields)) = form.get_mut(b"Fields") + { + fields.push(Object::Ref(r(61))); + } + let mut page = doc.get(r(3)).as_dict().cloned().unwrap(); + let mut annots = page.get(b"Annots").and_then(Object::as_array).cloned().unwrap(); + annots.push(Object::Ref(r(61))); + annots.extend(annot_extra.map(|n| Object::Ref(r(n)))); + page.set(b"Annots".to_vec(), Object::Array(annots)); + let placeholder = "0 0000000000 0000000000 0000000000"; + let bodies: [(u32, Vec); 4] = [ + (1, { + let mut b = Vec::new(); + pdfcraft_cos::serialize(&Object::Dict(catalog), &mut b); + b + }), + (3, { + let mut b = Vec::new(); + pdfcraft_cos::serialize(&Object::Dict(page), &mut b); + b + }), + (61, b"<< /Type /Annot /Subtype /Widget /FT /Sig /T (Later) /Rect [0 0 0 0] /F 132 /P 3 0 R /V 62 0 R >>".to_vec()), + ( + 62, + format!("<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /ByteRange [{placeholder}] /Contents <00> >>").into_bytes(), + ), + ]; + let mut out = signed.to_vec(); + let mut rows = Vec::new(); + for (num, body) in &bodies { + rows.push((*num, out.len())); + out.extend_from_slice(format!("{num} 0 obj\n").as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + // Rows of type 1: four bytes of offset, two of generation. + let mut data = Vec::new(); + for (_, offset) in &rows { + data.push(1u8); + data.extend_from_slice(&u32::try_from(*offset).unwrap().to_be_bytes()); + data.extend_from_slice(&[0, 0]); + } + let mut dict = doc.trailer().clone(); + let plumbing: [&[u8]; 7] = [b"Prev", b"XRefStm", b"Index", b"W", b"Filter", b"DecodeParms", b"Length"]; + for key in plumbing { + dict.remove(key); + } + dict.set(b"Type".to_vec(), Object::name("XRef")); + dict.set(b"Size".to_vec(), Object::Int(64)); + dict.set(b"Prev".to_vec(), Object::Int(prev)); + dict.set(b"W".to_vec(), Object::Array([1, 4, 2].map(Object::Int).to_vec())); + dict.set(b"Index".to_vec(), Object::Array([1, 1, 3, 1, 61, 2].map(Object::Int).to_vec())); + dict.set(b"Length".to_vec(), Object::Int(i64::try_from(data.len()).unwrap())); + let section = out.len(); + out.extend_from_slice(format!("{xref_num} 0 obj\n").as_bytes()); + pdfcraft_cos::serialize(&Object::Dict(dict), &mut out); + out.extend_from_slice(b"\nstream\n"); + out.extend_from_slice(&data); + out.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{section}\n%%EOF\n").as_bytes()); + // The value signs the revision: its range runs to the end, around /Contents. + let contents = out.windows(4).rposition(|w| w == b"<00>").unwrap(); + let range = format!("0 {contents:010} {:010} {:010}", contents + 4, out.len() - contents - 4); + let at = out.windows(placeholder.len()).rposition(|w| w == placeholder.as_bytes()).unwrap(); + out[at..at + placeholder.len()].copy_from_slice(range.as_bytes()); + out +} + +/// Many writers append a cross-reference stream with no row for itself. Its header sits in the +/// appended bytes where no entry points, but it is the section the reader followed, and nothing +/// refers to it: a later signature written that way stays a permitted change. The exemption +/// holds only for that: the same stream numbered as the signed page's content, or listed on the +/// page as an annotation, is refused. +#[test] +fn a_cross_reference_stream_without_a_row_for_itself_is_no_unlisted_body() { + let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap(); + let trust = TrustStore { certs: vec![id.certificate.clone()] }; + for certify in [Some(2), None] { + let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify, ..opts() }).unwrap(); + let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.field == "Signature1").unwrap(); + let resigned = append_signature_with_unlisted_xref_stream(&signed, 63, None); + let doc = open(&resigned); + assert!(doc.revisions().iter().any(|r| r.is_stream) && doc.xref_entry(63).is_none() && doc.xref_entry(62).is_some()); + let s = check(&resigned); + assert_eq!(s.status, Status::Valid, "{certify:?}: {:?}", s.modification); + assert_eq!(s.modification, Modification::Allowed(vec![kind::SIGNATURE]), "{certify:?}"); + for (what, xref_num, annot_extra, kind) in + [("numbered as the signed page content", 4, None, kind::PAGE_CONTENT), ("listed on the page", 63, Some(63), kind::OTHER)] + { + let s = check(&append_signature_with_unlisted_xref_stream(&signed, xref_num, annot_extra)); + assert_eq!(s.status, Status::Invalid, "{certify:?}, {what}: {:?}", s.modification); + assert!(matches!(&s.modification, Modification::Disallowed(k) if k.contains(&kind)), "{certify:?}, {what}: {:?}", s.modification); + } + } +} + /// `fixture()` with the page's resources indirect: object 7 is the resources dictionary, 8 its /// `/Font` dictionary, 9 an `/ExtGState` the content uses, and 5 the font as before. fn fixture_with_indirect_resources() -> Vec {