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;