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    /// Readable document faults, retaining their allocation lifetime.
324    #[must_use]
325    pub fn faults(&self) -> &[Error] {
326        &self.faults
327    }
328    /// Original `SignedData` source range.
329    #[must_use]
330    pub fn span(&self) -> Span {
331        self.element.span()
332    }
333    /// Original encoding without serialization.
334    #[must_use]
335    pub fn as_bytes(&self) -> &'a [u8] {
336        self.element.as_bytes()
337    }
338}
339
340fn version_fault(
341    execution: &impl Work,
342    version: u64,
343    required: u64,
344    element: &Element<'_>,
345) -> Result<OwnedVec<Error>> {
346    let mut faults = execution.vector();
347    if version != required {
348        faults
349            .try_push(Error::schema(
350                ErrorCode::VersionMismatch,
351                "signedData.version",
352                element.span().start,
353            ))
354            .map_err(|reason| {
355                Error::resource(reason, "signedData.version", element.span().start)
356            })?;
357    }
358    Ok(faults.into_owned())
359}
360
361fn ordered<'a>(
362    parent: &Reader<'a>,
363    previous: &mut Option<&'a [u8]>,
364    element: &Element<'a>,
365    field: &'static str,
366) -> Result<()> {
367    if parent.encoding().is_der() {
368        if let Some(earlier) = *previous
369            && !structured_pkix::der::set_ordered(parent, earlier, element, field)
370                .map_err(Error::pkix)?
371        {
372            return Err(Error::schema(
373                ErrorCode::SetOrder,
374                field,
375                element.span().start,
376            ));
377        }
378        *previous = Some(element.as_bytes());
379    }
380    Ok(())
381}
382
383fn other_format(parent: &Reader<'_>, element: &Element<'_>, field: &'static str) -> Result<()> {
384    other_fields(parent, element, field).map(|_| ())
385}
386
387fn other_fields<'a>(
388    parent: &Reader<'a>,
389    element: &Element<'a>,
390    field: &'static str,
391) -> Result<(Reader<'a>, Oid<'a>, Element<'a>)> {
392    let mut inside = parent
393        .enter(element)
394        .map_err(|error| Error::encoding(error, field))?;
395    let kind = inside
396        .read_oid()
397        .map_err(|error| Error::encoding(error, field))?;
398    let value = required(&mut inside, field)?;
399    if !inside.is_empty() {
400        return Err(Error::schema(
401            ErrorCode::TrailingData,
402            field,
403            inside.offset(),
404        ));
405    }
406    Ok((inside, kind, value))
407}
408
409fn catalogue<'a, T>(
410    parent: &Reader<'a>,
411    set: &Element<'a>,
412    tag: Tag,
413    field: &'static str,
414    mut read: impl FnMut(&Reader<'a>, &Element<'a>) -> Result<T>,
415) -> Result<OwnedVec<T>> {
416    if set.tag() != tag {
417        return Err(Error::schema(
418            ErrorCode::UnexpectedTag,
419            field,
420            set.span().start,
421        ));
422    }
423    let mut members = parent
424        .enter(set)
425        .map_err(|error| Error::encoding(error, field))?;
426    let execution = parent.execution();
427    let mut values = execution.vector();
428    let mut previous = None;
429    while let Some(entry) = members
430        .next_element()
431        .map_err(|error| Error::encoding(error, field))?
432    {
433        ordered(&members, &mut previous, &entry, field)?;
434        values
435            .try_reserve(1)
436            .map_err(|reason| Error::resource(reason, field, entry.span().start))?;
437        let value = read(&members, &entry)?;
438        values
439            .try_push(value)
440            .map_err(|reason| Error::resource(reason, field, entry.span().start))?;
441    }
442    Ok(values.into_owned())
443}
444
445fn read_certificates<'a>(
446    parent: &Reader<'a>,
447    set: &Element<'a>,
448    version: &mut u64,
449) -> Result<(OwnedVec<CertificateChoice<'a>>, OwnedVec<Certificate<'a>>)> {
450    const FIELD: &str = "signedData.certificates";
451    let execution = parent.execution();
452    let mut certificates = execution.vector();
453    let choices = catalogue(
454        parent,
455        set,
456        Tag::context(true, 0),
457        FIELD,
458        |members, entry| {
459            Ok(match entry.tag() {
460                tag if tag == Tag::constructed(universal::SEQUENCE) => {
461                    certificates
462                        .try_reserve(1)
463                        .map_err(|reason| Error::resource(reason, FIELD, entry.span().start))?;
464                    let certificate =
465                        Certificate::read_element(members, entry).map_err(Error::pkix)?;
466                    let index = certificates.len();
467                    certificates
468                        .try_push(certificate)
469                        .map_err(|reason| Error::resource(reason, FIELD, entry.span().start))?;
470                    CertificateChoice::X509(index)
471                }
472                tag if tag == Tag::context(true, 0) => CertificateChoice::Extended(*entry),
473                tag if tag == Tag::context(true, 1) => {
474                    *version = (*version).max(3);
475                    CertificateChoice::AttributeV1(*entry)
476                }
477                tag if tag == Tag::context(true, 2) => {
478                    *version = (*version).max(4);
479                    CertificateChoice::AttributeV2(*entry)
480                }
481                tag if tag == Tag::context(true, 3) => {
482                    other_format(members, entry, FIELD)?;
483                    *version = 5;
484                    CertificateChoice::Other(*entry)
485                }
486                _ => {
487                    return Err(Error::schema(
488                        ErrorCode::UnexpectedTag,
489                        FIELD,
490                        entry.span().start,
491                    ));
492                }
493            })
494        },
495    )?;
496    Ok((choices, certificates.into_owned()))
497}
498
499fn read_version<'a>(inside: &mut Reader<'a>) -> Result<(u64, Element<'a>)> {
500    const FIELD: &str = "signedData.version";
501    let element = inside
502        .expect(Tag::primitive(universal::INTEGER))
503        .map_err(|error| Error::encoding(error, FIELD))?;
504    let version = inside
505        .integer(&element)
506        .map_err(|error| Error::encoding(error, FIELD))?
507        .as_u64()
508        .ok_or_else(|| Error::schema(ErrorCode::ValueTooLarge, FIELD, element.span().start))?;
509    Ok((version, element))
510}
511
512fn read_revocations<'a>(
513    parent: &Reader<'a>,
514    set: &Element<'a>,
515    version: &mut u64,
516) -> Result<OwnedVec<Element<'a>>> {
517    const FIELD: &str = "signedData.crls";
518    catalogue(
519        parent,
520        set,
521        Tag::context(true, 1),
522        FIELD,
523        |members, entry| {
524            if entry.tag() == Tag::context(true, 1) {
525                other_format(members, entry, FIELD)?;
526                *version = 5;
527            } else if entry.tag() != Tag::constructed(universal::SEQUENCE) {
528                return Err(Error::schema(
529                    ErrorCode::UnexpectedTag,
530                    FIELD,
531                    entry.span().start,
532                ));
533            }
534            Ok(*entry)
535        },
536    )
537}