From d6f9083a3f682b6f28d0e00a0e6de89869f740e0 Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Mon, 9 Nov 2026 13:48:19 -0500 Subject: [PATCH] fix(sign): a change to a field a signature locks invalidates it (#6757) Validation read only DocMDP references. A signature field's /Lock and the FieldMDP references in its value were ignored, so filling a locked field after an approval signature read as a permitted form fill and the signature stayed Valid. Read both from the signed revision (All, Include, Exclude; a listed name covers the fields below it) and compare every locked field between that revision and the document now: its dictionary and the ones above it, and its widgets. A field that changed, went away or gained a twin under its name adds the new "locked field" kind to a disallowed modification. A lock that can't be read or compared leaves the signature Unknown. --- crates/sign/src/pdf.rs | 1 + crates/sign/src/pdf/locks.rs | 426 ++++++++++++++++++++++++++++ crates/sign/src/pdf/types.rs | 6 +- crates/sign/src/pdf/validate.rs | 38 ++- crates/sign/tests/it/field_locks.rs | 185 ++++++++++++ crates/sign/tests/it/main.rs | 1 + parity/acrobat-features.toml | 8 +- 7 files changed, 653 insertions(+), 12 deletions(-) create mode 100644 crates/sign/src/pdf/locks.rs create mode 100644 crates/sign/tests/it/field_locks.rs diff --git a/crates/sign/src/pdf.rs b/crates/sign/src/pdf.rs index 805cc1eacf..a491f15054 100644 --- a/crates/sign/src/pdf.rs +++ b/crates/sign/src/pdf.rs @@ -25,6 +25,7 @@ use crate::x509::{Certificate, build_chain, build_chain_noted}; mod changes; mod listing; +mod locks; mod signing; mod types; mod validate; diff --git a/crates/sign/src/pdf/locks.rs b/crates/sign/src/pdf/locks.rs new file mode 100644 index 0000000000..60d0b613a3 --- /dev/null +++ b/crates/sign/src/pdf/locks.rs @@ -0,0 +1,426 @@ +//! Fields a signature locks: its field's `/Lock` (ISO 32000-2 §12.7.5.5, Table 236) and the +//! FieldMDP transform in its value's `/Reference` (§12.8.2.4). Signers write either or both. Once +//! the field is signed, a change to a field the lock names breaks the signature, whatever the +//! change would count as otherwise (#6757). +//! +//! The locks are read from the signed revision, and the locked fields are compared between that +//! revision and the document as it is now: each field's dictionary and the ones above it (an +//! inherited `/V` is its value too), and its widgets. A field that is gone, or a second field +//! under its name, is a change as well. + +use std::collections::BTreeMap; + +use super::listing::{Field, MAX_ENTRIES, MAX_FIELD_NAME_BYTES, MAX_FIELDS, MAX_NAME_BYTES, text}; +use super::{Dict, Document, HashSet, ObjRef, Object}; + +/// What a lock covers (`/Action`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Action { + All, + Include, + Exclude, +} + +/// One lock: its action and the fully qualified names it lists. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Rule { + action: Action, + names: Vec, +} + +impl Rule { + /// Whether the rule locks field `name`. A listed name also covers the fields below it + /// (`address` covers `address.city`). + fn locks(&self, name: &str) -> bool { + let listed = || self.names.iter().any(|x| name == x || name.strip_prefix(x.as_str()).is_some_and(|r| r.starts_with('.'))); + match self.action { + Action::All => true, + Action::Include => listed(), + Action::Exclude => !listed(), + } + } +} + +/// Most names one lock lists; real locks name a handful. +const MAX_LOCK_NAMES: usize = MAX_FIELDS; +/// Deepest field tree walked. Real forms nest a few levels. +const MAX_FIELD_DEPTH: usize = 64; +/// Most objects one comparison visits, for all the locked fields of one signature together. +const MAX_COMPARED: usize = 1 << 18; + +/// What comparing a signature's locked fields found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Locked { + /// The signature locks no field, or none it locks changed. + Kept, + /// A field it locks changed. + Changed, + /// It locks fields, but a cap or a lock that can't be read kept them from being compared. + Unchecked, +} + +/// A lock dictionary (`/Lock`) or FieldMDP transform parameters. `Err` when it is there but can't +/// be read: its action is not one of the three, or it lists more names than are read. +fn rule(doc: &Document, d: &Dict) -> Result { + let action = match d.name(b"Action") { + Some(b"All") => Action::All, + Some(b"Include") => Action::Include, + Some(b"Exclude") => Action::Exclude, + _ => return Err(()), + }; + let listed = d.get(b"Fields").map(|f| doc.resolve(f)); + let listed = listed.as_deref().and_then(Object::as_array).map(Vec::as_slice).unwrap_or_default(); + if listed.len() > MAX_LOCK_NAMES { + return Err(()); + } + let names = listed + .iter() + .filter_map(|n| match &*doc.resolve(n) { + Object::String(s) => Some(s.to_text()), + Object::Name(n) => Some(String::from_utf8_lossy(n).into_owned()), + _ => None, + }) + .map(|s| s.trim_matches('\0').trim().to_owned()) + .filter(|s| !s.is_empty()) + .collect(); + Ok(Rule { action, names }) +} + +/// The locks of signature field `field`, whose value is `value`, both as the signed revision `old` +/// has them. `Err` when one is there but can't be read. +fn rules(old: &Document, field: &Field, value: &Dict) -> Result, ()> { + let mut out = Vec::new(); + if let Some(lock) = field.dict.get(b"Lock").map(|l| old.resolve(l)) { + match &*lock { + Object::Dict(d) => out.push(rule(old, d)?), + Object::Null => {} + _ => return Err(()), + } + } + let refs = value.get(b"Reference").map(|r| old.resolve(r)); + for r in refs.as_deref().and_then(Object::as_array).into_iter().flatten() { + let r = old.resolve(r); + let Some(rd) = r.as_dict() else { continue }; + if rd.name(b"TransformMethod") != Some(b"FieldMDP") { + continue; + } + let params = rd.get(b"TransformParams").map(|p| old.resolve(p)); + match params.as_deref().and_then(Object::as_dict) { + Some(p) => out.push(rule(old, p)?), + // A FieldMDP reference that does not say what it locks is a lock that can't be read. + None => return Err(()), + } + } + Ok(out) +} + +/// Whether any field the signature in `field` (signed with `value`) locks in the signed revision +/// `old` is different in `doc`, the document as it is now. +pub(super) fn locked_fields(doc: &Document, old: &Document, field: &Field, value: &Dict) -> Locked { + let Ok(rules) = rules(old, field, value) else { return Locked::Unchecked }; + if rules.is_empty() { + return Locked::Kept; + } + let Some(before) = form_fields(old) else { return Locked::Unchecked }; + let locked: Vec<&String> = before.fields.keys().filter(|name| **name != field.name && rules.iter().any(|r| r.locks(name))).collect(); + if locked.is_empty() { + return Locked::Kept; + } + let Some(now) = form_fields(doc) else { return Locked::Unchecked }; + let mut same = Same { old, doc, left: MAX_COMPARED, assumed: HashSet::new() }; + for name in locked { + let (Some(was), Some(is)) = (before.fields.get(name), now.fields.get(name)) else { return Locked::Changed }; + if was.len() != is.len() { + return Locked::Changed; + } + for (w, i) in was.iter().zip(is) { + match same.field(&before, w, &now, i) { + Some(true) => {} + Some(false) => return Locked::Changed, + None => return Locked::Unchecked, + } + } + } + Locked::Kept +} + +/// One field dictionary in a walk of the form, and the one above it. +struct Node { + dict: Dict, + parent: Option, +} + +/// One field under its fully qualified name: its node, and its widgets apart from it. +struct Entry { + node: usize, + widgets: Vec, +} + +/// Every field of a form by fully qualified name, terminal or not, in walk order. +struct Form { + nodes: Vec, + fields: BTreeMap>, +} + +/// The fields of `doc`'s form, or `None` when a cap stopped the walk (a field it did not read may +/// be one a lock names). The caps are the signature listing's. +fn form_fields(doc: &Document) -> Option
{ + let mut form = Form { nodes: Vec::new(), fields: BTreeMap::new() }; + let Some(root) = doc.root() else { return Some(form) }; + let Some(af) = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)) else { return Some(form) }; + let af = match &*af { + Object::Dict(d) => d.clone(), + Object::Null => return Some(form), + _ => return None, + }; + let top = af.get(b"Fields").map(|f| doc.resolve(f)); + let top: Vec = match top.as_deref() { + None | Some(Object::Null) => return Some(form), + Some(Object::Array(a)) => a.clone(), + Some(_) => return None, + }; + let (mut fields_left, mut entries_left, mut names_left) = (MAX_FIELDS, MAX_ENTRIES, MAX_NAME_BYTES); + let mut seen: HashSet = HashSet::new(); + let mut stack: Vec<(Object, String, Option, usize)> = Vec::new(); + if top.len() > MAX_ENTRIES { + return None; + } + entries_left -= top.len(); + for f in top.into_iter().rev() { + stack.push((f, String::new(), None, 0)); + } + while let Some((o, prefix, parent, depth)) = stack.pop() { + if depth > MAX_FIELD_DEPTH { + return None; + } + if let Some(r) = o.as_ref() + && !seen.insert(r) + { + continue; + } + let Some(d) = doc.resolve(&o).as_dict().cloned() else { continue }; + fields_left = fields_left.checked_sub(1)?; + let name = match (text(doc, &d, b"T"), prefix.is_empty()) { + (Some(p), true) => p, + (Some(p), false) => format!("{prefix}.{p}"), + (None, _) => prefix, + }; + if name.len() > MAX_FIELD_NAME_BYTES { + return None; + } + names_left = names_left.checked_sub(name.len())?; + let node = form.nodes.len(); + let kids = d.get(b"Kids").map(|k| doc.resolve(k)); + let kids: Vec = kids.as_deref().and_then(Object::as_array).cloned().unwrap_or_default(); + entries_left = entries_left.checked_sub(kids.len())?; + form.nodes.push(Node { dict: d, parent }); + let mut widgets = Vec::new(); + let mut sub = Vec::new(); + for k in kids { + let kd = doc.resolve(&k); + let Some(kd) = kd.as_dict() else { continue }; + // Kids with a /T are fields, and so are those with kids of their own; the others are + // this field's widgets. + if kd.contains(b"T") || kd.contains(b"Kids") { + sub.push(k); + } else { + widgets.push(kd.clone()); + } + } + for k in sub.into_iter().rev() { + stack.push((k, name.clone(), Some(node), depth + 1)); + } + form.fields.entry(name).or_default().push(Entry { node, widgets }); + } + Some(form) +} + +/// Entries a field's own dictionary is compared without: the tree's links, which change when a +/// field is added beside it or a widget's page gains an annotation, and say nothing of the field. +const FIELD_LINKS: &[&[u8]] = &[b"Kids", b"Parent", b"P"]; + +/// Compares objects of the signed revision with those of the document now, resolving references +/// in each, within [`MAX_COMPARED`] objects. +struct Same<'a> { + old: &'a Document, + doc: &'a Document, + left: usize, + /// Pairs of references being compared or found the same, so a cycle ends. + assumed: HashSet<(ObjRef, ObjRef)>, +} + +impl Same<'_> { + /// Whether field `was` of the signed revision's form `before` is unchanged as `is` in `now`: + /// its dictionary and each above it, and its widgets. `None` when the comparison ran past its cap. + fn field(&mut self, before: &Form, was: &Entry, now: &Form, is: &Entry) -> Option { + let (mut a, mut b) = (Some(was.node), Some(is.node)); + loop { + match (a.and_then(|i| before.nodes.get(i)), b.and_then(|i| now.nodes.get(i))) { + (None, None) => break, + (Some(x), Some(y)) => { + if !self.dicts(&x.dict, &y.dict, FIELD_LINKS, 0)? { + return Some(false); + } + (a, b) = (x.parent, y.parent); + } + _ => return Some(false), + } + } + if was.widgets.len() != is.widgets.len() { + return Some(false); + } + for (x, y) in was.widgets.iter().zip(&is.widgets) { + if !self.dicts(x, y, FIELD_LINKS, 0)? { + return Some(false); + } + } + Some(true) + } + + fn dicts(&mut self, a: &Dict, b: &Dict, skip: &[&[u8]], depth: usize) -> Option { + fn keys<'d>(d: &'d Dict, skip: &[&[u8]]) -> Vec<&'d [u8]> { + let mut k: Vec<&[u8]> = d.iter().map(|(k, _)| k.as_slice()).filter(|k| !skip.contains(k)).collect(); + k.sort_unstable(); + k + } + if keys(a, skip) != keys(b, skip) { + return Some(false); + } + for (k, v) in a.iter().filter(|(k, _)| !skip.contains(&k.as_slice())) { + let Some(w) = b.get(k) else { return Some(false) }; + if !self.objects(v, w, depth + 1)? { + return Some(false); + } + } + Some(true) + } + + /// Object equality across the two revisions: references resolved in their own revision, + /// dictionaries regardless of key order, a string by its bytes, a number by its value, and + /// stream data byte for byte as stored. A page is compared by reference only, since every + /// annotation added to it rewrites it. + fn objects(&mut self, a: &Object, b: &Object, depth: usize) -> Option { + self.left = self.left.checked_sub(1)?; + if depth > MAX_FIELD_DEPTH { + return None; + } + match (a, b) { + (Object::Ref(x), Object::Ref(y)) => { + if !self.assumed.insert((*x, *y)) { + return Some(true); + } + let (was, is) = (self.old.get(*x), self.doc.get(*y)); + if x == y && was.as_dict().is_some_and(|d| matches!(d.name(b"Type"), Some(b"Page" | b"Pages"))) { + return Some(true); + } + self.objects(&was, &is, depth) + } + (Object::Ref(x), _) => { + let was = self.old.get(*x); + self.objects(&was, b, depth) + } + (_, Object::Ref(y)) => { + let is = self.doc.get(*y); + self.objects(a, &is, depth) + } + (Object::String(x), Object::String(y)) => Some(x.bytes == y.bytes), + (Object::Int(i), Object::Real(r)) | (Object::Real(r), Object::Int(i)) => Some(r.fract() == 0.0 && *r as i128 == i128::from(*i)), + (Object::Dict(x), Object::Dict(y)) => self.dicts(x, y, &[], depth), + (Object::Stream(x), Object::Stream(y)) => Some(x.raw == y.raw && self.dicts(&x.dict, &y.dict, &[], depth)?), + (Object::Array(x), Object::Array(y)) => { + if x.len() != y.len() { + return Some(false); + } + for (v, w) in x.iter().zip(y) { + if !self.objects(v, w, depth + 1)? { + return Some(false); + } + } + Some(true) + } + _ => Some(a == b), + } + } +} + +/// The names `rules` would lock among `names`, for the tests below. +#[cfg(test)] +fn locked_names<'a>(rules: &[Rule], names: &[&'a str]) -> Vec<&'a str> { + names.iter().copied().filter(|n| rules.iter().any(|r| r.locks(n))).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use pdfcraft_cos::PdfString; + + fn dict(entries: Vec<(&str, Object)>) -> Dict { + let mut d = Dict::new(); + for (k, v) in entries { + d.set(k.as_bytes().to_vec(), v); + } + d + } + + fn names(n: &[&str]) -> Object { + Object::Array(n.iter().map(|s| Object::String(PdfString::text(s))).collect()) + } + + fn sig_field(lock: Option) -> Field { + let mut d = dict(vec![("FT", Object::name("Sig")), ("T", Object::String(PdfString::text("Approval")))]); + if let Some(l) = lock { + d.set(b"Lock".to_vec(), l); + } + Field { name: "Approval".into(), r: None, dict: d, widgets: Vec::new() } + } + + fn field_mdp(action: &str, fields: &[&str]) -> Dict { + let params = dict(vec![("Type", Object::name("TransformParams")), ("Action", Object::name(action)), ("Fields", names(fields))]); + let reference = + dict(vec![("Type", Object::name("SigRef")), ("TransformMethod", Object::name("FieldMDP")), ("TransformParams", Object::Dict(params))]); + dict(vec![("Type", Object::name("Sig")), ("Reference", Object::Array(vec![Object::Dict(reference)]))]) + } + + const ALL_NAMES: &[&str] = &["amount", "note", "address", "address.city", "addressee"]; + + /// A FieldMDP reference in the signature value locks as a `/Lock` on its field does: the + /// signers that write only one of them are read either way. + #[test] + fn a_fieldmdp_reference_in_the_value_locks_fields() { + let doc = Document::new_empty(); + let rules = rules(&doc, &sig_field(None), &field_mdp("Include", &["amount"])).unwrap(); + assert_eq!(locked_names(&rules, ALL_NAMES), ["amount"]); + let rules = rules_of(&doc, None, &field_mdp("Exclude", &["note", "address"])); + assert_eq!(locked_names(&rules, ALL_NAMES), ["amount", "addressee"]); + let rules = rules_of(&doc, None, &field_mdp("All", &[])); + assert_eq!(locked_names(&rules, ALL_NAMES), ALL_NAMES); + } + + /// A lock's names cover the fields below them, never a field that merely starts the same. + #[test] + fn a_listed_name_covers_its_kids_only() { + let doc = Document::new_empty(); + let lock = dict(vec![("Type", Object::name("SigFieldLock")), ("Action", Object::name("Include")), ("Fields", names(&["address"]))]); + let rules = rules_of(&doc, Some(Object::Dict(lock)), &dict(vec![])); + assert_eq!(locked_names(&rules, ALL_NAMES), ["address", "address.city"]); + } + + /// A lock that is there but can't be read leaves the signature's locks unknown, never "none". + #[test] + fn an_unreadable_lock_is_not_no_lock() { + let doc = Document::new_empty(); + let odd = dict(vec![("Action", Object::name("Some"))]); + assert!(rules(&doc, &sig_field(Some(Object::Dict(odd))), &dict(vec![])).is_err()); + assert!(rules(&doc, &sig_field(Some(Object::Int(1))), &dict(vec![])).is_err()); + let bare = dict(vec![("TransformMethod", Object::name("FieldMDP"))]); + assert!(rules(&doc, &sig_field(None), &dict(vec![("Reference", Object::Array(vec![Object::Dict(bare)]))])).is_err()); + assert_eq!(locked_fields(&doc, &doc, &sig_field(Some(Object::Int(1))), &dict(vec![])), Locked::Unchecked); + // No lock at all, and a DocMDP reference, lock nothing. + let docmdp = dict(vec![("TransformMethod", Object::name("DocMDP"))]); + assert_eq!(rules(&doc, &sig_field(None), &dict(vec![("Reference", Object::Array(vec![Object::Dict(docmdp)]))])), Ok(Vec::new())); + } + + fn rules_of(doc: &Document, lock: Option, value: &Dict) -> Vec { + rules(doc, &sig_field(lock), value).unwrap() + } +} diff --git a/crates/sign/src/pdf/types.rs b/crates/sign/src/pdf/types.rs index 93883e7584..5691761d13 100644 --- a/crates/sign/src/pdf/types.rs +++ b/crates/sign/src/pdf/types.rs @@ -40,12 +40,16 @@ pub mod kind { pub const STRUCTURE: &str = "document structure"; pub const PAGES: &str = "pages added or removed"; pub const OTHER: &str = "other changes"; + /// A change to a field the signature locks (its field's `/Lock`, or a FieldMDP reference in its + /// value), whatever else the change would count as. + pub const LOCKED_FIELD: &str = "locked field"; /// Not a change but the reason there is nothing to compare: the signed revision itself could not /// be read, or does not hold the signature, so what came after it cannot be allowed. pub const UNREADABLE: &str = "the signed version could not be read"; /// Every word above, for an interface to translate. - pub const ALL: &[&str] = &[PAGE_CONTENT, FORM_FILL, COMMENTS, SIGNATURE, SECURITY_STORE, METADATA, LINKS, STRUCTURE, PAGES, OTHER, UNREADABLE]; + pub const ALL: &[&str] = + &[PAGE_CONTENT, FORM_FILL, COMMENTS, SIGNATURE, SECURITY_STORE, METADATA, LINKS, STRUCTURE, PAGES, OTHER, LOCKED_FIELD, UNREADABLE]; } /// Changes made after signing. diff --git a/crates/sign/src/pdf/validate.rs b/crates/sign/src/pdf/validate.rs index 52bf79351f..04099267a9 100644 --- a/crates/sign/src/pdf/validate.rs +++ b/crates/sign/src/pdf/validate.rs @@ -1,6 +1,7 @@ use super::changes::classify_changes; use super::listing::{DigestCache, list, nums, sig_fields, text}; -use super::types::{Detail, Fill, Modification, Status, TrustStore}; +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, }; @@ -265,6 +266,7 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu let revocation = check_dss_revocation(doc, signer.as_ref(), &at, info); 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) { Modification::None } else { @@ -274,15 +276,25 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu // came after it is judged as when the revision cannot be read: not permitted. let old = cache.revision(doc, bytes, covered); let signed = old.as_ref().and_then(|old| { - sig_fields(old) - .iter() - .filter_map(|f| f.signature(old)) - .find(|v| nums(old, v, b"ByteRange").is_some_and(|b| b.len() == 4 && b[2] + b[3] == covered as f64)) + sig_fields(old).into_iter().find_map(|f| { + let v = f.signature(old)?; + nums(old, &v, b"ByteRange").is_some_and(|b| b.len() == 4 && b[2] + b[3] == covered as f64).then_some((f, v)) + }) }); match (old, signed) { - (Some(old), Some(v)) => { + (Some(old), Some((field, v))) => { set_certification(&old, &v, info); - classify_changes(doc, Some(old), info.certify) + // The fields this signature locks, as the signed revision has them, against the + // document now (#6757). + locks = locked_fields(doc, &old, &field, &v); + match classify_changes(doc, Some(old), info.certify) { + Modification::Allowed(_) if locks == Locked::Changed => Modification::Disallowed(vec![kind::LOCKED_FIELD]), + Modification::Disallowed(mut kinds) if locks == Locked::Changed => { + kinds.push(kind::LOCKED_FIELD); + Modification::Disallowed(kinds) + } + m => m, + } } _ => classify_changes(doc, None, info.certify), } @@ -306,6 +318,18 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu problems = true; } } + // A lock that could not be read or compared proves nothing either way: the changes may touch + // a field it locks, so the signature is not Valid. + if locks == Locked::Unchecked && !problems { + info.details.push(Detail::of( + "The signature could not be checked ({}).", + Fill::Reason("the fields this signature locks could not all be compared with the signed version".into()), + )); + if !revoked { + info.status = Status::Unknown; + } + problems = true; + } if revocation == DssRevocation::Incomplete { if !problems { info.status = Status::Unknown; diff --git a/crates/sign/tests/it/field_locks.rs b/crates/sign/tests/it/field_locks.rs new file mode 100644 index 0000000000..481558b829 --- /dev/null +++ b/crates/sign/tests/it/field_locks.rs @@ -0,0 +1,185 @@ +//! Fields a signature locks (ISO 32000-2 §12.7.5.5 `/Lock`, §12.8.2.4 FieldMDP): a change made +//! after signing to a field the signature locks is not a permitted form fill (#6757). + +use std::sync::Arc; + +use pdfcraft_cos::{Document, ObjRef, Object, PdfString, SaveOptions, Stream, write_incremental}; +use pdfcraft_sign::{Modification, SignOptions, Status, TrustStore, kind, pkcs12, signatures}; + +fn data(name: &str) -> Vec { + std::fs::read(format!("{}/tests/data/{name}", env!("CARGO_MANIFEST_DIR"))).unwrap() +} + +fn open(b: &[u8]) -> Document { + Document::open(Arc::new(b.to_vec())).unwrap() +} + +/// A classic-xref PDF of `objs`, numbered from 1, with object 1 as the catalog. +fn write_pdf(objs: &[&str]) -> Vec { + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +const AMOUNT: u32 = 6; +const AMOUNT_AP: u32 = 7; +const NOTE: u32 = 8; +const CITY: u32 = 11; + +/// A form with signature field "Approval" (object 5) carrying `lock` as its `/Lock`, a text field +/// "amount" with an appearance, a text field "note", and a field "address" whose kid is +/// "address.city". +fn form(lock: &str) -> Vec { + write_pdf(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R 8 0 R 10 0 R] >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots [5 0 R 6 0 R 8 0 R 11 0 R] >>", + "<< >>", + &format!("<< /Type /Annot /Subtype /Widget /FT /Sig /T (Approval) /Rect [150 20 280 70] /P 3 0 R /F 4 {lock} >>"), + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (amount) /V (100) /Rect [20 200 120 220] /P 3 0 R /F 4 /AP << /N 7 0 R >> >>", + "<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Length 26 >>\nstream\nBT /Helv 10 Tf (100) Tj ET\nendstream", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (note) /V (hello) /Rect [20 170 120 190] /P 3 0 R /F 4 >>", + "<< >>", + "<< /FT /Tx /T (address) /Kids [11 0 R] >>", + "<< /Type /Annot /Subtype /Widget /T (city) /Parent 10 0 R /V (Leeds) /Rect [20 140 120 160] /P 3 0 R /F 4 >>", + ]) +} + +/// `form(lock)` signed in its "Approval" field as an approval signature, and the trust that +/// makes that signature Valid. +fn signed(lock: &str) -> (Vec, TrustStore) { + let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap(); + let opts = SignOptions { field: Some("Approval".into()), date: "D:20261002120000+01'00'".into(), ..SignOptions::default() }; + let bytes = pdfcraft_sign::sign(&open(&form(lock)), &id, &opts).unwrap(); + let mut trust = TrustStore::default(); + trust.certs.push(id.certificate.clone()); + (bytes, trust) +} + +fn approval(bytes: &[u8], trust: &TrustStore) -> pdfcraft_sign::SignatureInfo { + signatures(&open(bytes), bytes, trust).into_iter().find(|s| s.field == "Approval").unwrap() +} + +fn edit_after(signed: &[u8], f: impl FnOnce(&mut Document)) -> Vec { + let mut doc = open(signed); + f(&mut doc); + write_incremental(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap() +} + +fn r(num: u32) -> ObjRef { + ObjRef { num, generation: 0 } +} + +/// Fill text field `num` with `value`, as a form filler does. +fn fill(num: u32, value: &str) -> impl FnOnce(&mut Document) { + let value = value.to_owned(); + move |doc| doc.update_dict(r(num), |d| d.set(b"V".to_vec(), Object::String(PdfString::text(&value)))).unwrap() +} + +/// Repaint "amount" without touching its value. +fn repaint_amount(doc: &mut Document) { + let body = b"BT /Helv 10 Tf (999999) Tj ET".to_vec(); + let mut d = pdfcraft_cos::Dict::new(); + d.set(b"Type".to_vec(), Object::name("XObject")); + d.set(b"Subtype".to_vec(), Object::name("Form")); + d.set(b"BBox".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(100), Object::Int(20)])); + d.set(b"Length".to_vec(), Object::Int(body.len() as i64)); + doc.set(r(AMOUNT_AP), Object::Stream(Stream::from_raw(d, body))); +} + +fn assert_locked(s: &pdfcraft_sign::SignatureInfo, what: &str) { + assert_eq!(s.status, Status::Invalid, "{what}: {:?}", s.details); + assert!(matches!(&s.modification, Modification::Disallowed(k) if k.contains(&kind::LOCKED_FIELD)), "{what}: {:?}", s.modification); +} + +fn assert_fill_allowed(s: &pdfcraft_sign::SignatureInfo, what: &str) { + assert_eq!((s.status, s.modification.clone()), (Status::Valid, Modification::Allowed(vec![kind::FORM_FILL])), "{what}: {:?}", s.details); +} + +const INCLUDE_AMOUNT: &str = "/Lock << /Type /SigFieldLock /Action /Include /Fields [(amount)] >>"; + +#[test] +fn changing_a_field_the_signature_locks_invalidates_it() { + let (bytes, trust) = signed(INCLUDE_AMOUNT); + assert_eq!(approval(&bytes, &trust).status, Status::Valid); + assert_locked(&approval(&edit_after(&bytes, fill(AMOUNT, "999999")), &trust), "value and appearance"); + let both = edit_after(&bytes, |doc| { + fill(AMOUNT, "999999")(doc); + repaint_amount(doc); + }); + assert_locked(&approval(&both, &trust), "value and appearance"); + assert_locked(&approval(&edit_after(&bytes, repaint_amount), &trust), "appearance only"); + // A field the lock does not name is filled as before. + assert_fill_allowed(&approval(&edit_after(&bytes, fill(NOTE, "changed")), &trust), "unlocked note"); +} + +#[test] +fn without_a_lock_the_same_change_is_a_form_fill() { + let (bytes, trust) = signed(""); + assert_fill_allowed(&approval(&edit_after(&bytes, fill(AMOUNT, "999999")), &trust), "no lock"); +} + +#[test] +fn exclude_locks_every_field_it_does_not_name() { + let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /Exclude /Fields [(note)] >>"); + assert_locked(&approval(&edit_after(&bytes, fill(AMOUNT, "1")), &trust), "amount under Exclude [note]"); + assert_fill_allowed(&approval(&edit_after(&bytes, fill(NOTE, "changed")), &trust), "note under Exclude [note]"); +} + +#[test] +fn all_locks_every_field() { + let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /All >>"); + assert_locked(&approval(&edit_after(&bytes, fill(NOTE, "changed")), &trust), "note under All"); + assert_locked(&approval(&edit_after(&bytes, fill(CITY, "York")), &trust), "address.city under All"); +} + +/// A name in `/Fields` locks the fields below it too: "address" covers "address.city". +#[test] +fn a_locked_parent_locks_its_kids() { + let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /Include /Fields [(address)] >>"); + assert_locked(&approval(&edit_after(&bytes, fill(CITY, "York")), &trust), "address.city under Include [address]"); + assert_fill_allowed(&approval(&edit_after(&bytes, fill(AMOUNT, "1")), &trust), "amount under Include [address]"); +} + +/// Removing a locked field, or adding a second field under its name, changes it too. +#[test] +fn removing_or_shadowing_a_locked_field_changes_it() { + let (bytes, trust) = signed(INCLUDE_AMOUNT); + let removed = edit_after(&bytes, |doc| { + let root = doc.root().unwrap(); + doc.update_dict(root, |c| { + if let Some(Object::Dict(form)) = c.get_mut(b"AcroForm") { + form.set(b"Fields".to_vec(), Object::Array(vec![Object::Ref(r(5)), Object::Ref(r(NOTE)), Object::Ref(r(10))])); + } + }) + .unwrap(); + }); + assert_eq!(approval(&removed, &trust).status, Status::Invalid); + let shadowed = edit_after(&bytes, |doc| { + let mut d = pdfcraft_cos::Dict::new(); + d.set(b"FT".to_vec(), Object::name("Tx")); + d.set(b"T".to_vec(), Object::String(PdfString::text("amount"))); + d.set(b"V".to_vec(), Object::String(PdfString::text("999999"))); + let twin = doc.add(Object::Dict(d)); + let root = doc.root().unwrap(); + doc.update_dict(root, |c| { + if let Some(Object::Dict(form)) = c.get_mut(b"AcroForm") + && let Some(Object::Array(fields)) = form.get_mut(b"Fields") + { + fields.push(Object::Ref(twin)); + } + }) + .unwrap(); + }); + assert_eq!(approval(&shadowed, &trust).status, Status::Invalid); +} diff --git a/crates/sign/tests/it/main.rs b/crates/sign/tests/it/main.rs index bcd6334719..389e8bf1e1 100644 --- a/crates/sign/tests/it/main.rs +++ b/crates/sign/tests/it/main.rs @@ -6,6 +6,7 @@ mod chain; mod cms; mod crypto; mod encrypted_signing; +mod field_locks; mod pdf; mod revision_classification; mod signed_structure; diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 642268ef87..1cbf1412e4 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -6340,11 +6340,11 @@ title = "Field locks (FieldMDP)" area = "H" tier = "P1" milestone = "M9" -status = "planned" +status = "partial" commands = [] -tools = [] -evidence = [] -notes = "" +tools = ["sign_list"] +evidence = ["crates/sign/tests/it/field_locks.rs::changing_a_field_the_signature_locks_invalidates_it", "crates/sign/tests/it/field_locks.rs::exclude_locks_every_field_it_does_not_name", "crates/sign/src/pdf/locks.rs::a_fieldmdp_reference_in_the_value_locks_fields"] +notes = "validation reads a signed field's /Lock and the FieldMDP references in its value (All, Include, Exclude; a listed name covers the fields below it) from the signed revision; a later change to a locked field or its widgets makes the signature invalid (modification: locked field), and a lock that can't be read or compared leaves it unknown. Not yet: writing a lock when signing, refusing to fill a locked field, and the /Lock /P permissions" [[feature]] id = "sign.document-timestamp"