diff --git a/crates/automation/src/signing.rs b/crates/automation/src/signing.rs index f2b583c070..0f0c5c88d7 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,37 @@ 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; + } + match eu_list { + Some(Some(list)) => trust.add_list(list), + Some(None) => trust.remove_list(EU_LIST), + None => {} + } + }); + } + 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 a37afa49f9..f6f34edc32 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 de02a93496..28d9fb177a 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9025,6 +9025,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 e28f5b6a5a..7d3d343744 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -37,10 +37,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..a5253c4aef 100644 --- a/crates/engine/src/session/save.rs +++ b/crates/engine/src/session/save.rs @@ -252,11 +252,44 @@ 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) and revalidate every open document. + pub fn add_trust_list(&mut self, list: pdfcraft_sign::trust::TrustList) { + self.update_trust(|trust| trust.add_list(list)); + } + + /// Remove the trust list called `name` and revalidate every open document. + pub fn remove_trust_list(&mut self, name: &str) { + self.update_trust(|trust| trust.remove_list(name)); + } + + 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 702160f482..1251eda327 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5844,6 +5844,31 @@ 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.add_list(list.clone()); + }); + assert_eq!(s.revalidations, 3); + assert_eq!((s.trusted_certificates().len(), s.trust_lists().len()), (1, 1)); + // A list loaded again under its name replaces itself; removing it by that name takes it back. + s.add_trust_list(list); + assert_eq!(s.trust_lists().len(), 1); + s.remove_trust_list("Test list"); + assert!(s.trust_lists().is_empty()); + assert_eq!(s.revalidations, 5); +} + #[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..dbc65f2eb4 100644 --- a/crates/sign/src/pdf/types.rs +++ b/crates/sign/src/pdf/types.rs @@ -1,12 +1,52 @@ 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. A list is known by its own name, so + /// [`remove_list`](Self::remove_list) takes back exactly what was loaded. + pub fn add_list(&mut self, list: crate::trust::TrustList) { + self.remove_list(&list.name); + self.lists.push(list); + } + + /// Remove the list called `name`, if one is loaded. + pub fn remove_list(&mut self, name: &str) { + self.lists.retain(|l| l.name != name); + } + + /// 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 +132,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 +240,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..3ab5e275da 100644 --- a/crates/sign/src/pdf/validate.rs +++ b/crates/sign/src/pdf/validate.rs @@ -1,7 +1,7 @@ use super::changes::classify_changes; 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::types::{Detail, Fill, Modification, Status, TrustSource, TrustStore, kind}; use super::{ Certificate, Dict, DigestAlg, Document, HashSet, ObjRef, Object, SignError, SignatureInfo, SignedData, Time, build_chain, build_chain_noted, }; @@ -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..dee91f8b75 --- /dev/null +++ b/crates/sign/src/trust.rs @@ -0,0 +1,141 @@ +//! 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. +//! +//! An entry that is not a CA stays in the list (the national lists file a few OCSP responder and +//! time-stamp certificates under their CA services, so refusing them would refuse the real +//! lists). It can issue nothing in chain building and vouches only for itself, which the signer +//! checks of [`crate::x509::Certificate::signing_problem`] still judge. +//! +//! 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 PEM bundle cut short is refused too, wherever the cut falls: in the last block, or + // right after the last complete one. + let blocks: Vec = list.certs.iter().map(crate::x509::to_pem).collect(); + let cut_inside = format!("{}{}", blocks[0], &blocks[1][..blocks[1].len() / 2]); + assert!(TrustList::from_bytes("cut pem", cut_inside.as_bytes()).is_err()); + let cut_after = format!("{}{}-----BEGIN CERTIFICATE-----\n", blocks[0], blocks[1]); + assert!(TrustList::from_bytes("cut pem", cut_after.as_bytes()).is_err()); + // So is a block that begins before the one before it ended. + let head: String = blocks[0].lines().take(2).map(|l| format!("{l}\n")).collect(); + let spliced = format!("{head}{}", blocks[1]); + assert!(TrustList::from_bytes("spliced", spliced.as_bytes()).is_err()); + // 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..754bed7088 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