From 8e52c9c3c37e5e5b2e9a7b96d6001b8599739f19 Mon Sep 17 00:00:00 2001 From: Thorsten Hirsch Date: Wed, 14 Oct 2026 19:45:09 +0200 Subject: [PATCH 1/2] M9: opt-in trust lists (a file of CA certificates, such as the EU Trusted Lists) A signer can be trusted through a list of CA certificates the user loads from a file: `sign_trust {"eu_trusted_list": ""}`, DER one after the other or PEM. Refs #775, #87, #824: the PDF attached to #775, a CAdES signature under a qualified service that Acrobat validates, is Unknown without the list and Valid with it. - The list is off until loaded, nothing is embedded, and it is kept apart from the user's own trusted certificates (`TrustStore::lists`). The details name the list that vouched. Chains through it still need CA certificates all the way (#620) and the signer's own certificate is held to #749's purpose rules. - A list vouches for signers, never for a time-stamp authority: a CA trusted to issue signing certificates is not thereby a source of trusted time, so trusted time still comes from the user's own certificates. - A cut-short or damaged list is refused instead of loading as a smaller one, and PEM that starts with text beginning with a "0" (DER's first byte) is read as PEM, in `x509::load_certificates` too. - `sign_trust` reads and checks every argument before it changes anything and revalidates the open documents once (`Session::update_trust`); the list path stays inside `--root` and the read is bounded. - `build_chain` takes its pool as an iterator, so a list's certificates are not copied for every signature. `TrustStore` gains `lists`: struct literals need `..TrustStore::default()`. Tests that fail without their change: the damaged-list and PEM cases (`trust.rs`), a list that holds a time-stamp authority's certificate not making its time trusted (`chain.rs`, with the shape of #775), and a bad `sign_trust` argument changing nothing (`automation.rs`). Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/signing.rs | 44 +++++++- crates/automation/src/tools.rs | 4 +- crates/automation/tests/it/automation.rs | 53 ++++++++++ crates/engine/src/session.rs | 6 +- crates/engine/src/session/save.rs | 37 ++++++- crates/engine/src/tests.rs | 22 ++++ crates/sign/README.md | 9 ++ crates/sign/src/lib.rs | 5 +- crates/sign/src/pdf.rs | 2 +- crates/sign/src/pdf/types.rs | 42 +++++++- crates/sign/src/pdf/validate.rs | 12 ++- crates/sign/src/trust.rs | 125 +++++++++++++++++++++++ crates/sign/src/x509.rs | 18 +++- crates/sign/tests/it/chain.rs | 101 +++++++++++++++++- crates/sign/tests/it/pdf.rs | 72 +++++++------ parity/acrobat-features.toml | 8 +- 16 files changed, 496 insertions(+), 64 deletions(-) create mode 100644 crates/sign/src/trust.rs diff --git a/crates/automation/src/signing.rs b/crates/automation/src/signing.rs index f2b583c070..40fabc1e71 100644 --- a/crates/automation/src/signing.rs +++ b/crates/automation/src/signing.rs @@ -2,6 +2,8 @@ //! document, and manage trusted certificates. Rectangles are points from the top-left of the //! displayed page. +use std::io::Read; + use pdfcraft_engine::js::SignEvent; use pdfcraft_engine::sign::{self, Certificate, DigitalId, Modification, Name, PrivateKey}; use pdfcraft_engine::{SignOptions, SignatureInfo, SignatureStatus}; @@ -9,6 +11,9 @@ use serde_json::{Value, json}; use crate::{Args, Automation, Result, ToolError, failed, write_atomic}; +/// The name the EU Trusted List file is loaded under (`sign_trust eu_trusted_list`). +const EU_LIST: &str = "EU Trusted List"; + fn bad(m: impl Into) -> ToolError { ToolError::InvalidArgs(m.into()) } @@ -377,8 +382,10 @@ impl Automation { } pub(crate) fn sign_trust(&mut self, a: &Args) -> Result { - let mut certs: Vec = - if a.opt_bool("clear")?.unwrap_or(false) { Vec::new() } else { self.session.trusted_certificates().to_vec() }; + // Every argument is read and checked first, so a bad one changes nothing, and the changes + // are applied together: the open documents are revalidated once, not once per change. + let clear = a.opt_bool("clear")?.unwrap_or(false); + let mut certs: Vec = if clear { Vec::new() } else { self.session.trusted_certificates().to_vec() }; // Which certificates are already in, by their bytes: a set, so a bundle of many distinct // certificates isn't compared against every one before it. let mut known: std::collections::HashSet> = certs.iter().map(|c| c.raw.clone()).collect(); @@ -391,6 +398,7 @@ impl Automation { .map(|p| p.as_str().map(str::to_string).ok_or_else(|| bad("paths must be strings"))) .collect::>()?, }; + let certs_changed = clear || !paths.is_empty(); for p in paths { let path = self.resolve(&p, false)?; let bytes = crate::read_input(&path)?; @@ -407,7 +415,35 @@ impl Automation { } } } - self.session.set_trusted_certificates(certs); - Ok(json!({ "trusted": self.session.trusted_certificates().iter().map(cert_json).collect::>() })) + // The trust list, off until asked for. `None`: not mentioned, left alone. + let eu_list = match a.get("eu_trusted_list") { + None => None, + Some(Value::Bool(false) | Value::Null) => Some(None), + Some(Value::String(p)) => { + let path = self.resolve(p, false)?; + // One byte more than allowed is read, so an oversize file (or one that grows, or a + // device) is refused by `from_bytes` instead of being read whole. + let mut bytes = Vec::new(); + std::fs::File::open(&path) + .and_then(|f| f.take(sign::trust::MAX_LIST_BYTES as u64 + 1).read_to_end(&mut bytes)) + .map_err(|e| failed(format!("{}: {e}", path.display())))?; + Some(Some(sign::trust::TrustList::from_bytes(EU_LIST, &bytes).map_err(failed)?)) + } + Some(_) => return Err(bad("eu_trusted_list must be the path of a trust list file, or false")), + }; + if certs_changed || eu_list.is_some() { + self.session.update_trust(|trust| { + if certs_changed { + trust.certs = certs; + } + if let Some(list) = eu_list { + trust.set_list(EU_LIST, list); + } + }); + } + Ok(json!({ + "trusted": self.session.trusted_certificates().iter().map(cert_json).collect::>(), + "trust_lists": self.session.trust_lists().iter().map(|l| json!({ "name": l.name, "certificates": l.certs.len() })).collect::>(), + })) } } diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index b9da1dbed5..36c4e98884 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1086,8 +1086,8 @@ pub fn tools() -> Vec { }), &["doc", "id", "out"], )), - t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). Every open document is revalidated. Returns the trusted list.").with(schema( - json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" } }), + t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). `eu_trusted_list` loads a trust list kept apart from them, off until asked for: the path of a file of CA certificates (DER one after the other, or PEM; the EU Trusted Lists' qualified CAs, say), whose CAs may vouch for signers but never for a time-stamp authority; false removes it. The changes of one call are applied together, or not at all if an argument is bad, and every open document is revalidated once. Returns the trusted list and the loaded trust lists.").with(schema( + json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" }, "eu_trusted_list": { "type": ["string", "boolean"] } }), &[], )), t("comment_mark", "Mark a comment with a checkmark", "Mark or unmark a comment with a checkmark (Acrobat: Mark with checkmark), recorded as a private reply. Undoable.").with(schema( diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index f1ccd7ea73..50a92f822b 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -8899,6 +8899,59 @@ fn optimizing_discards_an_embedded_search_index_through_tools() { assert_eq!(piece_info("small.pdf"), ["Illustrator"]); } +#[test] +fn a_trust_list_is_off_until_loaded_through_sign_trust() { + let dir = workdir("trust_list"); + let mut a = auto(&dir); + ok(&mut a, "sign_id_create", json!({ "name": "Ada Lovelace", "country": "GB", "key": "p256", "password": "secret12", "path": "ada.p12" })); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "sign_document", json!({ "doc": doc, "id": "ada.p12", "password": "secret12", "out": "signed.pdf" })); + let status = |a: &mut Automation| ok(a, "sign_list", json!({ "doc": doc }))["signatures"][0]["status"].as_str().unwrap().to_string(); + assert_eq!(status(&mut a), "unknown", "nothing trusted by default"); + + // Default: no list. + let t = ok(&mut a, "sign_trust", json!({})); + assert_eq!(t["trust_lists"].as_array().map(Vec::len), Some(0)); + + // A trust list file (the certificate as DER), loaded by path. + let ada = pdfcraft_engine::sign::pkcs12::open(&std::fs::read(dir.join("ada.p12")).unwrap(), "secret12").unwrap(); + std::fs::write(dir.join("list.der"), &ada.certificate.raw).unwrap(); + let t = ok(&mut a, "sign_trust", json!({ "eu_trusted_list": "list.der" })); + assert_eq!(t["trust_lists"][0]["name"], "EU Trusted List"); + assert_eq!(t["trust_lists"][0]["certificates"], 1); + assert_eq!(t["trusted"].as_array().unwrap().len(), 0, "the list is kept apart from the user's certificates"); + assert_eq!(status(&mut a), "valid"); + // Bad input is refused and leaves the list as it was. + std::fs::write(dir.join("junk.der"), b"not certificates").unwrap(); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "junk.der" })), Err(ToolError::Failed(_)))); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "missing.der" })), Err(ToolError::Failed(_)))); + // A file over the size limit (sparse, so cheap) is refused without being read whole. + let big = std::fs::File::create(dir.join("big.der")).unwrap(); + big.set_len(pdfcraft_engine::sign::trust::MAX_LIST_BYTES as u64 + 1).unwrap(); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "big.der" })), Err(ToolError::Failed(_)))); + assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": 5 })), Err(ToolError::InvalidArgs(_)))); + assert!(a.call("sign_trust", &json!({ "eu_trusted_list": "../outside.der" })).is_err(), "paths stay inside the root"); + assert_eq!(status(&mut a), "valid"); + // Removing it makes the signer unknown again. + assert_eq!(ok(&mut a, "sign_trust", json!({ "eu_trusted_list": false }))["trust_lists"].as_array().map(Vec::len), Some(0)); + assert_eq!(status(&mut a), "unknown"); + + // One call can change everything at once (and revalidates once). + let t = ok(&mut a, "sign_trust", json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "list.der" })); + assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(1), Some(1))); + // A bad argument changes nothing, not even what came before it in the same call. + ok(&mut a, "sign_trust", json!({ "clear": true, "eu_trusted_list": false })); + for bad in [ + json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "junk.der" }), + json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": 5 }), + ] { + assert!(a.call("sign_trust", &bad).is_err(), "{bad}"); + let t = ok(&mut a, "sign_trust", json!({})); + assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(0), Some(0)), "{bad}"); + } + assert_eq!(status(&mut a), "unknown"); +} + #[test] fn optimizing_through_tools() { let dir = workdir("optimize"); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 8b084c728b..0b175891d6 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -35,10 +35,14 @@ pub struct Session { /// injected time AS local time and zeroes the zone, so injecting only it leaves either the /// local dates or the UTC ones wrong by the zone's offset. utc_offset: Option i64>, - /// Certificates trusted for signing (Acrobat: Trusted Certificates). + /// What is trusted for signing: the user's certificates (Acrobat: Trusted Certificates) and the + /// trust lists they loaded. pub(crate) trust: Arc, /// The words signature status layers are drawn with, in the interface language. pub(crate) captions: Arc, + /// How often every open document's signatures were validated again after a trust change. + #[cfg(test)] + pub(crate) revalidations: usize, /// Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript, inverted (on by default). pub(crate) js_off: bool, /// Preferences ▸ Date format, when not the default (see [`dates`]). diff --git a/crates/engine/src/session/save.rs b/crates/engine/src/session/save.rs index a8770bc007..1de07acc6b 100644 --- a/crates/engine/src/session/save.rs +++ b/crates/engine/src/session/save.rs @@ -252,11 +252,40 @@ impl Session { &self.trust.certs } - /// Replace the trusted certificates, revalidate every open document's signatures, - /// and rebuild its display copy and renderer to match (working file untouched, - /// generation/dirty unchanged: trust alone is not an edit). + /// Change the trust store, revalidate every open document's signatures, and rebuild its + /// display copy and renderer to match (working file untouched, generation/dirty unchanged: + /// trust alone is not an edit). This happens once, however many changes `change` makes: + /// revalidating runs chain building and signature verification for every signature, against + /// every certificate of every trust list. + pub fn update_trust(&mut self, change: impl FnOnce(&mut TrustStore)) { + let mut trust = (*self.trust).clone(); + change(&mut trust); + self.trust = Arc::new(trust); + self.revalidate_signatures(); + } + + /// Replace the trusted certificates (see [`Session::update_trust`]). pub fn set_trusted_certificates(&mut self, certs: Vec) { - self.trust = Arc::new(TrustStore { certs }); + self.update_trust(|trust| trust.certs = certs); + } + + /// The trust lists the user loaded (e.g. the EU Trusted Lists' qualified CAs), none by default. + /// They are not part of [`Session::trusted_certificates`]. + pub fn trust_lists(&self) -> &[pdfcraft_sign::trust::TrustList] { + &self.trust.lists + } + + /// Load `list` (replacing a list of the same name), or with `None` remove the list called + /// `name`, and revalidate every open document. + pub fn set_trust_list(&mut self, name: &str, list: Option) { + self.update_trust(|trust| trust.set_list(name, list)); + } + + fn revalidate_signatures(&mut self) { + #[cfg(test)] + { + self.revalidations += 1; + } for doc in &mut self.docs { Self::revalidate(doc, self.trust.clone()); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 13696f531b..b7098e86a5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5798,6 +5798,28 @@ fn reading_colors_set_and_invalidated() { assert!(!s.set_reading_colors(DocId(u64::MAX), ReadingColors::WHITE_ON_BLACK)); } +#[test] +fn several_trust_changes_revalidate_the_open_documents_once() { + let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); + let cert = sign::pkcs12::open(&p12, "test").unwrap().certificate; + let mut s = Session::default(); + // Each setter changes one thing and revalidates. + s.set_trusted_certificates(vec![cert.clone()]); + s.set_trusted_certificates(Vec::new()); + assert_eq!(s.revalidations, 2); + // One `update_trust` changes any number of things and revalidates once. + let list = sign::trust::TrustList::from_bytes("Test list", &cert.raw).unwrap(); + s.update_trust(|trust| { + trust.certs = vec![cert.clone()]; + trust.set_list("Test list", Some(list)); + }); + assert_eq!(s.revalidations, 3); + assert_eq!((s.trusted_certificates().len(), s.trust_lists().len()), (1, 1)); + // Replacing a list by name, and removing it. + s.set_trust_list("Test list", None); + assert!(s.trust_lists().is_empty()); +} + #[test] fn signing_saving_trusting_and_commenting_afterwards() { let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap(); diff --git a/crates/sign/README.md b/crates/sign/README.md index a5289cbe30..c41d66eaf0 100644 --- a/crates/sign/README.md +++ b/crates/sign/README.md @@ -114,6 +114,15 @@ needs a prompt to open is listed and asks at signing (issue #179). - **Weak algorithms still validate, and say so.** SHA-1 and RIPEMD-160 signatures are common in documents signed years ago, so they validate (new signatures never use SHA-1), but the signature's details say that the algorithm is weak and shouldn't be relied on. +- **Trust is the user's decision.** Only the user's own list (`TrustStore::certs`) is trusted by + default. A trust list the user loads from a file (`sign_trust eu_trusted_list`, the EU Trusted + Lists' qualified CAs, say) is kept apart from it (`TrustStore::lists`), off until loaded, and + named in the details when it vouches. Nothing of the kind is embedded. A list vouches for + signers, never for a time-stamp authority: trusted time comes from the user's own certificates. +- **Not Adobe's list.** Adobe's AATL is not used: Adobe-authored data outside the closed list in + AGENTS.md §1.1 needs the owner's explicit approval, and the EU Trusted Lists (and, planned, the + operating system's store) cover the same ground. A signer that chains only to an AATL root stays + "unknown" until the user trusts that root. - **Validation algorithms:** digests SHA-1, SHA-224/256/384/512, SHA-512/224, SHA-512/256, SHA3-224/256/384/512 and RIPEMD-160. RSA PKCS #1 v1.5 and RSASSA-PSS (the hash, MGF1 hash and salt length the signature declares), ECDSA on P-256, P-384, P-521, brainpoolP256r1, P384r1 and diff --git a/crates/sign/src/lib.rs b/crates/sign/src/lib.rs index a34c1f2f1c..94e3e1d259 100644 --- a/crates/sign/src/lib.rs +++ b/crates/sign/src/lib.rs @@ -21,6 +21,7 @@ pub mod pkcs12; pub mod revocation; pub mod status_layers; pub mod timestamp; +pub mod trust; #[cfg(target_os = "windows")] pub mod windows; pub mod x509; @@ -29,8 +30,8 @@ pub use der::Time; pub use graphic::Graphic; pub use keys::{DigestAlg, PrivateKey, PublicKey}; pub use pdf::{ - Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustStore, WORDINGS, Words, - has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate, + Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustSource, TrustStore, WORDINGS, + Words, has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate, }; pub use pkcs12::DigitalId; pub use status_layers::{StatusCaptions, has_status_layers, show_status_layers, status_rgb}; diff --git a/crates/sign/src/pdf.rs b/crates/sign/src/pdf.rs index a491f15054..8e5206198b 100644 --- a/crates/sign/src/pdf.rs +++ b/crates/sign/src/pdf.rs @@ -40,7 +40,7 @@ pub use listing::{DigestCache, list, list_cached}; pub(crate) use listing::{walk_sig_fields, widget_shown}; pub(crate) use signing::fmt; pub use signing::{Appearance, AppearanceLabels, SignOptions, display_date, has_signatures, sign, sign_with_timestamp, timestamp_document}; -pub use types::{Detail, Fill, Modification, Status, TrustStore, WORDINGS, Words, in_english, kind}; +pub use types::{Detail, Fill, Modification, Status, TrustSource, TrustStore, WORDINGS, Words, in_english, kind}; pub(crate) use validate::signature_contents; pub use validate::validate; #[cfg(test)] diff --git a/crates/sign/src/pdf/types.rs b/crates/sign/src/pdf/types.rs index 5691761d13..5ee8a0210c 100644 --- a/crates/sign/src/pdf/types.rs +++ b/crates/sign/src/pdf/types.rs @@ -1,12 +1,46 @@ use super::Certificate; -/// Certificates the user trusts for signing (Acrobat: Trusted Certificates). +/// Certificates trusted for signing (Acrobat: Trusted Certificates). Only `certs`, the user's own +/// list, is trusted by default; a trust list has to be loaded. #[derive(Clone, Debug, Default)] pub struct TrustStore { pub certs: Vec, + /// Lists of CA certificates the user loaded (e.g. the EU Trusted Lists' qualified CAs). They + /// vouch for signers, never for a time-stamp authority: trusted time comes from `certs` alone. + pub lists: Vec, +} + +/// Why a certificate in a chain is trusted. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TrustSource { + /// The user's own list of trusted certificates. + User, + /// The named list the user loaded. + List(String), } impl TrustStore { + /// Load `list`, replacing a list of the same name, or with `None` remove the list `name`. + pub fn set_list(&mut self, name: &str, list: Option) { + self.lists.retain(|l| l.name != name); + self.lists.extend(list); + } + + /// Every certificate that can anchor a signer's chain: the user's, then the loaded lists'. + pub(super) fn anchors(&self) -> impl Iterator + Clone { + self.certs.iter().chain(self.lists.iter().flat_map(|l| l.certs.iter())) + } + + /// What makes `c` trusted to vouch for a signer, if anything. The user's own list wins. + pub fn source_of(&self, c: &Certificate) -> Option { + if self.trusts(c) { + Some(TrustSource::User) + } else { + self.lists.iter().find(|l| l.certs.iter().any(|t| t.raw == c.raw)).map(|l| TrustSource::List(l.name.clone())) + } + } + + /// Whether the user's own list holds `c`. Only that vouches for a time-stamp authority. pub(super) fn trusts(&self, c: &Certificate) -> bool { self.certs.iter().any(|t| t.raw == c.raw) } @@ -92,8 +126,9 @@ pub enum Fill { /// A value out of the signature itself — a time, the evidence a revocation came from — written /// as it stands, the way a certificate's name or date is. Value(String), - /// Two certificates' own names, for the wording that says one was not used to vouch for the - /// other. They go in the order the wording puts its two holes in, which a language may reverse. + /// Two names, for the wording with two holes: that one certificate was not used to vouch for + /// another, or which trust list vouched through which certificate. They go in the order the + /// wording puts its two holes in, which a language may reverse. Names(String, String), } @@ -199,6 +234,7 @@ pub const WORDINGS: &[&str] = &[ "The certificate of {} was not valid at the time of signing, so it is not used to vouch for {}.", "The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted certificates.", "The signer's identity is valid.", + "Its certificate chains to {} in the trust list “{}”.", "The signature includes an embedded timestamp.", "Signing time is from the clock on the signer's computer.", // What the signature's own timestamp token proves, if it carries one. diff --git a/crates/sign/src/pdf/validate.rs b/crates/sign/src/pdf/validate.rs index 32874b81c8..148580294c 100644 --- a/crates/sign/src/pdf/validate.rs +++ b/crates/sign/src/pdf/validate.rs @@ -337,13 +337,13 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu 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(); - pool.extend(trust.certs.iter().cloned()); // The time the chain is judged at: trusted timestamp, else the signer's claimed time. let at = info.timestamp_time.or(info.signing_time); - let (chain, refused) = build_chain_noted(&cert, &pool, at); + let (chain, refused) = build_chain_noted(&cert, embedded.iter().chain(trust.anchors()), at); let chain: Vec = chain.into_iter().cloned().collect(); - let trusted = chain.iter().any(|c| trust.trusts(c)); + // The first trusted certificate going up the chain, and what makes it trusted. + let anchor = chain.iter().find_map(|c| trust.source_of(c).map(|s| (c.display_name(), s))); + let trusted = anchor.is_some(); info.chain = chain; info.certificate = Some(cert.clone()); if let Some(why) = refused @@ -474,6 +474,10 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu } } else { info.details.push(Detail::plain("The signer's identity is valid.")); + // Which list vouched, when one did: the user's own list is the plain case and says nothing. + if let Some((root, TrustSource::List(list))) = anchor { + info.details.push(Detail::of("Its certificate chains to {} in the trust list “{}”.", Fill::Names(root, list))); + } if !problems && !revoked { info.status = Status::Valid; } diff --git a/crates/sign/src/trust.rs b/crates/sign/src/trust.rs new file mode 100644 index 0000000000..48661f2dde --- /dev/null +++ b/crates/sign/src/trust.rs @@ -0,0 +1,125 @@ +//! Trust lists: sets of CA certificates the user loads from a file, kept apart from the +//! certificates they trust themselves. +//! +//! Nothing here is trusted unless the user loads it (`TrustStore::lists`): which authorities a PDF +//! reader vouches for is the user's decision, not ours, so no list is embedded in PdfCraft. The +//! first intended source is the EU Trusted Lists' qualified CA services. Chain building +//! ([`crate::x509::build_chain`]) still applies to a list: a certificate in it only vouches for what +//! a chain of CA certificates under it leads to. +//! +//! A list vouches for signers. It never vouches for a time-stamp authority: a CA that is trusted +//! to issue signing certificates is not thereby a source of trusted time, so trusted time still +//! comes only from the user's own certificates. +//! +//! Adobe's AATL is not used in any form: Adobe-authored data outside the closed list in AGENTS.md §1.1 +//! needs the owner's explicit approval, and the EU Trusted Lists cover the same ground. + +use std::sync::Arc; + +use crate::SignError; +use crate::der::Tlv; +use crate::x509::Certificate; + +/// Certificates as DER one after the other. A certificate that doesn't parse (a key type PdfCraft +/// doesn't read, say) is skipped. Bytes that aren't a DER element at all, as in a file cut short, +/// are an error, so a damaged list doesn't load as a smaller one without a word. +fn parse_concatenated(mut rest: &[u8]) -> Result, SignError> { + let mut out = Vec::new(); + while !rest.iter().all(u8::is_ascii_whitespace) { + let Ok((t, r)) = Tlv::parse(rest) else { + return Err(SignError::Malformed(format!("the trust list is damaged after {} certificates ({} bytes left)", out.len(), rest.len()))); + }; + if let Ok(c) = Certificate::parse(t.raw) { + out.push(c); + } + rest = r; + } + Ok(out) +} + +/// The most a list file may hold: far above the roughly 1.5 MB of the EU qualified CAs. +pub const MAX_LIST_BYTES: usize = 32 << 20; + +/// A named set of trusted CA certificates the user loaded from a file, e.g. "EU Trusted List". +#[derive(Clone, Debug)] +pub struct TrustList { + pub name: String, + pub certs: Arc>, +} + +impl TrustList { + /// A list from a file's bytes: certificates as DER one after the other, or a PEM bundle. + /// Certificates that don't parse are skipped; a file with none, a damaged one, or one over + /// [`MAX_LIST_BYTES`], is an error. + pub fn from_bytes(name: &str, bytes: &[u8]) -> Result { + if bytes.len() > MAX_LIST_BYTES { + return Err(SignError::Malformed(format!("trust list over {} MiB", MAX_LIST_BYTES >> 20))); + } + let mut certs = if bytes.first() == Some(&0x30) && !crate::x509::is_pem(bytes) { + parse_concatenated(bytes)? + } else { + crate::x509::load_certificates(bytes)? + }; + let mut seen = std::collections::HashSet::new(); + certs.retain(|c| seen.insert(c.raw.clone())); + if certs.is_empty() { + return Err(SignError::Malformed("no certificates in the trust list".into())); + } + Ok(TrustList { name: name.to_string(), certs: Arc::new(certs) }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A few self-made certificates to load: the lists are tested without any real CA's data. + fn certificates(n: usize) -> Vec> { + (0..n) + .map(|i| { + let key = crate::PrivateKey::generate_p256().unwrap(); + let name = crate::x509::Name::build(&format!("List Test {i}"), "", "Trust Tests", "", "US"); + let alg = key.preferred_digest(); + let sig_alg = key.signature_algorithm(alg); + let tbs = crate::der::seq(&[ + &crate::der::uint(&[1 + i as u8]), + &sig_alg, + &name.raw, + &crate::der::seq(&[ + &crate::der::Time { year: 2020, month: 1, day: 1, hour: 0, minute: 0, second: 0 }.encode(), + &crate::der::Time { year: 2040, month: 1, day: 1, hour: 0, minute: 0, second: 0 }.encode(), + ]), + &name.raw, + &key.public_key().spki(), + ]); + let signature = key.sign(alg, &tbs).unwrap(); + crate::der::seq(&[&tbs, &sig_alg, &crate::der::bit_string(&signature)]) + }) + .collect() + } + + #[test] + fn a_list_reads_concatenated_der_and_rejects_garbage() { + let certs = certificates(3); + let file = certs.concat(); + let list = TrustList::from_bytes("Test list", &file).unwrap(); + assert_eq!((list.name.as_str(), list.certs.len()), ("Test list", 3)); + // The same as a PEM bundle. + let pem: String = list.certs.iter().map(crate::x509::to_pem).collect(); + assert_eq!(TrustList::from_bytes("pem", pem.as_bytes()).unwrap().certs.len(), 3); + assert!(TrustList::from_bytes("none", b"not certificates").is_err()); + assert!(TrustList::from_bytes("none", &[]).is_err()); + assert!(TrustList::from_bytes("big", &vec![0x30; MAX_LIST_BYTES + 1]).is_err()); + // A file cut short is refused, not loaded as the certificates before the cut. + assert!(TrustList::from_bytes("cut", &file[..file.len() - 5]).is_err()); + // Whitespace after the last certificate is not damage. + let spaced = [file.as_slice(), b"\n"].concat(); + assert_eq!(TrustList::from_bytes("spaced", &spaced).unwrap().certs.len(), 3); + // PEM that follows a note starting with "0" (the first byte DER starts with) is still PEM. + let noted = format!("0 certificates have been revoked in this bundle\n{pem}"); + assert_eq!(TrustList::from_bytes("noted", noted.as_bytes()).unwrap().certs.len(), 3); + // A certificate listed twice, even apart, is one entry. + let repeated = [certs[0].clone(), certs[1].clone(), certs[0].clone()].concat(); + assert_eq!(TrustList::from_bytes("dups", &repeated).unwrap().certs.len(), 2); + } +} diff --git a/crates/sign/src/x509.rs b/crates/sign/src/x509.rs index 91f74ff214..e08dbe1966 100644 --- a/crates/sign/src/x509.rs +++ b/crates/sign/src/x509.rs @@ -569,7 +569,7 @@ pub fn subject_of(raw: &[u8]) -> Option { /// `pathLenConstraint` allows the CA certificates below it, and (when `at` is given) it was valid /// then. Stops at a self-signed certificate. Certificates embedded in a document are in `pool` /// too, so an ordinary end-entity certificate must never be accepted as an issuer. -pub fn build_chain<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at: Option