Skip to main content

structured_cms/
signed.rs

1//! `SignedData` catalogues and version facts, without application trust decisions.
2
3use crate::content::{ContentInfo, Encapsulated};
4use crate::signer::{SignerInfo, required};
5use crate::{Error, ErrorCode, Result, oid};
6use structured_asn1::memory::{OwnedVec, Work};
7use structured_asn1::{Element, Encoding, Oid, Parser, Reader, Span, Tag, universal};
8use structured_pkix::{AlgorithmIdentifier, Certificate};
9
10/// One original certificate CHOICE (RFC5652 §10.2.2).
11///
12/// X.509 values live in one flat accounted catalogue, avoiding one Box
13/// allocation per certificate and avoiding a large enum slot for opaque kinds.
14#[derive(Debug, Clone, Copy)]
15pub enum CertificateChoice<'a> {
16    /// Index into this message's [`SignedData::certificates`] catalogue.
17    X509(usize),
18    /// Obsolete PKCS6 extended certificate, preserved without interpreting it.
19    Extended(Element<'a>),
20    /// Obsolete version-1 attribute certificate, preserved as encoded.
21    AttributeV1(Element<'a>),
22    /// Version-2 attribute certificate, preserved as encoded.
23    AttributeV2(Element<'a>),
24    /// Other format with its original format identifier and value.
25    Other(Element<'a>),
26}
27
28/// Original CMS other-revocation format and its untouched ANY value. Decoding
29/// a recognized format establishes no signature, authorization or freshness.
30#[derive(Debug)]
31pub struct OtherRevocationInfo<'a> {
32    reader: Reader<'a>,
33    kind: Oid<'a>,
34    value: Element<'a>,
35}
36
37impl<'a> OtherRevocationInfo<'a> {
38    /// Reads an original context \[1\] IMPLICIT `OtherRevocationInfoFormat` using
39    /// the same field kernel as `SignedData`'s structural catalogue validation.
40    pub fn read(parent: &Reader<'a>, element: &Element<'a>) -> Result<Self> {
41        const FIELD: &str = "signedData.crls.other";
42        if element.tag() != Tag::context(true, 1) {
43            return Err(Error::schema(
44                ErrorCode::UnexpectedTag,
45                FIELD,
46                element.span().start,
47            ));
48        }
49        let (reader, kind, value) = other_fields(parent, element, FIELD)?;
50        Ok(Self {
51            reader,
52            kind,
53            value,
54        })
55    }
56
57    /// Original open-format identifier, without provider/default normalization.
58    #[must_use]
59    pub fn kind(&self) -> Oid<'a> {
60        self.kind
61    }
62
63    /// Whole original ANY element, not its contents or a re-encoded value.
64    #[must_use]
65    pub fn value(&self) -> Element<'a> {
66        self.value
67    }
68
69    /// Decodes the successful whole `OCSPResponse` required by RFC5940 §3.
70    /// An unknown format returns None; a known malformed response or unsigned
71    /// protocol failure returns an error. Unsupported inner response syntax is
72    /// preserved by the shared envelope, rather than promoted to a basic body.
73    /// <https://www.rfc-editor.org/rfc/rfc5940#section-3>
74    pub fn ocsp(self) -> Result<Option<structured_pkix::ocsp::ResponseBytes<'a>>> {
75        const FIELD: &str = "signedData.crls.other";
76        self.reader
77            .charge(9)
78            .map_err(|error| Error::encoding(error, FIELD))?;
79        if self.kind != oid::OCSP_RESPONSE {
80            return Ok(None);
81        }
82        match structured_pkix::ocsp::Response::read_element(&self.reader, &self.value)
83            .map_err(Error::pkix)?
84        {
85            structured_pkix::ocsp::Response::Successful(response) => Ok(Some(response)),
86            structured_pkix::ocsp::Response::Failure { span, .. } => {
87                Err(Error::schema(ErrorCode::MalformedValue, FIELD, span.start))
88            }
89        }
90    }
91}
92
93/// Original CMS `SignedData` with independently accounted metadata and faults.
94#[derive(Debug)]
95pub struct SignedData<'a> {
96    parser: &'a Parser,
97    encoding: Encoding,
98    outer: u32,
99    version: u64,
100    required_version: u64,
101    algorithms: OwnedVec<AlgorithmIdentifier<'a>>,
102    content: Encapsulated<'a>,
103    choices: OwnedVec<CertificateChoice<'a>>,
104    certificates: OwnedVec<Certificate<'a>>,
105    certificate_field: Option<Span>,
106    revocations: OwnedVec<Element<'a>>,
107    revocation_field: Option<Span>,
108    signers: OwnedVec<SignerInfo<'a>>,
109    faults: OwnedVec<Error>,
110    element: Element<'a>,
111}
112
113impl<'a> SignedData<'a> {
114    /// Reads one entire CMS `ContentInfo` and its `SignedData` using the same parser.
115    pub fn read(parser: &'a Parser, encoded: &'a [u8], base: u64) -> Result<Self> {
116        let mut root = parser
117            .read(encoded, base)
118            .map_err(|error| Error::encoding(error, "contentInfo"))?;
119        let (envelope, parent) = ContentInfo::read(&mut root)?;
120        parent
121            .execution()
122            .charge_work(envelope.kind().as_bytes().len() as u64)
123            .map_err(|reason| {
124                Error::resource(reason, "contentInfo.contentType", envelope.span().start)
125            })?;
126        if envelope.kind() != oid::SIGNED_DATA {
127            return Err(Error::schema(
128                ErrorCode::UnexpectedContentType,
129                "contentInfo.contentType",
130                envelope.span().start,
131            ));
132        }
133        Self::read_element(&parent, envelope.content())
134    }
135
136    /// Reads an original embedded `SignedData`, preserving enclosing depth/work.
137    pub fn read_element(parent: &Reader<'a>, element: &Element<'a>) -> Result<Self> {
138        const FIELD: &str = "signedData";
139        if element.tag() != Tag::constructed(universal::SEQUENCE) {
140            return Err(Error::schema(
141                ErrorCode::UnexpectedTag,
142                FIELD,
143                element.span().start,
144            ));
145        }
146        let mut inside = parent
147            .enter(element)
148            .map_err(|error| Error::encoding(error, FIELD))?;
149        let execution = parent.execution();
150        let (version, version_element) = read_version(&mut inside)?;
151        let set = required(&mut inside, "signedData.digestAlgorithms")?;
152        let algorithms = catalogue(
153            &inside,
154            &set,
155            Tag::constructed(universal::SET),
156            "signedData.digestAlgorithms",
157            |members, entry| {
158                structured_pkix::algorithm::read(members, entry, "signedData.digestAlgorithms")
159                    .map_err(Error::pkix)
160            },
161        )?;
162        let content_element = required(&mut inside, "signedData.encapContentInfo")?;
163        let content = Encapsulated::read(&inside, &content_element)?;
164        execution
165            .charge_work(content.kind().as_bytes().len() as u64)
166            .map_err(|reason| {
167                Error::resource(
168                    reason,
169                    "signedData.encapContentInfo.eContentType",
170                    content.span().start,
171                )
172            })?;
173        // RFC5652 §5.1 ladder, computed during the admitted schema traversal:
174        // 5 (other), 4 (v2 AC), 3 (v1 AC/v3 signer/non-data), otherwise 1.
175        // https://www.rfc-editor.org/rfc/rfc5652#section-5.1
176        let mut required_version = if content.kind() == oid::DATA { 1 } else { 3 };
177        let mut choices = parent.memory().vector();
178        let mut certificates = parent.memory().vector();
179        let mut revocations = parent.memory().vector();
180        let mut certificate_field = None;
181        let mut revocation_field = None;
182        let mut next = required(&mut inside, "signedData.signerInfos")?;
183        if next.tag() == Tag::context(true, 0) {
184            certificate_field = Some(next.span());
185            (choices, certificates) = read_certificates(&inside, &next, &mut required_version)?;
186            next = required(&mut inside, "signedData.signerInfos")?;
187        }
188        if next.tag() == Tag::context(true, 1) {
189            revocation_field = Some(next.span());
190            revocations = read_revocations(&inside, &next, &mut required_version)?;
191            next = required(&mut inside, "signedData.signerInfos")?;
192        }
193        let signers = catalogue(
194            &inside,
195            &next,
196            Tag::constructed(universal::SET),
197            "signedData.signerInfos",
198            |members, entry| {
199                let signer = SignerInfo::read(members, entry)?;
200                if signer.version() == 3 {
201                    required_version = required_version.max(3);
202                }
203                Ok(signer)
204            },
205        )?;
206        if !inside.is_empty() {
207            return Err(Error::schema(
208                ErrorCode::TrailingData,
209                FIELD,
210                inside.offset(),
211            ));
212        }
213        let faults = version_fault(&execution, version, required_version, &version_element)?;
214        Ok(Self {
215            parser: parent.parser(),
216            encoding: parent.encoding(),
217            outer: inside.depth(),
218            version,
219            required_version,
220            algorithms,
221            content,
222            choices,
223            certificates,
224            certificate_field,
225            revocations,
226            revocation_field,
227            signers,
228            faults,
229            element: *element,
230        })
231    }
232
233    /// Declared version.
234    #[must_use]
235    pub fn version(&self) -> u64 {
236        self.version
237    }
238    /// Version independently required by the encoded choices.
239    #[must_use]
240    pub fn required_version(&self) -> u64 {
241        self.required_version
242    }
243    /// Original advertised digest algorithms; provider resolution is separate.
244    /// RFC5652 §§5.1, 5.3 permit zero entries and do not require recipients to
245    /// refuse an unlisted signer digest. These advertisements never replace the
246    /// original signer algorithm; stricter catalogue acceptance is caller policy.
247    /// <https://www.rfc-editor.org/rfc/rfc5652#section-5.1>
248    #[must_use]
249    pub fn digest_algorithms(&self) -> &[AlgorithmIdentifier<'a>] {
250        &self.algorithms
251    }
252    /// Original attached or absent content.
253    #[must_use]
254    pub fn content(&self) -> &Encapsulated<'a> {
255        &self.content
256    }
257    /// Certificate choices in their original order.
258    #[must_use]
259    pub fn certificate_choices(&self) -> &[CertificateChoice<'a>] {
260        &self.choices
261    }
262    /// Parsed X.509 certificates, in the order referenced by X509 choices.
263    #[must_use]
264    pub fn certificates(&self) -> &[Certificate<'a>] {
265        &self.certificates
266    }
267    /// Original presence of the certificate field, including an empty written set.
268    #[must_use]
269    pub fn certificate_field(&self) -> Option<Span> {
270        self.certificate_field
271    }
272    /// Original presence of the revocation field, including an empty written set.
273    #[must_use]
274    pub fn revocation_field(&self) -> Option<Span> {
275        self.revocation_field
276    }
277    /// Original revocation choices, not implicitly authenticated or fetched.
278    #[must_use]
279    pub fn revocations(&self) -> &[Element<'a>] {
280        &self.revocations
281    }
282    /// Opens one original revocation CHOICE under the current query operation.
283    ///
284    /// The reader contains the whole original CRL or other-format CHOICE, not
285    /// its contents. Original parser, encoding, location and set-member depth
286    /// are preserved; the query may come from another document and pays all
287    /// new work/storage while both source and operation ceilings remain active.
288    /// No bytes are copied and no new parser or authentication is introduced.
289    /// An absent ordinal returns `None` only after paid metadata admission.
290    pub fn revocation_reader_in<'query>(
291        &self,
292        query: &Reader<'query>,
293        ordinal: usize,
294    ) -> Result<Option<Reader<'query>>>
295    where
296        'a: 'query,
297    {
298        const FIELD: &str = "signedData.crls";
299        let at = self.revocation_field.unwrap_or(self.element.span()).start;
300        query
301            .execution()
302            .charge_work(1)
303            .map_err(|reason| Error::resource(reason, FIELD, at))?;
304        let Some(entry) = self.revocations.get(ordinal) else {
305            return Ok(None);
306        };
307        self.parser
308            .read_nested_query_in(
309                query,
310                entry.as_bytes(),
311                entry.span().start,
312                self.encoding,
313                self.outer,
314            )
315            .map(Some)
316            .map_err(|error| Error::encoding(error, FIELD))
317    }
318    /// Independent signers in their original order, without an all-signers verdict.
319    #[must_use]
320    pub fn signers(&self) -> &[SignerInfo<'a>] {
321        &self.signers
322    }
323    /// Refuses a reader of another parser session.
324    pub(crate) fn require_session(&self, parent: &Reader<'_>, field: &'static str) -> Result<()> {
325        if !core::ptr::eq(self.parser, parent.parser()) {
326            return Err(Error::pkix(structured_pkix::Error::new(
327                structured_pkix::ErrorCode::ForeignReader,
328                field,
329                self.element.span().start,
330            )));
331        }
332        Ok(())
333    }
334    /// Refuses a `SignerInfo` that is not one of these signers, by identity.
335    ///
336    /// Constant work: a reference to one of these signers lies inside their
337    /// storage, so an address range test replaces a scan of every signer.
338    pub(crate) fn require_signer(
339        &self,
340        signer: &SignerInfo<'_>,
341        field: &'static str,
342    ) -> Result<()> {
343        let storage = self.signers.as_ptr_range();
344        let address = core::ptr::from_ref(signer).cast::<SignerInfo<'a>>();
345        if !storage.contains(&address) {
346            return Err(Error::schema(
347                ErrorCode::InvalidLocation,
348                field,
349                signer.span().start,
350            ));
351        }
352        Ok(())
353    }
354    /// Readable document faults, retaining their allocation lifetime.
355    #[must_use]
356    pub fn faults(&self) -> &[Error] {
357        &self.faults
358    }
359    /// Original `SignedData` source range.
360    #[must_use]
361    pub fn span(&self) -> Span {
362        self.element.span()
363    }
364    /// Original encoding without serialization.
365    #[must_use]
366    pub fn as_bytes(&self) -> &'a [u8] {
367        self.element.as_bytes()
368    }
369}
370
371fn version_fault(
372    execution: &impl Work,
373    version: u64,
374    required: u64,
375    element: &Element<'_>,
376) -> Result<OwnedVec<Error>> {
377    let mut faults = execution.vector();
378    if version != required {
379        faults
380            .try_push(Error::schema(
381                ErrorCode::VersionMismatch,
382                "signedData.version",
383                element.span().start,
384            ))
385            .map_err(|reason| {
386                Error::resource(reason, "signedData.version", element.span().start)
387            })?;
388    }
389    Ok(faults.into_owned())
390}
391
392fn ordered<'a>(
393    parent: &Reader<'a>,
394    previous: &mut Option<&'a [u8]>,
395    element: &Element<'a>,
396    field: &'static str,
397) -> Result<()> {
398    if parent.encoding().is_der() {
399        if let Some(earlier) = *previous
400            && !structured_pkix::der::set_ordered(parent, earlier, element, field)
401                .map_err(Error::pkix)?
402        {
403            return Err(Error::schema(
404                ErrorCode::SetOrder,
405                field,
406                element.span().start,
407            ));
408        }
409        *previous = Some(element.as_bytes());
410    }
411    Ok(())
412}
413
414fn other_format(parent: &Reader<'_>, element: &Element<'_>, field: &'static str) -> Result<()> {
415    other_fields(parent, element, field).map(|_| ())
416}
417
418fn other_fields<'a>(
419    parent: &Reader<'a>,
420    element: &Element<'a>,
421    field: &'static str,
422) -> Result<(Reader<'a>, Oid<'a>, Element<'a>)> {
423    let mut inside = parent
424        .enter(element)
425        .map_err(|error| Error::encoding(error, field))?;
426    let kind = inside
427        .read_oid()
428        .map_err(|error| Error::encoding(error, field))?;
429    let value = required(&mut inside, field)?;
430    if !inside.is_empty() {
431        return Err(Error::schema(
432            ErrorCode::TrailingData,
433            field,
434            inside.offset(),
435        ));
436    }
437    Ok((inside, kind, value))
438}
439
440fn catalogue<'a, T>(
441    parent: &Reader<'a>,
442    set: &Element<'a>,
443    tag: Tag,
444    field: &'static str,
445    mut read: impl FnMut(&Reader<'a>, &Element<'a>) -> Result<T>,
446) -> Result<OwnedVec<T>> {
447    if set.tag() != tag {
448        return Err(Error::schema(
449            ErrorCode::UnexpectedTag,
450            field,
451            set.span().start,
452        ));
453    }
454    let mut members = parent
455        .enter(set)
456        .map_err(|error| Error::encoding(error, field))?;
457    let execution = parent.execution();
458    let mut values = execution.vector();
459    let mut previous = None;
460    while let Some(entry) = members
461        .next_element()
462        .map_err(|error| Error::encoding(error, field))?
463    {
464        ordered(&members, &mut previous, &entry, field)?;
465        values
466            .try_reserve(1)
467            .map_err(|reason| Error::resource(reason, field, entry.span().start))?;
468        let value = read(&members, &entry)?;
469        values
470            .try_push(value)
471            .map_err(|reason| Error::resource(reason, field, entry.span().start))?;
472    }
473    Ok(values.into_owned())
474}
475
476fn read_certificates<'a>(
477    parent: &Reader<'a>,
478    set: &Element<'a>,
479    version: &mut u64,
480) -> Result<(OwnedVec<CertificateChoice<'a>>, OwnedVec<Certificate<'a>>)> {
481    const FIELD: &str = "signedData.certificates";
482    let execution = parent.execution();
483    let mut certificates = execution.vector();
484    let choices = catalogue(
485        parent,
486        set,
487        Tag::context(true, 0),
488        FIELD,
489        |members, entry| {
490            Ok(match entry.tag() {
491                tag if tag == Tag::constructed(universal::SEQUENCE) => {
492                    certificates
493                        .try_reserve(1)
494                        .map_err(|reason| Error::resource(reason, FIELD, entry.span().start))?;
495                    let certificate =
496                        Certificate::read_element(members, entry).map_err(Error::pkix)?;
497                    let index = certificates.len();
498                    certificates
499                        .try_push(certificate)
500                        .map_err(|reason| Error::resource(reason, FIELD, entry.span().start))?;
501                    CertificateChoice::X509(index)
502                }
503                tag if tag == Tag::context(true, 0) => CertificateChoice::Extended(*entry),
504                tag if tag == Tag::context(true, 1) => {
505                    *version = (*version).max(3);
506                    CertificateChoice::AttributeV1(*entry)
507                }
508                tag if tag == Tag::context(true, 2) => {
509                    *version = (*version).max(4);
510                    CertificateChoice::AttributeV2(*entry)
511                }
512                tag if tag == Tag::context(true, 3) => {
513                    other_format(members, entry, FIELD)?;
514                    *version = 5;
515                    CertificateChoice::Other(*entry)
516                }
517                _ => {
518                    return Err(Error::schema(
519                        ErrorCode::UnexpectedTag,
520                        FIELD,
521                        entry.span().start,
522                    ));
523                }
524            })
525        },
526    )?;
527    Ok((choices, certificates.into_owned()))
528}
529
530fn read_version<'a>(inside: &mut Reader<'a>) -> Result<(u64, Element<'a>)> {
531    const FIELD: &str = "signedData.version";
532    let element = inside
533        .expect(Tag::primitive(universal::INTEGER))
534        .map_err(|error| Error::encoding(error, FIELD))?;
535    let version = inside
536        .integer(&element)
537        .map_err(|error| Error::encoding(error, FIELD))?
538        .as_u64()
539        .ok_or_else(|| Error::schema(ErrorCode::ValueTooLarge, FIELD, element.span().start))?;
540    Ok((version, element))
541}
542
543fn read_revocations<'a>(
544    parent: &Reader<'a>,
545    set: &Element<'a>,
546    version: &mut u64,
547) -> Result<OwnedVec<Element<'a>>> {
548    const FIELD: &str = "signedData.crls";
549    catalogue(
550        parent,
551        set,
552        Tag::context(true, 1),
553        FIELD,
554        |members, entry| {
555            if entry.tag() == Tag::context(true, 1) {
556                other_format(members, entry, FIELD)?;
557                *version = 5;
558            } else if entry.tag() != Tag::constructed(universal::SEQUENCE) {
559                return Err(Error::schema(
560                    ErrorCode::UnexpectedTag,
561                    FIELD,
562                    entry.span().start,
563                ));
564            }
565            Ok(*entry)
566        },
567    )
568}