From adb9e769cab985991c125f3ef13f9d2ea97fb1b7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 21:57:49 -0500 Subject: [PATCH 1/3] Add bounded borrowed certificate inspection views MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep wire evidence separate from existing verification and trust APIs. Inspection semantics acknowledge Afloat’s original Craft Anything raw-field and non-minimal-length contributions. --- crates/pkcs7/README.md | 9 ++ crates/pkcs7/src/inspection.rs | 184 ++++++++++++++++++++++++++++ crates/pkcs7/src/lib.rs | 1 + crates/pkcs7/tests/it/inspection.rs | 119 ++++++++++++++++++ crates/pkcs7/tests/it/main.rs | 1 + 5 files changed, 314 insertions(+) create mode 100644 crates/pkcs7/src/inspection.rs create mode 100644 crates/pkcs7/tests/it/inspection.rs diff --git a/crates/pkcs7/README.md b/crates/pkcs7/README.md index fc715c3b9..b0339a848 100644 --- a/crates/pkcs7/README.md +++ b/crates/pkcs7/README.md @@ -7,6 +7,11 @@ message or a digital ID file is made of. keeps its exact encoding, so a signed structure is verified over the bytes that were signed. Reading is strict DER; `parse_ber` also takes indefinite lengths and segmented strings, which PKCS #12 files from Windows use. Nesting is bounded. +- **`inspection`**: borrowed definite-length cursors without child-list allocations and borrowed X.509 wire fields. + Each sibling list is bounded to 4,096 elements and child cursors to depth 32; callers must + separately bound whole-document traversal. Redundant lengths are flagged. Optional and + trailing fields remain explicitly uninspected until their cursors are consumed. This is + evidence extraction, not a complete certificate validator or a signature/trust verdict. - **`x509`**: certificates (RFC 5280): names, validity, key, the extensions that matter for signing (basic constraints, key usage, extended key usage, key identifiers, OCSP and CRL locations), `build_chain` / `build_chain_noted` (issuers that may issue, path length, validity, @@ -42,3 +47,7 @@ Weak algorithms are read, not refused, because old signed documents use them: `DigestAlg::weakness` and `PublicKey::weakness` say when one is weak, and the caller decides. Moved from PdfCraft's `pdfcraft-sign`. + +The inspection profile follows Craft Anything’s bounded reader and Afloat’s raw-certificate +and non-minimal-length contributions (craft-anything #1131, #1514, #1646). Existing verification +and trust APIs are unchanged; high-level CMS/metadata adapters remain separate work. diff --git a/crates/pkcs7/src/inspection.rs b/crates/pkcs7/src/inspection.rs new file mode 100644 index 000000000..93b9eed39 --- /dev/null +++ b/crates/pkcs7/src/inspection.rs @@ -0,0 +1,184 @@ +//! Bounded, borrowed inspection of definite-length ASN.1 and X.509 wire fields. +//! +//! These views are evidence, not validated certificates or signature/trust verdicts. They do +//! not replace [`crate::x509::Certificate`]. Unknown algorithms and original encodings are kept. +//! The profile follows Craft Anything's inspection reader (including Afloat's raw-field and +//! non-minimal-length work); callers retain their existing semantic and verification checks. + +use crate::der::{Tlv, tag}; + +/// Maximum siblings read by one cursor, matching the inspection consumer's bound. +pub const MAX_CHILDREN: usize = 4096; +/// Maximum nesting accepted when obtaining child cursors. Root elements have depth zero. +pub const MAX_DEPTH: usize = 32; + +/// An inspection stopped without establishing that the remaining bytes are complete. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum InspectionError { + #[error("malformed or unsupported definite-length element")] + Malformed, + #[error("inspection child limit reached")] + ChildLimit, + #[error("inspection depth limit reached")] + DepthLimit, + #[error("missing or unexpected certificate field")] + Field, +} + +/// One borrowed wire element. Redundant definite lengths are readable but explicitly noted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Element<'a> { + tlv: Tlv<'a>, + depth: usize, + non_minimal_length: bool, +} + +impl<'a> Element<'a> { + pub fn tag(&self) -> u8 { + self.tlv.tag + } + pub fn raw(&self) -> &'a [u8] { + self.tlv.raw + } + pub fn value(&self) -> &'a [u8] { + self.tlv.value + } + pub fn non_minimal_length(&self) -> bool { + self.non_minimal_length + } + + /// Inspect children without allocating a child list. Primitive values are not interpreted as children. + pub fn children(&self) -> Result, InspectionError> { + if self.tlv.tag & 0x20 == 0 { + return Err(InspectionError::Field); + } + // Prevent callers following nested wire fields from silently exceeding the profile. + if self.depth >= MAX_DEPTH { + return Err(InspectionError::DepthLimit); + } + Ok(Cursor::at_depth(self.tlv.value, self.depth + 1)) + } +} + +/// A non-recursive sibling cursor with a hard per-list work bound and no child-list allocation. +/// +/// Successful reads allocate no memory; the underlying parser may allocate an error message. +/// `Ok(None)` means complete input, never a malformed/limited prefix. Errors are sticky and +/// leave the offending remainder available. Separate cursors have separate sibling budgets; +/// this does not impose a global budget on an application's traversal of many lists. +#[derive(Clone, Debug)] +pub struct Cursor<'a> { + remaining: &'a [u8], + count: usize, + depth: usize, + stopped: Option, +} + +impl<'a> Cursor<'a> { + pub fn new(input: &'a [u8]) -> Self { + Self::at_depth(input, 0) + } + fn at_depth(input: &'a [u8], depth: usize) -> Self { + Self { remaining: input, count: 0, depth, stopped: None } + } + /// Bytes not yet inspected. An empty remainder alone is not a recursive DER validation. + pub fn remaining(&self) -> &'a [u8] { + self.remaining + } + pub fn next_element(&mut self) -> Result>, InspectionError> { + if let Some(error) = self.stopped { + return Err(error); + } + if self.remaining.is_empty() { + return Ok(None); + } + if self.count == MAX_CHILDREN { + self.stopped = Some(InspectionError::ChildLimit); + return Err(InspectionError::ChildLimit); + } + let input = self.remaining; + let (tlv, rest) = match Tlv::parse(input) { + Ok(value) => value, + Err(_) => { + self.stopped = Some(InspectionError::Malformed); + return Err(InspectionError::Malformed); + } + }; + let non_minimal_length = input.get(1).is_some_and(|b| b & 0x80 != 0) && (input.get(2) == Some(&0) || tlv.value.len() < 128); + self.remaining = rest; + self.count += 1; + Ok(Some(Element { tlv, depth: self.depth, non_minimal_length })) + } + fn required(&mut self, expected: u8) -> Result, InspectionError> { + self.next_element()?.filter(|e| e.tag() == expected).ok_or(InspectionError::Field) + } +} + +/// Borrowed required X.509 wire fields, without algorithm, signature, key or trust validation. +/// +/// The BIT STRING is retained whole, including its unused-bit count. Both AlgorithmIdentifier +/// encodings are retained independently: their equality and parameter policy are the verifier's +/// responsibility. Optional/trailing fields remain in bounded cursors rather than being silently +/// reported as complete. Parsing this view does not walk nested names, keys or extensions. +#[derive(Clone, Debug)] +pub struct CertificateView<'a> { + pub certificate: Element<'a>, + pub tbs: Element<'a>, + pub version: Option>, + pub serial: Element<'a>, + pub signed_algorithm: Element<'a>, + pub issuer: Element<'a>, + pub validity: Element<'a>, + pub subject: Element<'a>, + pub spki: Element<'a>, + pub signature_algorithm: Element<'a>, + pub signature_bits: Element<'a>, + pub remaining_certificate_fields: Cursor<'a>, + pub remaining_tbs_fields: Cursor<'a>, +} + +impl<'a> CertificateView<'a> { + /// Inspect required fields of the first certificate; return bytes following its outer TLV. + /// Readable prefixes do not imply complete optional fields. Inspect the returned cursors to + /// distinguish complete, malformed, and limited tails. Existing strict verification stays separate. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let certificate = roots.required(tag::SEQUENCE)?; + let mut outer = certificate.children()?; + let tbs = outer.required(tag::SEQUENCE)?; + let signature_algorithm = outer.required(tag::SEQUENCE)?; + let signature_bits = outer.required(tag::BIT_STRING)?; + let mut fields = tbs.children()?; + let first = fields.next_element()?.ok_or(InspectionError::Field)?; + let (version, serial) = if first.tag() == tag::ctx(0) { + (Some(first), fields.required(tag::INTEGER)?) + } else if first.tag() == tag::INTEGER { + (None, first) + } else { + return Err(InspectionError::Field); + }; + let signed_algorithm = fields.required(tag::SEQUENCE)?; + let issuer = fields.required(tag::SEQUENCE)?; + let validity = fields.required(tag::SEQUENCE)?; + let subject = fields.required(tag::SEQUENCE)?; + let spki = fields.required(tag::SEQUENCE)?; + Ok(( + Self { + certificate, + tbs, + version, + serial, + signed_algorithm, + issuer, + validity, + subject, + spki, + signature_algorithm, + signature_bits, + remaining_certificate_fields: outer, + remaining_tbs_fields: fields, + }, + roots.remaining(), + )) + } +} diff --git a/crates/pkcs7/src/lib.rs b/crates/pkcs7/src/lib.rs index 776be2749..0b501515d 100644 --- a/crates/pkcs7/src/lib.rs +++ b/crates/pkcs7/src/lib.rs @@ -29,6 +29,7 @@ pub mod cms; pub mod der; mod ec512; +pub mod inspection; pub mod keys; pub mod pkcs12; pub mod revocation; diff --git a/crates/pkcs7/tests/it/inspection.rs b/crates/pkcs7/tests/it/inspection.rs new file mode 100644 index 000000000..e079a19f5 --- /dev/null +++ b/crates/pkcs7/tests/it/inspection.rs @@ -0,0 +1,119 @@ +//! Benign wire parity and boundary tests; no signature/trust decisions are made by these views. +use craft_pkcs7::der::{self, tag}; +use craft_pkcs7::inspection::{CertificateView, Cursor, InspectionError, MAX_CHILDREN, MAX_DEPTH}; + +#[test] +fn cursor_keeps_exact_bytes_and_length_notes() { + for (encoded, note) in [(vec![4, 3, 1, 2, 3], false), (vec![4, 0x81, 3, 1, 2, 3], true), (vec![4, 0x82, 0, 3, 1, 2, 3], true)] { + let mut cursor = Cursor::new(&encoded); + let element = cursor.next_element().unwrap().unwrap(); + assert_eq!(element.raw(), encoded); + assert_eq!(element.raw().as_ptr(), encoded.as_ptr()); + assert_eq!(element.value(), &[1, 2, 3]); + assert_eq!(element.non_minimal_length(), note); + assert_eq!(cursor.next_element(), Ok(None)); + } + let canonical = der::octets(&[7; 128]); + assert!(!Cursor::new(&canonical).next_element().unwrap().unwrap().non_minimal_length()); +} + +#[test] +fn cursor_distinguishes_completion_and_sticky_partial_results() { + let bytes = [5, 0, 4]; // One complete NULL followed by an incomplete header. + let mut cursor = Cursor::new(&bytes); + assert_eq!(cursor.next_element().unwrap().unwrap().tag(), tag::NULL); + assert_eq!(cursor.next_element(), Err(InspectionError::Malformed)); + assert_eq!(cursor.next_element(), Err(InspectionError::Malformed)); + assert_eq!(cursor.remaining(), &[4]); + assert_eq!(Cursor::new(&[0x30, 0x80, 0, 0]).next_element(), Err(InspectionError::Malformed)); + assert_eq!(Cursor::new(&[0x30, 0]).next_element().unwrap().unwrap().raw(), &[0x30, 0]); +} + +#[test] +fn sibling_limit_allows_exact_completion_without_allocating_a_child_list() { + let mut bytes = [5, 0].repeat(MAX_CHILDREN); + let mut cursor = Cursor::new(&bytes); + for _ in 0..MAX_CHILDREN { + assert!(cursor.next_element().unwrap().is_some()); + } + assert_eq!(cursor.next_element(), Ok(None)); + bytes.extend_from_slice(&[5, 0]); + let mut cursor = Cursor::new(&bytes); + for _ in 0..MAX_CHILDREN { + cursor.next_element().unwrap(); + } + assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit)); + assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit)); + assert_eq!(cursor.remaining(), &[5, 0]); +} + +#[test] +fn nested_cursor_depth_is_explicitly_bounded() { + let mut bytes = der::seq(&[]); + for _ in 0..MAX_DEPTH { + bytes = der::seq(&[&bytes]); + } + let mut element = Cursor::new(&bytes).next_element().unwrap().unwrap(); + for _ in 0..MAX_DEPTH { + element = element.children().unwrap().next_element().unwrap().unwrap(); + } + assert!(matches!(element.children(), Err(InspectionError::DepthLimit))); +} + +fn certificate(version: bool, tail: &[u8]) -> (Vec, Vec, Vec, Vec) { + // Unknown algorithms are still inspectable. These are wire fixtures, not signed certificates. + let algorithm = der::seq(&[&der::oid("1.2.3.4"), &der::tlv(tag::NULL, &[])]); + let name = der::seq(&[]); + let spki = der::seq(&[&algorithm, &der::bit_string(&[1, 2, 3])]); + let version_field = if version { der::explicit(0, &der::int(2)) } else { vec![] }; + let tbs = der::seq(&[&version_field, &der::int(7), &algorithm, &name, &der::seq(&[]), &name, &spki, tail]); + let cert = der::seq(&[&tbs, &algorithm, &der::bit_string(&[9, 8, 7])]); + (cert, tbs, algorithm, spki) +} + +#[test] +fn certificate_fields_are_borrowed_exact_and_do_not_consume_trailing_input() { + for version in [false, true] { + let (mut bytes, tbs, algorithm, spki) = certificate(version, &[]); + let len = bytes.len(); + bytes.extend_from_slice(&[5, 0]); + let (mut view, rest) = CertificateView::parse(&bytes).unwrap(); + assert_eq!(view.certificate.raw(), &bytes[..len]); + assert_eq!(view.certificate.raw().as_ptr(), bytes.as_ptr()); + assert_eq!(view.tbs.raw(), tbs); + assert_eq!(view.signed_algorithm.raw(), algorithm); + assert_eq!(view.signature_algorithm.raw(), algorithm); + assert_eq!(view.spki.raw(), spki); + assert_eq!(view.serial.value(), &[7]); + assert_eq!(view.signature_bits.value(), &[0, 9, 8, 7]); + assert_eq!(view.version.is_some(), version); + assert_eq!(rest, &[5, 0]); + assert_eq!(view.remaining_tbs_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_certificate_fields.next_element(), Ok(None)); + } +} + +#[test] +fn required_fields_do_not_hide_optional_tail_diagnostics() { + let (bytes, _, _, _) = certificate(false, &[0xa3]); + let (mut view, _) = CertificateView::parse(&bytes).unwrap(); + assert_eq!(view.remaining_tbs_fields.remaining(), &[0xa3]); + assert_eq!(view.remaining_tbs_fields.next_element(), Err(InspectionError::Malformed)); + // This partial wire view is deliberately not accepted as a validated certificate. + assert!(craft_pkcs7::Certificate::parse(&bytes).is_err()); +} + +#[test] +fn existing_certificate_fixture_retains_signed_components() { + let cert = craft_pkcs7::x509::load_certificates(include_bytes!("../data/ca.crt.pem")).unwrap().remove(0); + let (view, rest) = CertificateView::parse(&cert.raw).unwrap(); + assert!(rest.is_empty()); + let parts = cert.clone().into_parts(); + assert_eq!(view.tbs.raw(), parts.tbs); + assert_eq!(view.signature_algorithm.raw(), parts.sig_alg); + assert_eq!(view.signature_bits.value().first(), Some(&0)); + assert_eq!(&view.signature_bits.value()[1..], parts.signature); + assert_eq!(view.issuer.raw(), parts.issuer.raw); + assert_eq!(view.subject.raw(), parts.subject.raw); + assert_eq!(view.spki.raw(), parts.public_key.spki()); +} diff --git a/crates/pkcs7/tests/it/main.rs b/crates/pkcs7/tests/it/main.rs index 4a10ec793..c4a2f0fba 100644 --- a/crates/pkcs7/tests/it/main.rs +++ b/crates/pkcs7/tests/it/main.rs @@ -5,4 +5,5 @@ mod ber; mod chain; mod cms; mod crypto; +mod inspection; mod store_keys; From c24d572c8fa6ac80a1967da050121ad19b8cbe6e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 22:03:03 -0500 Subject: [PATCH 2/3] Add private bounded CMS wire prefix views --- crates/pkcs7/src/inspection.rs | 2 + crates/pkcs7/src/inspection/cms.rs | 98 +++++++++++++++++++++++++ crates/pkcs7/tests/it/inspection_cms.rs | 56 ++++++++++++++ crates/pkcs7/tests/it/main.rs | 2 + 4 files changed, 158 insertions(+) create mode 100644 crates/pkcs7/src/inspection/cms.rs create mode 100644 crates/pkcs7/tests/it/inspection_cms.rs diff --git a/crates/pkcs7/src/inspection.rs b/crates/pkcs7/src/inspection.rs index 93b9eed39..aacc6aa94 100644 --- a/crates/pkcs7/src/inspection.rs +++ b/crates/pkcs7/src/inspection.rs @@ -7,6 +7,8 @@ use crate::der::{Tlv, tag}; +pub mod cms; + /// Maximum siblings read by one cursor, matching the inspection consumer's bound. pub const MAX_CHILDREN: usize = 4096; /// Maximum nesting accepted when obtaining child cursors. Root elements have depth zero. diff --git a/crates/pkcs7/src/inspection/cms.rs b/crates/pkcs7/src/inspection/cms.rs new file mode 100644 index 000000000..0d63c64ad --- /dev/null +++ b/crates/pkcs7/src/inspection/cms.rs @@ -0,0 +1,98 @@ +//! Borrowed CMS wire prefixes. These do not validate signed attributes or authenticate signers. +//! Optional/remaining fields are explicit cursors, governed by the parent inspection bounds. + +use super::{Cursor, Element, InspectionError}; +use crate::der::tag; + +/// Required SignedData fields inside ContentInfo, without copying certificates or content. +/// All optional certificate/CRL/signer sets remain in `remaining_fields` for bounded inspection. +#[derive(Clone, Debug)] +pub struct SignedDataView<'a> { + pub content_info: Element<'a>, + pub signed_data: Element<'a>, + pub version: Element<'a>, + pub digest_algorithms: Element<'a>, + pub encapsulated_content: Element<'a>, + pub remaining_fields: Cursor<'a>, + pub remaining_explicit_fields: Cursor<'a>, + pub remaining_content_info_fields: Cursor<'a>, +} + +impl<'a> SignedDataView<'a> { + /// Read the required prefix and retain every tail. Matching the ContentInfo OID is not a + /// signature check. Encapsulated content, certificates, attributes and identities are unvalidated. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let content_info = roots.required(tag::SEQUENCE)?; + let mut fields = content_info.children()?; + let kind = fields.required(tag::OID)?; + if kind.value() != [0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 1, 7, 2] { + return Err(InspectionError::Field); + } + let explicit = fields.required(tag::ctx(0))?; + let mut wrapped = explicit.children()?; + let signed_data = wrapped.required(tag::SEQUENCE)?; + let mut inner = signed_data.children()?; + let version = inner.required(tag::INTEGER)?; + let digest_algorithms = inner.required(tag::SET)?; + let encapsulated_content = inner.required(tag::SEQUENCE)?; + Ok(( + Self { + content_info, + signed_data, + version, + digest_algorithms, + encapsulated_content, + remaining_fields: inner, + remaining_explicit_fields: wrapped, + remaining_content_info_fields: fields, + }, + roots.remaining(), + )) + } +} + +/// One SignerInfo's raw required fields, not an authentication or identity-match result. +/// The identity remains its original issuer/serial SEQUENCE or context-specific key identifier. +/// Version consistency, algorithm policy, signed-attribute validation and re-encoding remain the +/// caller's responsibility; this view never substitutes an encapsulated content type or digest. +#[derive(Clone, Debug)] +pub struct SignerInfoView<'a> { + pub signer_info: Element<'a>, + pub version: Element<'a>, + pub identifier: Element<'a>, + pub digest_algorithm: Element<'a>, + pub signed_attributes: Option>, + pub signature_algorithm: Element<'a>, + pub signature: Element<'a>, + pub remaining_fields: Cursor<'a>, +} + +impl<'a> SignerInfoView<'a> { + /// Read one signer's required wire fields, retaining any optional tail and subsequent signers. + /// An absent signature field is an error, not an implicitly empty authenticated signature. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let signer_info = roots.required(tag::SEQUENCE)?; + let mut fields = signer_info.children()?; + let version = fields.required(tag::INTEGER)?; + let identifier = fields.next_element()?.ok_or(InspectionError::Field)?; + if identifier.tag() != tag::SEQUENCE && identifier.tag() != tag::ctx_prim(0) { + return Err(InspectionError::Field); + } + let digest_algorithm = fields.required(tag::SEQUENCE)?; + let next = fields.next_element()?.ok_or(InspectionError::Field)?; + let (signed_attributes, signature_algorithm) = if next.tag() == tag::ctx(0) { + (Some(next), fields.required(tag::SEQUENCE)?) + } else if next.tag() == tag::SEQUENCE { + (None, next) + } else { + return Err(InspectionError::Field); + }; + let signature = fields.required(tag::OCTET_STRING)?; + Ok(( + Self { signer_info, version, identifier, digest_algorithm, signed_attributes, signature_algorithm, signature, remaining_fields: fields }, + roots.remaining(), + )) + } +} diff --git a/crates/pkcs7/tests/it/inspection_cms.rs b/crates/pkcs7/tests/it/inspection_cms.rs new file mode 100644 index 000000000..4e7609f76 --- /dev/null +++ b/crates/pkcs7/tests/it/inspection_cms.rs @@ -0,0 +1,56 @@ +use craft_pkcs7::der::{self, tag}; +use craft_pkcs7::inspection::InspectionError; +use craft_pkcs7::inspection::cms::{SignedDataView, SignerInfoView}; + +fn fixture(key_id: bool, attrs: bool) -> (Vec, Vec) { + let digest = der::seq(&[&der::oid("2.16.840.1.101.3.4.2.1")]); + let sig_alg = der::seq(&[&der::oid("1.2.840.113549.1.1.1"), &der::tlv(tag::NULL, &[])]); + let identifier = if key_id { der::tlv(tag::ctx_prim(0), &[7, 8]) } else { der::seq(&[&der::seq(&[]), &der::int(7)]) }; + let attributes = if attrs { + let content = der::seq(&[&der::oid("1.2.840.113549.1.9.3"), &der::set_of(&[&der::oid("1.2.840.113549.1.7.1")])]); + let digest_attr = der::seq(&[&der::oid("1.2.840.113549.1.9.4"), &der::set_of(&[&der::octets(&[6; 32])])]); + der::tlv(tag::ctx(0), &[content, digest_attr].concat()) + } else { + vec![] + }; + let signer = der::seq(&[&der::int(if key_id { 3 } else { 1 }), &identifier, &digest, &attributes, &sig_alg, &der::octets(&[1, 2, 3])]); + let content = der::seq(&[&der::oid("1.2.840.113549.1.7.1"), &der::explicit(0, &der::octets(b"hello"))]); + let signed_data = der::seq(&[&der::int(1), &der::set_of(&[&digest]), &content, &der::set_of(&[&signer])]); + (der::seq(&[&der::oid("1.2.840.113549.1.7.2"), &der::explicit(0, &signed_data)]), signer) +} + +#[test] +fn cms_fields_retain_encodings_and_both_identifier_forms() { + for key_id in [false, true] { + for attrs in [false, true] { + let (cms, signer) = fixture(key_id, attrs); + let (mut view, rest) = SignedDataView::parse(&cms).unwrap(); + assert!(rest.is_empty()); + assert_eq!(view.content_info.raw().as_ptr(), cms.as_ptr()); + assert_eq!(view.version.value(), &[1]); + let signer_set = view.remaining_fields.next_element().unwrap().unwrap(); + let (mut si, rest) = SignerInfoView::parse(signer_set.value()).unwrap(); + assert_eq!(si.signer_info.raw(), signer); + assert!(rest.is_empty()); + assert_eq!(si.identifier.tag(), if key_id { 0x80 } else { 0x30 }); + assert_eq!(si.signed_attributes.is_some(), attrs); + assert_eq!(si.signature.value(), &[1, 2, 3]); + assert_eq!(si.remaining_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_explicit_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_content_info_fields.next_element(), Ok(None)); + } + } +} + +#[test] +fn signer_prefix_does_not_hide_optional_tail_or_consume_next_signer() { + let (_, signer) = fixture(false, true); + let parsed = der::Tlv::parse_all(&signer).unwrap(); + let with_tail = der::seq(&[parsed.value, &[0xa1]]); + let joined = [with_tail, signer.clone()].concat(); + let (mut view, rest) = SignerInfoView::parse(&joined).unwrap(); + assert_eq!(rest, signer); + assert_eq!(view.remaining_fields.next_element(), Err(InspectionError::Malformed)); + assert_eq!(view.remaining_fields.remaining(), &[0xa1]); +} diff --git a/crates/pkcs7/tests/it/main.rs b/crates/pkcs7/tests/it/main.rs index c4a2f0fba..1c6616b39 100644 --- a/crates/pkcs7/tests/it/main.rs +++ b/crates/pkcs7/tests/it/main.rs @@ -7,3 +7,5 @@ mod cms; mod crypto; mod inspection; mod store_keys; + +mod inspection_cms; From e4252faa21de3772dd609816a90a1836984a01c0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 02:55:14 -0500 Subject: [PATCH 3/3] Exercise optional CMS wire sets and preserve acceptance boundaries --- crates/pkcs7/src/inspection/cms.rs | 5 +++ crates/pkcs7/tests/it/inspection_cms.rs | 55 +++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/crates/pkcs7/src/inspection/cms.rs b/crates/pkcs7/src/inspection/cms.rs index 0d63c64ad..e59d84a8c 100644 --- a/crates/pkcs7/src/inspection/cms.rs +++ b/crates/pkcs7/src/inspection/cms.rs @@ -1,5 +1,10 @@ //! Borrowed CMS wire prefixes. These do not validate signed attributes or authenticate signers. //! Optional/remaining fields are explicit cursors, governed by the parent inspection bounds. +//! +//! Each `parse` starts a new depth root. Callers traversing nested structures must retain their +//! whole-document work/depth policy; reparsing a slice does not carry a previous cursor's budget. +//! The required wire tags and exact SignedData OID are this view's structural profile, not a +//! replacement for a consumer's acceptance or diagnostic policy. Existing parsers remain unchanged. use super::{Cursor, Element, InspectionError}; use crate::der::tag; diff --git a/crates/pkcs7/tests/it/inspection_cms.rs b/crates/pkcs7/tests/it/inspection_cms.rs index 4e7609f76..ffdc75a42 100644 --- a/crates/pkcs7/tests/it/inspection_cms.rs +++ b/crates/pkcs7/tests/it/inspection_cms.rs @@ -54,3 +54,58 @@ fn signer_prefix_does_not_hide_optional_tail_or_consume_next_signer() { assert_eq!(view.remaining_fields.next_element(), Err(InspectionError::Malformed)); assert_eq!(view.remaining_fields.remaining(), &[0xa1]); } + +// Ordinary optional sets and complete trailing TLVs, never interpreted as trust evidence here. +fn optional_fixture(certificate_count: usize, with_crl: bool, tails: bool) -> (Vec, Vec, Vec) { + let certificate = craft_pkcs7::x509::load_certificates(include_bytes!("../data/ca.crt.pem")).unwrap().remove(0).raw; + let (base, signer) = fixture(false, true); + let (view, _) = SignedDataView::parse(&base).unwrap(); + let certificates = der::tlv(tag::ctx(0), &certificate.repeat(certificate_count)); + let crl = if with_crl { der::tlv(tag::ctx(1), &der::seq(&[])) } else { vec![] }; + let tail = if tails { der::tlv(tag::NULL, &[]) } else { vec![] }; + let signed_data = der::seq(&[ + view.version.raw(), + view.digest_algorithms.raw(), + view.encapsulated_content.raw(), + &certificates, + &crl, + &der::set_of(&[&signer]), + &tail, + ]); + let wrapped = der::tlv(tag::ctx(0), &[signed_data, tail.clone()].concat()); + let content = der::seq(&[&der::oid("1.2.840.113549.1.7.2"), &wrapped, &tail]); + ([content, tail].concat(), certificate, crl) +} + +#[test] +fn optional_certificate_crl_sets_and_all_tails_remain_visible() { + for with_crl in [false, true] { + let (bytes, cert, crl) = optional_fixture(2, with_crl, true); + let (mut view, rest) = SignedDataView::parse(&bytes).unwrap(); + assert_eq!(rest, &[5, 0]); + let certs = view.remaining_fields.next_element().unwrap().unwrap(); + assert_eq!(certs.tag(), tag::ctx(0)); + assert_eq!(certs.value(), cert.repeat(2)); + if with_crl { + assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().raw(), crl); + } + assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().tag(), tag::SET); + for cursor in [&mut view.remaining_fields, &mut view.remaining_explicit_fields, &mut view.remaining_content_info_fields] { + assert_eq!(cursor.next_element().unwrap().unwrap().raw(), &[5, 0]); + assert_eq!(cursor.next_element(), Ok(None)); + } + } +} + +#[test] +fn signer_unsigned_attributes_remain_raw_and_separate_from_signed_attributes() { + let (_, signer) = fixture(true, true); + let fields = der::Tlv::parse_all(&signer).unwrap(); + let unsigned = der::tlv(tag::ctx(1), &der::seq(&[])); + let bytes = der::seq(&[fields.value, &unsigned]); + let (mut view, rest) = SignerInfoView::parse(&bytes).unwrap(); + assert!(rest.is_empty()); + assert_eq!(view.signed_attributes.unwrap().tag(), tag::ctx(0)); + assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().raw(), unsigned); + assert_eq!(view.remaining_fields.next_element(), Ok(None)); +}