diff --git a/crates/sign/src/pdf/changes.rs b/crates/sign/src/pdf/changes.rs index 01e6b90889..f3d52f84c4 100644 --- a/crates/sign/src/pdf/changes.rs +++ b/crates/sign/src/pdf/changes.rs @@ -982,7 +982,7 @@ fn extensions_kept(doc: &Document, old: &Document, d: &Dict, b: &Dict) -> bool { /// A change to the signed catalog `b`, now `d`. fn catalog_kind(doc: &Document, old: &Document, d: &Dict, b: &Dict) -> &'static str { - let keys: &[&[u8]] = &[b"AcroForm", b"DSS", b"Perms", b"Metadata", b"NeedsRendering", b"Extensions"]; + let keys: &[&[u8]] = &[b"AcroForm", b"DSS", b"Perms", b"Metadata", b"Extensions"]; if !same_entries(d, b, keys) { kind::STRUCTURE } else if !extensions_kept(doc, old, d, b) { diff --git a/crates/sign/src/pdf/listing.rs b/crates/sign/src/pdf/listing.rs index 2d41477127..3c4afb1b32 100644 --- a/crates/sign/src/pdf/listing.rs +++ b/crates/sign/src/pdf/listing.rs @@ -1,7 +1,7 @@ use std::rc::Rc; use super::types::{Detail, Modification, Status, TrustStore}; -use super::validate::{is_doc_timestamp, validate_doc_timestamp, validate_into}; +use super::validate::{SignatureValidation, is_doc_timestamp, validate_doc_timestamp, validate_into}; use super::{Arc, Dict, DigestAlg, Document, HashMap, HashSet, ObjRef, Object, SignatureInfo}; /// Digests of signed byte ranges (and parsed signed revisions), kept across revalidations of @@ -486,7 +486,7 @@ pub fn list_cached(doc: &Document, bytes: &[u8], trust: &TrustStore, cache: &Dig details: Vec::new(), }; if let Some(v) = v { - validate_into(doc, bytes, trust, &v, &mut info, cache); + validate_into(SignatureValidation { doc, bytes, trust, field: Some(&f), stamp_ref: None, info: &mut info, cache }, &v); } if let Some(r) = shared { judged.insert(r, out.len()); @@ -532,7 +532,7 @@ pub fn list_cached(doc: &Document, bytes: &[u8], trust: &TrustStore, cache: &Dig verdict_shown: false, details: Vec::new(), }; - validate_doc_timestamp(doc, bytes, d, &mut info, cache, trust); + validate_doc_timestamp(SignatureValidation { doc, bytes, trust, field: None, stamp_ref: Some(r), info: &mut info, cache }, d); out.push(info); } if !whole { diff --git a/crates/sign/src/pdf/validate.rs b/crates/sign/src/pdf/validate.rs index 66eec94f20..32874b81c8 100644 --- a/crates/sign/src/pdf/validate.rs +++ b/crates/sign/src/pdf/validate.rs @@ -1,19 +1,23 @@ use super::changes::classify_changes; -use super::listing::{DigestCache, list, nums, sig_fields, text}; +use super::listing::{DigestCache, Field, list, nums, sig_fields, text}; use super::locks::{Locked, locked_fields}; use super::types::{Detail, Fill, Modification, Status, TrustStore, kind}; use super::{ Certificate, Dict, DigestAlg, Document, HashSet, ObjRef, Object, SignError, SignatureInfo, SignedData, Time, build_chain, build_chain_noted, }; -struct SignatureValidation<'a> { - doc: &'a Document, - bytes: &'a [u8], - trust: &'a TrustStore, - info: &'a mut SignatureInfo, - cache: &'a DigestCache, +/// Inputs and output target for validating one signature or document timestamp. +pub(super) struct SignatureValidation<'a> { + pub(super) doc: &'a Document, + pub(super) bytes: &'a [u8], + pub(super) trust: &'a TrustStore, + pub(super) field: Option<&'a Field>, + pub(super) stamp_ref: Option, + pub(super) info: &'a mut SignatureInfo, + pub(super) cache: &'a DigestCache, } +/// Cryptographically verified signature material before chain, trust, and change checks. struct VerifiedSignature<'a> { covered: usize, certificate: Certificate, @@ -82,42 +86,118 @@ fn set_certification(doc: &Document, v: &Dict, info: &mut SignatureInfo) { } } -pub(super) fn validate_into(doc: &Document, bytes: &[u8], trust: &TrustStore, v: &Dict, info: &mut SignatureInfo, cache: &DigestCache) { +/// Whether `covered` spans the entire file (ignoring trailing whitespace and NUL padding). +fn whole_file(bytes: &[u8], covered: usize) -> bool { + covered == bytes.len() || bytes.get(covered..).is_some_and(|rest| rest.iter().all(|b| b.is_ascii_whitespace() || *b == 0)) +} + +/// The raw bytes of `d`'s `/Contents` string. +fn dict_contents(doc: &Document, d: &Dict) -> Option> { + let contents = d.get(b"Contents").map(|c| doc.resolve(c))?; + let s = contents.as_string()?; + if s.hex { Some(s.bytes.clone()) } else { unhex(&s.bytes) } +} + +/// Locate the signature or standalone timestamp dictionary in an earlier revision `rev`. +fn find_sig_in_revision(rev: &Document, field: Option<&Field>, stamp_ref: Option) -> Option { + if let Some(f) = field { + // A later field that reuses the name is a different field. Match the object when we + // have one, and the name only when neither side has an object. Two candidates is not + // a match: the signature must not be reported on an attacker-chosen widget. + let mut matched = sig_fields(rev).into_iter().filter(|of| match f.r { + Some(want) => of.r == Some(want), + None => of.r.is_none() && of.name == f.name, + }); + let found = matched.next()?; + if matched.next().is_some() { + return None; + } + found.signature(rev) + } else if let Some(r) = stamp_ref { + rev.try_get(r.num).ok().and_then(|o| o.as_dict().cloned()).filter(is_doc_timestamp) + } else { + None + } +} + +/// The revision in which this signature or timestamp first appeared (when an earlier revision +/// already holds it), or the current document. +fn earliest_signed_dict(context: &SignatureValidation<'_>, v: &Dict) -> (Document, Dict) { + let ends = context.doc.revision_ends(); + if ends.len() > 1 { + for &end in &ends[..ends.len() - 1] { + if end < context.bytes.len() + && !whole_file(context.bytes, end) + && let Some(old) = context.cache.revision(context.doc, context.bytes, end) + && let Some(old_v) = find_sig_in_revision(&old, context.field, context.stamp_ref) + { + return (old, old_v); + } + } + } + (context.doc.clone(), v.clone()) +} + +/// Validate a signature field's dictionary `v` and record the verdict in `context.info`. +pub(super) fn validate_into(context: SignatureValidation<'_>, v: &Dict) { + let (mut sig_doc, mut sig_v) = earliest_signed_dict(&context, v); // A document timestamp can also be the value of a signature field (Documenso writes // `Timestamp_1` that way). Its `/Contents` is a bare RFC 3161 token, not a signature over the // document, so it must not be read as one. - if is_doc_timestamp(v) { - info.sub_filter = Some("ETSI.RFC3161".to_string()); - info.doc_timestamp = true; - info.timestamp = true; - validate_doc_timestamp(doc, bytes, v, info, cache, trust); + if is_doc_timestamp(&sig_v) || is_doc_timestamp(v) { + context.info.sub_filter = Some("ETSI.RFC3161".to_string()); + context.info.doc_timestamp = true; + context.info.timestamp = true; + validate_doc_timestamp(context, v); return; } - info.date = text(doc, v, b"M"); - info.reason = text(doc, v, b"Reason"); - info.location = text(doc, v, b"Location"); - info.contact = text(doc, v, b"ContactInfo"); - info.sub_filter = v.name(b"SubFilter").map(|s| String::from_utf8_lossy(s).into_owned()); - info.signer = text(doc, v, b"Name"); - set_certification(doc, v, info); + let SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache } = context; + let fill_metadata = |d_doc: &Document, d_v: &Dict, info: &mut SignatureInfo| { + info.date = text(d_doc, d_v, b"M"); + info.reason = text(d_doc, d_v, b"Reason"); + info.location = text(d_doc, d_v, b"Location"); + info.contact = text(d_doc, d_v, b"ContactInfo"); + info.sub_filter = d_v.name(b"SubFilter").map(|s| String::from_utf8_lossy(s).into_owned()); + info.signer = text(d_doc, d_v, b"Name"); + set_certification(d_doc, d_v, info); + }; + fill_metadata(&sig_doc, &sig_v, info); let invalid = |info: &mut SignatureInfo, why: Detail| { info.status = Status::Invalid; info.details.push(why); }; // Byte ranges: [0 a b c] with the gap holding exactly the hex /Contents. - let Some(br) = nums(doc, v, b"ByteRange").filter(|b| b.len() == 4 && b.iter().all(|x| *x >= 0.0)) else { + let Some(br) = nums(&sig_doc, &sig_v, b"ByteRange").filter(|b| b.len() == 4 && b.iter().all(|x| *x >= 0.0)) else { return invalid(info, Detail::plain("The signature has no valid byte range.")); }; let [o0, l0, o1, l1] = [br[0] as usize, br[1] as usize, br[2] as usize, br[3] as usize]; if o0 != 0 || o1 < l0 || o1.checked_add(l1).is_none_or(|end| end > bytes.len()) || o1 - l0 < 2 { return invalid(info, Detail::plain("The signature's byte range does not match the file.")); - } + }; let gap = &bytes[l0..o1]; if gap.first() != Some(&b'<') || gap.last() != Some(&b'>') { return invalid(info, Detail::plain("The signature's byte range does not exclude exactly its contents.")); } let Some(contents) = unhex(&gap[1..gap.len() - 1]) else { return invalid(info, Detail::plain("The signature contents are not hexadecimal.")) }; let covered = o1 + l1; + if !whole_file(bytes, covered) { + let Some(old) = cache.revision(doc, bytes, covered) else { + return invalid(info, Detail::plain("The signature's byte range does not match the file.")); + }; + let Some(old_v) = find_sig_in_revision(&old, field, stamp_ref) else { + return invalid(info, Detail::plain("The signature's byte range does not match the file.")); + }; + if nums(&old, &old_v, b"ByteRange") != Some(br) { + return invalid(info, Detail::plain("The signature's byte range does not match the file.")); + } + fill_metadata(&old, &old_v, info); + (sig_doc, sig_v) = (old, old_v); + } + let expected_contents = + sig_doc.bytes().get(l0..o1).filter(|g| g.first() == Some(&b'<') && g.last() == Some(&b'>')).and_then(|g| unhex(&g[1..g.len() - 1])); + if dict_contents(&sig_doc, &sig_v) != expected_contents { + return invalid(info, Detail::plain("The signature's byte range does not exclude exactly its contents.")); + } info.signed_len = covered; // The signed revision's number: its cross-reference sections (1 for a reconstructed file). info.revision = cache.revision(doc, bytes, covered).map_or(1, |d| d.revisions().len().max(1)); @@ -129,7 +209,13 @@ pub(super) fn validate_into(doc: &Document, bytes: &[u8], trust: &TrustStore, v: info.details.push(Detail::of("PdfCraft can't check this signature yet: {}.", Fill::Reason(why.to_owned()))); }; if info.sub_filter.as_deref() == Some("adbe.x509.rsa_sha1") { - return validate_x509_rsa_sha1(SignatureValidation { doc, bytes, trust, info, cache }, v, (l0, o1, covered), &contents); + return validate_x509_rsa_sha1( + SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache }, + &sig_doc, + &sig_v, + (l0, o1, covered), + &contents, + ); } let sd = match SignedData::parse(&contents) { Ok(sd) => sd, @@ -240,7 +326,7 @@ pub(super) fn validate_into(doc: &Document, bytes: &[u8], trust: &TrustStore, v: } } finish_validation( - SignatureValidation { doc, bytes, trust, info, cache }, + SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache }, VerifiedSignature { covered, certificate: cert, embedded: &sd.certificates, cms_time: s.signing_time, unverified_time }, ); } @@ -248,7 +334,7 @@ pub(super) fn validate_into(doc: &Document, bytes: &[u8], trust: &TrustStore, v: /// The verdict once the signature value has been checked: chain and trust, the signing time /// against the certificate's validity, and what later revisions changed. fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignature<'_>) { - let SignatureValidation { doc, bytes, trust, info, cache } = context; + let SignatureValidation { doc, bytes, trust, info, cache, .. } = context; let VerifiedSignature { covered, certificate: cert, embedded, cms_time, unverified_time } = verified; info.signing_time = cms_time.or_else(|| info.date.as_deref().and_then(Time::from_pdf)); let mut pool = embedded.to_vec(); @@ -272,7 +358,7 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu let revoked = revocation == DssRevocation::Revoked; // Changes after signing. let mut locks = Locked::Kept; - info.modification = if covered == bytes.len() || bytes[covered..].iter().all(|b| b.is_ascii_whitespace() || *b == 0) { + info.modification = if whole_file(bytes, covered) { Modification::None } else { // The permissions are the signed revision's: a later one can rewrite `/P` (#1788) or the @@ -410,7 +496,6 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu /// Distinct evidence streams read from one `/DSS` array. pub(crate) const MAX_DSS_ENTRIES: usize = 1024; - /// Decoded bytes read from one `/DSS` array; real CRLs and OCSP responses are kilobytes each. pub(crate) const MAX_DSS_BYTES: usize = 64 << 20; @@ -565,15 +650,17 @@ fn check_dss_revocation(doc: &Document, signer: Option<&Certificate>, at: &Optio } } -/// Validate a standalone document timestamp dictionary (`/ETSI.RFC3161`): the token must be -/// cryptographically valid and its message imprint must cover the file's signed bytes. -pub(super) fn validate_doc_timestamp(doc: &Document, bytes: &[u8], v: &Dict, info: &mut SignatureInfo, cache: &DigestCache, trust: &TrustStore) { - info.date = text(doc, v, b"M"); +/// Validate a standalone or field document timestamp dictionary (`/ETSI.RFC3161`): the token must +/// be cryptographically valid and its message imprint must cover the file's signed bytes. +pub(super) fn validate_doc_timestamp(context: SignatureValidation<'_>, v: &Dict) { + let (mut sig_doc, mut sig_v) = earliest_signed_dict(&context, v); + let SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache } = context; + info.date = text(&sig_doc, &sig_v, b"M"); let invalid = |info: &mut SignatureInfo, why: Detail| { info.status = Status::Invalid; info.details.push(why); }; - let Some(br) = nums(doc, v, b"ByteRange").filter(|b| b.len() == 4 && b.iter().all(|x| *x >= 0.0)) else { + let Some(br) = nums(&sig_doc, &sig_v, b"ByteRange").filter(|b| b.len() == 4 && b.iter().all(|x| *x >= 0.0)) else { return invalid(info, Detail::plain("The timestamp has no valid byte range.")); }; let [o0, l0, o1, l1] = [br[0] as usize, br[1] as usize, br[2] as usize, br[3] as usize]; @@ -588,6 +675,24 @@ pub(super) fn validate_doc_timestamp(doc: &Document, bytes: &[u8], v: &Dict, inf return invalid(info, Detail::plain("The timestamp contents are not hexadecimal.")); }; let covered = o1 + l1; + if !whole_file(bytes, covered) { + let Some(old) = cache.revision(doc, bytes, covered) else { + return invalid(info, Detail::plain("The timestamp's byte range does not match the file.")); + }; + let Some(old_v) = find_sig_in_revision(&old, field, stamp_ref) else { + return invalid(info, Detail::plain("The timestamp's byte range does not match the file.")); + }; + if nums(&old, &old_v, b"ByteRange") != Some(br) { + return invalid(info, Detail::plain("The timestamp's byte range does not match the file.")); + } + info.date = text(&old, &old_v, b"M"); + (sig_doc, sig_v) = (old, old_v); + } + let expected_contents = + sig_doc.bytes().get(l0..o1).filter(|g| g.first() == Some(&b'<') && g.last() == Some(&b'>')).and_then(|g| unhex(&g[1..g.len() - 1])); + if dict_contents(&sig_doc, &sig_v) != expected_contents { + return invalid(info, Detail::plain("The timestamp's byte range does not exclude exactly its contents.")); + } info.signed_len = covered; info.revision = cache.revision(doc, bytes, covered).map_or(1, |d| d.revisions().len().max(1)); let token = match crate::timestamp::parse_token(&contents) { @@ -694,14 +799,14 @@ pub(crate) fn signature_contents(doc: &Document) -> Vec> { /// `adbe.x509.rsa_sha1` (ISO 32000-2 ยง12.8.3.2, deprecated): `/Contents` is the PKCS #1 /// signature as a DER OCTET STRING over the SHA-1 digest of the byte ranges, and `/Cert` holds the /// signer's certificate (then any others) as DER byte strings. -fn validate_x509_rsa_sha1(context: SignatureValidation<'_>, v: &Dict, (l0, o1, covered): (usize, usize, usize), contents: &[u8]) { - let SignatureValidation { doc, bytes, trust, info, cache } = context; +fn validate_x509_rsa_sha1(context: SignatureValidation<'_>, sig_doc: &Document, v: &Dict, (l0, o1, covered): (usize, usize, usize), contents: &[u8]) { + let SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache } = context; let fail = |info: &mut SignatureInfo, why: Detail| { info.status = Status::Invalid; info.details.push(why); }; - let certs: Vec = match v.get(b"Cert").map(|c| doc.resolve(c)).as_deref() { - Some(Object::Array(a)) => a.iter().filter_map(|c| doc.resolve(c).as_string().map(|s| s.bytes.clone())).collect::>(), + let certs: Vec = match v.get(b"Cert").map(|c| sig_doc.resolve(c)).as_deref() { + Some(Object::Array(a)) => a.iter().filter_map(|c| sig_doc.resolve(c).as_string().map(|s| s.bytes.clone())).collect::>(), Some(Object::String(s)) => vec![s.bytes.clone()], _ => Vec::new(), } @@ -743,7 +848,7 @@ fn validate_x509_rsa_sha1(context: SignatureValidation<'_>, v: &Dict, (l0, o1, c info.details.push(Detail::plain("The signature uses the legacy adbe.x509.rsa_sha1 format.")); info.details.extend(DigestAlg::Sha1.weakness().map(Detail::plain)); finish_validation( - SignatureValidation { doc, bytes, trust, info, cache }, + SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache }, VerifiedSignature { covered, certificate: cert, embedded: &certs, cms_time: None, unverified_time: None }, ); } diff --git a/crates/sign/tests/it/pdf.rs b/crates/sign/tests/it/pdf.rs index 0805357e05..403426c053 100644 --- a/crates/sign/tests/it/pdf.rs +++ b/crates/sign/tests/it/pdf.rs @@ -1416,6 +1416,66 @@ fn xfa_page_swap(doc: &mut Document) { .unwrap(); } +/// A second widget that reuses the signed field's name and `/V` is not that signature. +#[test] +fn a_later_field_with_the_same_name_does_not_inherit_the_signature() { + let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap(); + let trust = TrustStore { certs: vec![id.certificate.clone()] }; + let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap(); + let edited = edit_after(&signed, |doc| { + let root = doc.root().unwrap(); + let form = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned()).unwrap(); + let fields = form.get(b"Fields").map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()).unwrap(); + let original = fields.iter().find_map(Object::as_ref).unwrap(); + let value = doc.get(original).as_dict().unwrap().get(b"V").cloned().expect("the signed field has /V"); + let mut widget = pdfcraft_cos::Dict::new(); + widget.set(b"Type".to_vec(), Object::name("Annot")); + widget.set(b"Subtype".to_vec(), Object::name("Widget")); + widget.set(b"FT".to_vec(), Object::name("Sig")); + widget.set(b"T".to_vec(), PdfString::text("Approval")); + widget.set(b"Rect".to_vec(), Object::Array(vec![Object::Int(10), Object::Int(10), Object::Int(80), Object::Int(40)])); + widget.set(b"P".to_vec(), Object::Ref(pdfcraft_cos::ObjRef { num: 3, generation: 0 })); + let cloned_v = doc.add((*doc.resolve(&value)).clone()); + widget.set(b"V".to_vec(), Object::Ref(cloned_v)); + let planted = doc.add(Object::Dict(widget)); + doc.update_dict(root, |c| { + if let Some(Object::Dict(form)) = c.get_mut(b"AcroForm") + && let Some(Object::Array(list)) = form.get_mut(b"Fields") + { + list.push(Object::Ref(planted)); + } + }) + .unwrap(); + doc.update_dict(pdfcraft_cos::ObjRef { num: 3, generation: 0 }, |p| { + if let Some(Object::Array(annots)) = p.get_mut(b"Annots") { + annots.push(Object::Ref(planted)); + } + }) + .unwrap(); + }); + let listed = signatures(&open(&edited), &edited, &trust); + let original = listed.iter().find(|s| s.rect == Some([150.0, 20.0, 280.0, 70.0])).expect("original field"); + let planted = listed.iter().find(|s| s.rect == Some([10.0, 10.0, 80.0, 40.0])).expect("planted field"); + assert_eq!(original.status, Status::Valid, "{:?}", original.details); + assert_ne!(planted.status, Status::Valid, "the planted widget inherited the signature: {:?}", planted.details); +} + +#[test] +fn toggling_needs_rendering_is_a_structure_change() { + let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap(); + let trust = TrustStore { certs: vec![id.certificate.clone()] }; + let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap(); + let certified = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap(); + assert_eq!(check(&certified).status, Status::Valid); + let edited = edit_after(&certified, |doc| { + let root = doc.root().unwrap(); + doc.update_dict(root, |c| c.set(b"NeedsRendering".to_vec(), Object::Bool(true))).unwrap(); + }); + let s = check(&edited); + assert_eq!(s.status, Status::Invalid, "{:?}", s.details); + assert!(matches!(&s.modification, Modification::Disallowed(k) if k.contains(&kind::STRUCTURE)), "{:?}", s.modification); +} + #[test] fn declaring_a_form_xfa_does_not_excuse_replacing_the_pages() { let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap(); @@ -3546,6 +3606,174 @@ fn signing_a_field_with_a_null_value_after_another_signature_keeps_the_first_val ); } +/// The signed catalog and page-tree nodes keep their structural roles even if a later revision +/// drops `/Type /Catalog` or `/Type /Pages` and adds form keys (`/FT /Tx`, `/DR`) while swapping +/// the page tree (#3998). +#[test] +fn signed_catalog_and_page_tree_keep_their_role_when_relabelled_or_dropped() { + use pdfcraft_cos::{ObjRef, Stream}; + // Rewriting the signed catalog without `/Type /Catalog` while pointing `/Pages` at a new page tree + // and adding `/FT /Tx` is refused as a structure change at every DocMDP level. + assert_refused_at_every_level(&fixture(), kind::STRUCTURE, |doc| { + let new_content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"BT /F1 14 Tf 20 250 Td (Forged) Tj ET".to_vec()))); + let new_page = doc.add(Object::Dict(dict_of(vec![ + ("Type", Object::name("Page")), + ("Parent", oref(2)), + ("MediaBox", Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(300), Object::Int(300)])), + ("Contents", Object::Ref(new_content)), + ]))); + let new_pages = doc.add(Object::Dict(dict_of(vec![ + ("Type", Object::name("Pages")), + ("Kids", Object::Array(vec![Object::Ref(new_page)])), + ("Count", Object::Int(1)), + ]))); + let af = doc.get(ObjRef { num: 1, generation: 0 }).as_dict().and_then(|c| c.get(b"AcroForm").cloned()).unwrap(); + doc.set( + ObjRef { num: 1, generation: 0 }, + Object::Dict(dict_of(vec![("Pages", Object::Ref(new_pages)), ("AcroForm", af), ("FT", Object::name("Tx"))])), + ); + }); + + // Rewriting the signed `/Pages` dictionary without `/Type /Pages` while replacing `/Kids` and + // adding `/FT /Tx` is refused as a page-tree change (`kind::PAGES`) at every DocMDP level. + assert_refused_at_every_level(&fixture(), kind::PAGES, |doc| { + let new_content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"BT /F1 14 Tf 20 250 Td (Forged) Tj ET".to_vec()))); + let new_page = doc.add(Object::Dict(dict_of(vec![ + ("Type", Object::name("Page")), + ("Parent", oref(2)), + ("MediaBox", Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(300), Object::Int(300)])), + ("Contents", Object::Ref(new_content)), + ]))); + doc.set( + ObjRef { num: 2, generation: 0 }, + Object::Dict(dict_of(vec![ + ("Kids", Object::Array(vec![Object::Ref(new_page), oref(3)])), + ("Count", Object::Int(2)), + ("FT", Object::name("Tx")), + ])), + ); + }); + + // Rewriting a signed non-form dictionary (such as an `/Action` dictionary) by adding `/FT /Tx` + // or `/DR` in a later revision is classified as `kind::OTHER` rather than `kind::FORM_FILL`, + // and is refused even under DocMDP `P = 2` (and `P = 3`). + let with_action = fixture_with( + b"<< /Type /Catalog /Pages 2 0 R /OpenAction 7 0 R /AcroForm << /Fields [6 0 R] >> >>", + &[b"<< /Type /Action /S /URI /URI (https://example.test/signed) >>"], + ); + assert_refused_at_every_level(&with_action, kind::OTHER, |doc| { + doc.set( + ObjRef { num: 7, generation: 0 }, + Object::Dict(dict_of(vec![ + ("Type", Object::name("Action")), + ("S", Object::name("URI")), + ("URI", Object::String(PdfString::text("https://attacker.invalid/phish"))), + ("FT", Object::name("Tx")), + ("DR", Object::Dict(Dict::new())), + ])), + ); + }); +} + +/// Signature dictionaries (`/ByteRange`, `/Contents`, `/Reference`) are read from the revision +/// covered by the signature, and rewriting a signed signature object or attaching a signature in a +/// later revision whose `/ByteRange` only covers an earlier revision is refused (#3998). +#[test] +fn signed_signature_objects_and_byte_ranges_are_read_from_the_signed_revision() { + let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap(); + let trust = TrustStore { certs: vec![id.certificate.clone()] }; + let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap(); + let sig_ref = open(&signed) + .object_numbers() + .into_iter() + .map(|num| pdfcraft_cos::ObjRef { num, generation: 0 }) + .find(|r| open(&signed).get(*r).as_dict().is_some_and(|d| d.name(b"Type") == Some(b"Sig"))) + .unwrap(); + + // Rewriting the signed `/Type /Sig` dictionary in a later revision (trying to relax `/P` from + // 1 to 3 and adding `/FT /Sig` so the rewrite looks like a signature field) keeps `certify` as + // `Some(1)` from the signed revision and invalidates the signature. + let relaxed = edit_after(&signed, |doc| { + doc.update_dict(sig_ref, |d| { + d.remove(b"Type"); + d.set(b"FT".to_vec(), Object::name("Sig")); + d.set( + b"Reference".to_vec(), + Object::Array(vec![Object::Dict(dict_of(vec![ + ("Type", Object::name("SigRef")), + ("TransformMethod", Object::name("DocMDP")), + ( + "TransformParams", + Object::Dict(dict_of(vec![("Type", Object::name("TransformParams")), ("P", Object::Int(3)), ("V", Object::name("1.2"))])), + ), + ]))]), + ); + }) + .unwrap(); + }); + let s = signatures(&open(&relaxed), &relaxed, &trust).into_iter().find(|s| s.signed).unwrap(); + assert_eq!(s.certify, Some(1), "DocMDP level must come from the signed revision"); + assert_eq!(s.status, Status::Invalid, "{:?}", s.modification); + assert!(matches!(&s.modification, Modification::Disallowed(k) if k.contains(&kind::OTHER)), "{:?}", s.modification); + + // A signature object added in a later revision whose `/ByteRange` only covers the earlier + // revision (where that signature field did not hold that signature) is refused. + let sig_dict = open(&signed).get(sig_ref).as_dict().cloned().unwrap(); + let replayed = edit_after(&signed, |doc| { + let replayed_v = doc.add(Object::Dict(sig_dict.clone())); + doc.update_dict(pdfcraft_cos::ObjRef { num: 6, generation: 0 }, |f| { + f.set(b"V".to_vec(), Object::Ref(replayed_v)); + }) + .unwrap(); + }); + let all = signatures(&open(&replayed), &replayed, &trust); + let approval = all.iter().find(|s| s.field == "Approval").unwrap(); + assert_eq!(approval.status, Status::Invalid, "a later signature whose ByteRange only covers an earlier revision must be invalid: {approval:?}"); +} + +/// Under DocMDP `P = 1` (no changes permitted), adding a signature field or counter-signing an +/// existing unsigned signature field invalidates the certifying signature, whereas adding an +/// RFC 3161 document timestamp (PAdES-LTA) remains permitted (#3998). +#[test] +fn certify_level_one_forbids_adding_signature_fields_or_counter_signing() { + let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap(); + let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } }; + let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()] }; + let certified_p1 = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap(); + let counter_p1 = pdfcraft_sign::sign(&open(&certified_p1), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap(); + let first_p1 = signatures(&open(&counter_p1), &counter_p1, &trust).into_iter().find(|s| s.field == "Signature1").unwrap(); + assert_eq!(first_p1.status, Status::Invalid, "{:?}", first_p1.modification); + assert_eq!(first_p1.modification, Modification::Disallowed(vec![kind::SIGNATURE])); + + // Adding an RFC 3161 document timestamp to a P = 1 certified document is permitted for + // long-term validation and keeps the certifying signature valid. + let stamped_p1 = pdfcraft_sign::timestamp_document(&open(&certified_p1), &tsa, "D:20261006120000Z").unwrap(); + let stamped_sigs = signatures(&open(&stamped_p1), &stamped_p1, &trust); + let cert_after_ts = stamped_sigs.iter().find(|s| s.field == "Signature1").unwrap(); + assert_eq!(cert_after_ts.status, Status::Valid, "{:?}", cert_after_ts.modification); + assert!(matches!(&cert_after_ts.modification, Modification::Allowed(k) if k.contains(&kind::SIGNATURE)), "{:?}", cert_after_ts.modification); + let doc_ts = stamped_sigs.iter().find(|s| s.doc_timestamp).unwrap(); + assert_eq!(doc_ts.status, Status::Valid, "{:?}", doc_ts.details); + + // Dropping `/Perms` from the catalog after certification is a structure change. + let dropped_perms = edit_after(&certified_p1, |doc| { + let root = doc.root().unwrap(); + doc.update_dict(root, |c| { + c.remove(b"Perms"); + }) + .unwrap(); + }); + let after_drop = signatures(&open(&dropped_perms), &dropped_perms, &trust).into_iter().find(|s| s.field == "Signature1").unwrap(); + assert_eq!(after_drop.status, Status::Invalid, "{:?}", after_drop.modification); + assert_eq!(after_drop.modification, Modification::Disallowed(vec![kind::STRUCTURE])); + + // Under P = 2 (filling forms and signing allowed), the same counter-signature is permitted. + let certified_p2 = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(2), ..opts() }).unwrap(); + let counter_p2 = pdfcraft_sign::sign(&open(&certified_p2), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap(); + let first_p2 = signatures(&open(&counter_p2), &counter_p2, &trust).into_iter().find(|s| s.field == "Signature1").unwrap(); + assert_eq!(first_p2.status, Status::Valid, "{:?}", first_p2.modification); +} + /// Fields that name one signature value are listed each, under their own name, with the verdict /// the value earned once. #[test]