Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(sign): don't report valid when a DSS cap hides revocation evidence

aiongga887405ea15a
diff --git a/crates/sign/src/pdf.rs b/crates/sign/src/pdf.rs
index 04598e033..f4fe2c601 100644
--- a/crates/sign/src/pdf.rs
+++ b/crates/sign/src/pdf.rs
@@ -892,7 +892,8 @@ fn finish_validation(
// Revocation evidence embedded in the document security store, if any. A verified
// revocation is final: later blocks must not soften the verdict.
let signer = info.chain.first().cloned();
- let revoked = check_dss_revocation(doc, signer.as_ref(), &at, info);
+ let revocation = check_dss_revocation(doc, signer.as_ref(), &at, info);
+ let revoked = revocation == DssRevocation::Revoked;
// Changes after signing.
info.modification = if covered == bytes.len() || bytes[covered..].iter().all(|b| b.is_ascii_whitespace() || *b == 0) {
Modification::None
@@ -929,6 +930,12 @@ fn finish_validation(
problems = true;
}
}
+ if revocation == DssRevocation::Incomplete {
+ if !problems {
+ info.status = Status::Unknown;
+ }
+ problems = true;
+ }
if let Some(t) = info.timestamp_time.or(info.signing_time)
&& !cert.valid_at(t)
{
@@ -975,46 +982,86 @@ fn finish_validation(
}
}
-/// Evidence streams read from one `/DSS` array.
+/// Distinct evidence streams read from one `/DSS` array.
const MAX_DSS_ENTRIES: usize = 1024;
/// Decoded bytes read from one `/DSS` array; real CRLs and OCSP responses are kilobytes each.
const MAX_DSS_BYTES: usize = 64 << 20;
/// The decoded streams of the `/DSS` evidence array `key` (`/CRLs`, `/OCSPs`), one at a time so
/// each is checked before the next decodes: each stream once and within the evidence size cap,
-/// at most [`MAX_DSS_ENTRIES`] of them and [`MAX_DSS_BYTES`] together.
-fn dss_evidence<'a>(doc: &'a Document, dss: &Dict, key: &[u8]) -> impl Iterator<Item = Vec<u8>> + 'a {
- let items = dss.get(key).map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
- let mut items = items.into_iter().take(MAX_DSS_ENTRIES);
- let mut seen = HashSet::new();
- let mut left = MAX_DSS_BYTES;
- std::iter::from_fn(move || {
- for item in items.by_ref() {
- if left == 0 {
- return None;
- }
- if item.as_ref().is_some_and(|r| !seen.insert(r)) {
+/// at most [`MAX_DSS_ENTRIES`] distinct ones and [`MAX_DSS_BYTES`] together. A stream past a cap
+/// sets [`DssEvidence::cut`] and ends the iteration.
+struct DssEvidence<'a> {
+ doc: &'a Document,
+ items: std::vec::IntoIter<Object>,
+ seen: HashSet<ObjRef>,
+ taken: usize,
+ left: usize,
+ /// A cap stopped the array being read in full.
+ cut: bool,
+}
+
+impl<'a> DssEvidence<'a> {
+ fn new(doc: &'a Document, dss: &Dict, key: &[u8]) -> Self {
+ let items = dss.get(key).map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
+ DssEvidence { doc, items: items.into_iter(), seen: HashSet::new(), taken: 0, left: MAX_DSS_BYTES, cut: false }
+ }
+}
+
+impl Iterator for DssEvidence<'_> {
+ type Item = Vec<u8>;
+
+ fn next(&mut self) -> Option<Vec<u8>> {
+ if self.cut {
+ return None;
+ }
+ // Repeats are skipped before the caps count anything, so repeating one stream cannot use
+ // them up; the scan of the array itself is bounded by the parser's cap on array length.
+ for item in self.items.by_ref() {
+ if item.as_ref().is_some_and(|r| !self.seen.insert(r)) {
continue;
}
- let o = doc.resolve(&item);
+ let o = self.doc.resolve(&item);
let Object::Stream(s) = o.as_ref() else { continue };
- let Ok(bytes) = s.decoded_within(crate::revocation::MAX_EVIDENCE.min(left)) else { continue };
- left = left.saturating_sub(bytes.len());
+ if self.taken >= MAX_DSS_ENTRIES {
+ self.cut = true;
+ return None;
+ }
+ self.taken += 1;
+ // A stream past the evidence cap would not parse as evidence either.
+ let Ok(bytes) = s.decoded_within(crate::revocation::MAX_EVIDENCE) else { continue };
+ let Some(left) = self.left.checked_sub(bytes.len()) else {
+ self.cut = true;
+ return None;
+ };
+ self.left = left;
return Some(bytes);
}
None
- })
+ }
+}
+
+/// What the catalog's `/DSS` says about the signer's certificate.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum DssRevocation {
+ /// Verified evidence revokes it.
+ Revoked,
+ /// A cap stopped the evidence being read in full, and what was read does not revoke it.
+ Incomplete,
+ /// All of the evidence was read, and none of it revokes it.
+ NotRevoked,
}
/// Check the revocation evidence in the catalog's `/DSS` against the signer's chain at `at`.
/// Only evidence whose signature verifies against the issuer counts; returns whether the
-/// certificate is revoked (which invalidates the signature).
-fn check_dss_revocation(doc: &Document, signer: Option<&Certificate>, at: &Option<Time>, info: &mut SignatureInfo) -> bool {
+/// certificate is revoked (which invalidates the signature), or whether a cap kept the check from
+/// reading all of the evidence.
+fn check_dss_revocation(doc: &Document, signer: Option<&Certificate>, at: &Option<Time>, info: &mut SignatureInfo) -> DssRevocation {
use crate::revocation::{CertificateList, OcspResponse, RevocationStatus};
- let (Some(signer), Some(at)) = (signer, *at) else { return false };
- let Some(root) = doc.root() else { return false };
+ let (Some(signer), Some(at)) = (signer, *at) else { return DssRevocation::NotRevoked };
+ let Some(root) = doc.root() else { return DssRevocation::NotRevoked };
let Some(dss) = doc.get(root).as_dict().and_then(|c| c.get(b"DSS").cloned()).map(|d| doc.resolve(&d)).and_then(|d| d.as_dict().cloned()) else {
- return false;
+ return DssRevocation::NotRevoked;
};
let issuer = info.chain.get(1).unwrap_or(signer);
// A verified revocation wins; "good" from any covering evidence is reported, but never
@@ -1022,7 +1069,8 @@ fn check_dss_revocation(doc: &Document, signer: Option<&Certificate>, at: &Optio
let mut revoked = None;
let mut covered = false;
let mut sources = Vec::new();
- for r in dss_evidence(doc, &dss, b"CRLs") {
+ let mut crls = DssEvidence::new(doc, &dss, b"CRLs");
+ for r in crls.by_ref() {
let Ok(list) = CertificateList::parse(&r) else { continue };
sources.push("CRL");
match list.check(signer, issuer, at) {
@@ -1034,8 +1082,10 @@ fn check_dss_revocation(doc: &Document, signer: Option<&Certificate>, at: &Optio
RevocationStatus::Unknown => {}
}
}
+ let mut cut = crls.cut;
if revoked.is_none() {
- for r in dss_evidence(doc, &dss, b"OCSPs") {
+ let mut ocsps = DssEvidence::new(doc, &dss, b"OCSPs");
+ for r in ocsps.by_ref() {
let Ok(resp) = OcspResponse::parse(&r) else { continue };
sources.push("OCSP");
match resp.check(signer, issuer, at) {
@@ -1047,6 +1097,7 @@ fn check_dss_revocation(doc: &Document, signer: Option<&Certificate>, at: &Optio
RevocationStatus::Unknown => {}
}
}
+ cut |= ocsps.cut;
}
match revoked {
Some(at) => {
@@ -1054,14 +1105,22 @@ fn check_dss_revocation(doc: &Document, signer: Option<&Certificate>, at: &Optio
// The evidence and the date go in together: one hole, so a reader can put the
// sentence's parts in whatever order its language wants.
info.details.push(Detail::of("The signer's certificate has been revoked ({}).", Fill::Value(format!("{}, {at}", sources.join(", ")))));
- true
+ DssRevocation::Revoked
+ }
+ // Evidence past a cap may revoke the certificate, so a partial check proves nothing.
+ None if cut => {
+ info.details.push(Detail::of(
+ "The signature could not be checked ({}).",
+ Fill::Reason("the /DSS holds more revocation evidence than PdfCraft reads".into()),
+ ));
+ DssRevocation::Incomplete
}
None if covered => {
info.details
.push(Detail::plain("The document's embedded revocation information shows that the signer's certificate has not been revoked."));
- false
+ DssRevocation::NotRevoked
}
- None => false,
+ None => DssRevocation::NotRevoked,
}
}
diff --git a/crates/sign/src/pdf_discovery_tests.rs b/crates/sign/src/pdf_discovery_tests.rs
index 9bc444823..6c0456ac5 100644
--- a/crates/sign/src/pdf_discovery_tests.rs
+++ b/crates/sign/src/pdf_discovery_tests.rs
@@ -383,13 +383,17 @@ fn dss_evidence_decodes_each_stream_once_within_its_caps() {
}
let mut dss = Dict::new();
dss.set(b"CRLs".to_vec(), Object::Array(items));
- let read: Vec<Vec<u8>> = dss_evidence(&doc, &dss, b"CRLs").collect();
+ let mut crls = DssEvidence::new(&doc, &dss, b"CRLs");
+ let read: Vec<Vec<u8>> = crls.by_ref().collect();
assert_eq!(read, vec![b"evidence".to_vec()]);
- // Distinct streams stop at the entry and byte budgets.
+ assert!(!crls.cut, "repeats and oversized streams are not a cap");
+ // Distinct streams stop at the entry and byte budgets, and say so.
let items: Vec<Object> =
(0..MAX_DSS_ENTRIES + 10).map(|_| Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), &[1; 1 << 16]))))).collect();
dss.set(b"OCSPs".to_vec(), Object::Array(items));
- let total: usize = dss_evidence(&doc, &dss, b"OCSPs").map(|b| b.len()).sum();
+ let mut ocsps = DssEvidence::new(&doc, &dss, b"OCSPs");
+ let total: usize = ocsps.by_ref().map(|b| b.len()).sum();
assert!(total <= MAX_DSS_BYTES, "{total}");
- assert!(dss_evidence(&doc, &dss, b"OCSPs").count() <= MAX_DSS_ENTRIES);
+ assert!(ocsps.cut);
+ assert!(DssEvidence::new(&doc, &dss, b"OCSPs").count() <= MAX_DSS_ENTRIES);
}
diff --git a/crates/sign/tests/it/pdf.rs b/crates/sign/tests/it/pdf.rs
index 61517b53d..d8f455050 100644
--- a/crates/sign/tests/it/pdf.rs
+++ b/crates/sign/tests/it/pdf.rs
@@ -1546,6 +1546,37 @@ fn a_revoked_certificate_stays_invalid_when_it_was_also_expired_at_signing() {
}
}
+#[test]
+fn a_revocation_behind_many_dss_entries_is_not_reported_valid() {
+ let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
+ let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
+ let t = |year| Time { year, month: 1, day: 1, hour: 0, minute: 0, second: 0 };
+ let crl = self_crl(&id, t(2026), t(2027), Time { year: 2026, month: 6, day: 1, hour: 8, minute: 0, second: 0 });
+ let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
+ let trust = TrustStore { certs: vec![anchor] };
+ // `/CRLs`: the revoking CRL after `benign` other entries; `repeated` lists one stream for all of them.
+ let status = |benign: usize, repeated: bool| {
+ let ltv = edit_after(&signed, |doc| {
+ let one = doc.add(stream_of(b"benign"));
+ let mut crls: Vec<Object> = (0..benign)
+ .map(|k| if repeated { Object::Ref(one) } else { Object::Ref(doc.add(stream_of(format!("benign {k}").as_bytes()))) })
+ .collect();
+ crls.push(Object::Ref(doc.add(stream_of(&crl))));
+ set_dss(doc, Object::Dict(dict_of(vec![("Type", Object::name("DSS")), ("CRLs", Object::Array(crls))])));
+ });
+ let s = signatures(&open(&ltv), &ltv, &trust).into_iter().find(|s| s.signed && !s.doc_timestamp).unwrap();
+ (s.status, s.details)
+ };
+ let (found, details) = status(1, false);
+ assert_eq!(found, Status::Invalid, "{details:?}");
+ // Repeats of one stream don't use up the entry cap, so the revocation is still found.
+ let (found, details) = status(2000, true);
+ assert_eq!(found, Status::Invalid, "{details:?}");
+ // Past the cap of distinct entries the check is incomplete, so the signature is not valid.
+ let (found, details) = status(1100, false);
+ assert_eq!(found, Status::Unknown, "{details:?}");
+}
+
#[test]
fn an_untrusted_timestamp_does_not_set_the_validation_time() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();