structured-cms 0.10.0

Borrowed CMS SignedData processing with explicit providers and resource accounting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Original signer identities, algorithms, attributes and signature ranges.

use crate::attribute::{Attributes, Placement};
use crate::{Error, ErrorCode, Octets, Result};
use structured_asn1::memory::{OwnedVec, Work};
use structured_asn1::{Element, Encoding, Integer, Reader, ScopedReader, Span, Tag, universal};
use structured_pkix::Name;
use structured_pkix::algorithm::AlgorithmReading;

/// The identity actually selected by the document, without certificate selection.
#[derive(Debug)]
pub enum SignerIdentifier<'a> {
    /// The issuer's distinguished name and original certificate serial.
    IssuerAndSerial {
        /// Original issuer name, interpreted by the common PKIX name core.
        issuer: Name<'a>,
        /// Original minimal two's-complement serial; no certificate policy is inferred.
        serial: Integer<'a>,
    },
    /// Logical identifier octets, preserving any BER segmentation.
    SubjectKeyIdentifier(Octets<'a>),
}

impl<'a> SignerIdentifier<'a> {
    fn read(parent: &Reader<'a>, element: &Element<'a>) -> Result<Self> {
        const FIELD: &str = "signerInfo.sid";
        if element.tag() == Tag::context(false, 0) || element.tag() == Tag::context(true, 0) {
            return Octets::read_identifier(parent, element, FIELD).map(Self::SubjectKeyIdentifier);
        }
        if element.tag() != Tag::constructed(universal::SEQUENCE) {
            return Err(Error::schema(
                ErrorCode::UnexpectedTag,
                FIELD,
                element.span().start,
            ));
        }
        let mut inside = parent
            .enter(element)
            .map_err(|error| Error::encoding(error, FIELD))?;
        let name = inside
            .expect(Tag::constructed(universal::SEQUENCE))
            .map_err(|error| Error::encoding(error, FIELD))?;
        let issuer = structured_pkix::name::read(&inside, &name, FIELD).map_err(Error::pkix)?;
        let serial = inside
            .read_integer()
            .map_err(|error| Error::encoding(error, FIELD))?;
        if !inside.is_empty() {
            return Err(Error::schema(
                ErrorCode::TrailingData,
                FIELD,
                inside.offset(),
            ));
        }
        Ok(Self::IssuerAndSerial { issuer, serial })
    }

    /// The version required by this CHOICE (RFC5652 ยง5.3).
    #[must_use]
    pub fn required_version(&self) -> u64 {
        match self {
            Self::IssuerAndSerial { .. } => 1,
            Self::SubjectKeyIdentifier(_) => 3,
        }
    }
}

/// One parsed CMS signer, retaining original byte identity and diagnostic storage.
#[derive(Debug)]
pub struct SignerInfo<'a> {
    version: u64,
    sid: SignerIdentifier<'a>,
    digest_algorithm: AlgorithmReading<'a>,
    signed_attributes: Option<Attributes<'a>>,
    signature_algorithm: AlgorithmReading<'a>,
    signature: Octets<'a>,
    signed_fields: &'a [u8],
    unsigned_attributes: Option<Attributes<'a>>,
    encoding: Encoding,
    element: Element<'a>,
    faults: OwnedVec<Error>,
}

impl<'a> SignerInfo<'a> {
    /// Requires the original producing parser, before a protocol layer reads
    /// retained fields. Equal accounts or equal encodings are not session identity.
    pub fn require_session(&self, parent: &Reader<'_>, field: &'static str) -> Result<()> {
        if !self.digest_algorithm.same_session(parent) {
            return Err(Error::pkix(structured_pkix::Error::new(
                structured_pkix::ErrorCode::ForeignReader,
                field,
                self.span().start,
            )));
        }
        Ok(())
    }
    /// Reads a signer at the original depth with both producing work ceilings.
    ///
    /// A uniquely readable version mismatch is retained as a fault, never a
    /// successful conformance claim. Signed attributes remain DER and their
    /// original octets are never repaired (RFC5652 ยงยง5.3โ€“5.4).
    /// Each algorithm uses the PKIX inspection reader: a uniquely bounded
    /// malformed parameter stays visible with its located diagnostic, while
    /// missing/ambiguous fields and resource/processing refusals remain errors.
    /// Provider preparation refuses either malformed algorithm before callbacks.
    /// <https://www.rfc-editor.org/rfc/rfc5652#section-5.3>
    pub fn read(parent: &Reader<'a>, element: &Element<'a>) -> Result<Self> {
        const FIELD: &str = "signerInfo";
        if element.tag() != Tag::constructed(universal::SEQUENCE) {
            return Err(Error::schema(
                ErrorCode::UnexpectedTag,
                FIELD,
                element.span().start,
            ));
        }
        let mut inside = parent
            .enter(element)
            .map_err(|error| Error::encoding(error, FIELD))?;
        let execution = parent.execution();
        let mut faults = execution.vector();
        let version_element = inside
            .expect(Tag::primitive(universal::INTEGER))
            .map_err(|error| Error::encoding(error, "signerInfo.version"))?;
        let version = inside
            .integer(&version_element)
            .map_err(|error| Error::encoding(error, "signerInfo.version"))?
            .as_u64()
            .ok_or_else(|| {
                Error::schema(
                    ErrorCode::ValueTooLarge,
                    "signerInfo.version",
                    version_element.span().start,
                )
            })?;
        let named = required(&mut inside, "signerInfo.sid")?;
        let sid = SignerIdentifier::read(&inside, &named)?;
        if version != sid.required_version() {
            faults
                .try_push(Error::schema(
                    ErrorCode::VersionMismatch,
                    "signerInfo.version",
                    version_element.span().start,
                ))
                .map_err(|reason| {
                    Error::resource(reason, "signerInfo.version", version_element.span().start)
                })?;
        }
        let digest = required(&mut inside, "signerInfo.digestAlgorithm")?;
        let digest_algorithm =
            read_algorithm(&inside, &digest, "signerInfo.digestAlgorithm", &mut faults)?;
        let mut next = required(&mut inside, "signerInfo.signatureAlgorithm")?;
        let signed_attributes = if next.tag() == Tag::context(true, 0) {
            let attributes = read_attributes(&inside, &next, Placement::Signed, &mut faults)?;
            next = required(&mut inside, "signerInfo.signatureAlgorithm")?;
            Some(attributes)
        } else {
            None
        };
        let signature_algorithm =
            read_algorithm(&inside, &next, "signerInfo.signatureAlgorithm", &mut faults)?;
        let signature_element = required(&mut inside, "signerInfo.signature")?;
        let signature = Octets::read(&inside, &signature_element, "signerInfo.signature")?;
        let signed_fields = field_range(element, &version_element, &signature_element);
        let unsigned_attributes = match inside
            .next_element()
            .map_err(|error| Error::encoding(error, "signerInfo.unsignedAttrs"))?
        {
            Some(attributes) => Some(read_attributes(
                &inside,
                &attributes,
                Placement::Unsigned,
                &mut faults,
            )?),
            None => None,
        };
        if !inside.is_empty() {
            return Err(Error::schema(
                ErrorCode::TrailingData,
                FIELD,
                inside.offset(),
            ));
        }
        Ok(Self {
            version,
            sid,
            digest_algorithm,
            signed_attributes,
            signature_algorithm,
            signature,
            signed_fields,
            unsigned_attributes,
            encoding: inside.encoding(),
            element: *element,
            faults: faults.into_owned(),
        })
    }

    /// Declared numeric version, independently of any retained mismatch.
    #[must_use]
    pub fn version(&self) -> u64 {
        self.version
    }
    /// The document's signer identity CHOICE.
    #[must_use]
    pub fn sid(&self) -> &SignerIdentifier<'a> {
        &self.sid
    }
    /// Original digest inspection, including any parameter syntax fault.
    /// Only the reading's `identifier()` exposes a validated provider input.
    #[must_use]
    pub fn digest_algorithm(&self) -> &AlgorithmReading<'a> {
        &self.digest_algorithm
    }
    /// Original signed attributes, when present.
    #[must_use]
    pub fn signed_attributes(&self) -> Option<&Attributes<'a>> {
        self.signed_attributes.as_ref()
    }
    /// Original signature inspection, including any parameter syntax fault.
    /// A readable malformed algorithm is never a validated provider input.
    #[must_use]
    pub fn signature_algorithm(&self) -> &AlgorithmReading<'a> {
        &self.signature_algorithm
    }
    /// Logical signature octets without joining.
    #[must_use]
    pub fn signature(&self) -> &Octets<'a> {
        &self.signature
    }
    /// Original attributes outside the signature's coverage.
    #[must_use]
    pub fn unsigned_attributes(&self) -> Option<&Attributes<'a>> {
        self.unsigned_attributes.as_ref()
    }

    /// The original encodings of `version` through `signature`, in their order
    /// of appearance and without the unsigned attributes that follow them.
    #[must_use]
    pub fn signed_fields(&self) -> &'a [u8] {
        self.signed_fields
    }

    /// Reads direct unsigned countersignatures lazily through original provenance.
    /// Malformed values remain independent answers; resource refusal stops once.
    pub fn countersignatures_in<'s>(
        &'s self,
        parent: &'s Reader<'a>,
    ) -> crate::counter::Countersignatures<'s, 'a> {
        crate::counter::Countersignatures::new(self, parent)
    }
    /// Encoding contract of the envelope, not that of the signed attributes.
    #[must_use]
    pub fn encoding(&self) -> Encoding {
        self.encoding
    }
    /// Original signer range.
    #[must_use]
    pub fn span(&self) -> Span {
        self.element.span()
    }
    /// Original whole element, including its index in the source container.
    ///
    /// This is not a global signer ordinal: nested counter values retain
    /// their own original container positions. Ranges use the producing
    /// reader's coordinates; joined-source projection remains with its source map.
    #[must_use]
    pub fn element(&self) -> &Element<'a> {
        &self.element
    }
    /// Entire original encoding, including non-DER envelope spelling.
    #[must_use]
    pub fn as_bytes(&self) -> &'a [u8] {
        self.element.as_bytes()
    }
    /// Retained document faults; resource refusals never enter this list.
    ///
    /// Registered CMS instance/placement violations are retained independently
    /// of certificate selection. Unknown generic attribute repetition is not
    /// a blanket fault; value syntax and context-specific binding stay separate.
    #[must_use]
    pub fn faults(&self) -> &[Error] {
        &self.faults
    }

    /// Parsed-field identity for duplicate recovery, not signature acceptance.
    ///
    /// BER outer headers and octet segmentation are ignored. Issuer names use
    /// the common PKIX equality rules; serial bytes, opaque parameters and
    /// attribute sets retain encoded identity. Two
    /// present NULL parameters compare by their parsed NULL value, so its
    /// root length spelling cannot create a different reading. Signed
    /// attributes therefore remain byte-identical. RFC5754 ยง2 SHA-2 digest
    /// absence/NULL defaults share the PKIX comparer; other algorithm defaults
    /// and selected-provider acceptance remain separate operations.
    pub fn same_value(&self, other: &SignerInfo<'_>, parent: &Reader<'_>) -> Result<bool> {
        if !self.same_fields(other, parent)? {
            return Ok(false);
        }
        // Resource refusal belongs to this duplicate query, not a prior
        // retained algorithm's location. Syntax/caller errors keep provenance.
        let comparison_error = |source| duplicate_comparison_error(source, other.span().start);
        // RFC5754 ยง2 requires SHA224/256/384/512 absent/NULL equivalence.
        // Written identity is checked first so identical opaque malformed
        // parameters remain inspectable, without claiming algorithm acceptance.
        // https://www.rfc-editor.org/rfc/rfc5754#section-2
        if !self
            .digest_algorithm
            .same_written_in(&other.digest_algorithm, parent)
            .map_err(comparison_error)?
        {
            let (Some(left), Some(right)) = (
                self.digest_algorithm.identifier(),
                other.digest_algorithm.identifier(),
            ) else {
                // Malformed parameters have only their original encoded
                // identity. They cannot acquire valid algorithm defaults.
                return Ok(false);
            };
            if !left
                .digest_matches_in(&right, parent)
                .map_err(comparison_error)?
            {
                return Ok(false);
            }
        }
        self.signature_algorithm
            .same_written_in(&other.signature_algorithm, parent)
            .map_err(comparison_error)
    }

    // Shared document-field identity for encoded and selected-provider paths.
    // Provider identities replace only algorithm comparison; original signed
    // octets and signature/SID value checks cannot be bypassed by either path.
    pub(crate) fn same_fields(&self, other: &SignerInfo<'_>, parent: &Reader<'_>) -> Result<bool> {
        let field = "signedData.signerInfos";
        let at = other.span().start;
        self.require_session(parent, field)?;
        other.require_session(parent, field)?;
        parent
            .execution()
            .charge_work(1)
            .map_err(|reason| Error::resource(reason, field, at))?;
        if self.version != other.version {
            return Ok(false);
        }
        let same_sid = match (&self.sid, &other.sid) {
            (
                SignerIdentifier::IssuerAndSerial { issuer, serial },
                SignerIdentifier::IssuerAndSerial {
                    issuer: right,
                    serial: number,
                },
            ) => {
                // RFC5280 ยง7.1 names denote the same issuer after the shared
                // directory-string preparation; original signedAttrs stay exact.
                // https://www.rfc-editor.org/rfc/rfc5280#section-7.1
                issuer
                    .matches_in(right, parent)
                    .map_err(|source| duplicate_comparison_error(source, at))?
                    && same_bytes(parent, serial.as_bytes(), number.as_bytes(), field, at)?
            }
            (
                SignerIdentifier::SubjectKeyIdentifier(left),
                SignerIdentifier::SubjectKeyIdentifier(right),
            ) => left.same_value(right, parent, field, at)?,
            _ => false,
        };
        if !same_sid {
            return Ok(false);
        }
        for (left, right) in [
            (&self.signed_attributes, &other.signed_attributes),
            (&self.unsigned_attributes, &other.unsigned_attributes),
        ] {
            if !same_optional(
                parent,
                left.as_ref().map(|attrs| attrs.element().as_bytes()),
                right.as_ref().map(|attrs| attrs.element().as_bytes()),
                field,
                at,
            )? {
                return Ok(false);
            }
        }
        self.signature
            .same_value(&other.signature, parent, field, at)
    }
}

fn read_attributes<'a, W: Work>(
    parent: &Reader<'a>,
    element: &Element<'a>,
    placement: Placement,
    faults: &mut OwnedVec<Error, W>,
) -> Result<Attributes<'a>> {
    let reading = Attributes::read_inspection(parent, element, placement)?;
    if let Some(fault) = reading.fault() {
        let field = fault.field();
        let at = fault.offset();
        faults
            .try_push(fault)
            .map_err(|reason| Error::resource(reason, field, at))?;
    }
    reading.inspect_registered(parent, faults)?;
    Ok(reading)
}

fn read_algorithm<'a, W: Work>(
    parent: &Reader<'a>,
    element: &Element<'a>,
    field: &'static str,
    faults: &mut OwnedVec<Error, W>,
) -> Result<AlgorithmReading<'a>> {
    // RFC5652 ยง5.3 carries an AlgorithmIdentifier in each slot. Retaining a
    // unique malformed parameter is inspection recovery, not conforming BER
    // or permission to resolve a cryptographic algorithm. PKIX owns that one
    // structural/parameter kernel; resources and ambiguous syntax still refuse.
    // https://www.rfc-editor.org/rfc/rfc5652#section-5.3
    let reading =
        structured_pkix::algorithm::read_inspection(parent, element, field).map_err(Error::pkix)?;
    if let Some(fault) = reading.fault() {
        faults
            .try_push(Error::pkix(fault.clone()))
            .map_err(|reason| Error::resource(reason, fault.field(), fault.offset()))?;
    }
    Ok(reading)
}

fn duplicate_comparison_error(source: structured_pkix::Error, at: u64) -> Error {
    if source.is_resource() {
        Error::pkix(structured_pkix::Error::new(
            source.code(),
            "signedData.signerInfos",
            at,
        ))
    } else {
        Error::pkix(source)
    }
}

// The fields are consecutive members of the signer, so they are one range of
// its own encoding: no element starts before the first or ends after the last.
fn field_range<'a>(signer: &Element<'a>, first: &Element<'a>, last: &Element<'a>) -> &'a [u8] {
    let origin = signer.span().start;
    let start = first.span().start - origin;
    let end = last.span().start + last.span().length - origin;
    let bytes = signer.as_bytes();
    // Both members lie inside the signer, whose encoding holds every offset.
    let start = usize::try_from(start).expect("member offset fits the signer encoding");
    let end = usize::try_from(end).expect("member end fits the signer encoding");
    &bytes[start..end]
}

pub(crate) fn required<'a>(
    reader: &mut ScopedReader<'a, '_>,
    field: &'static str,
) -> Result<Element<'a>> {
    reader
        .next_element()
        .map_err(|error| Error::encoding(error, field))?
        .ok_or_else(|| Error::schema(ErrorCode::MissingField, field, reader.offset()))
}

fn same_bytes(
    parent: &Reader<'_>,
    left: &[u8],
    right: &[u8],
    field: &'static str,
    at: u64,
) -> Result<bool> {
    let execution = parent.execution();
    execution
        .charge_work(1)
        .map_err(|reason| Error::resource(reason, field, at))?;
    if left.len() != right.len() {
        return Ok(false);
    }
    execution
        .charge_work(left.len() as u64)
        .map_err(|reason| Error::resource(reason, field, at))?;
    Ok(left == right)
}

fn same_optional(
    parent: &Reader<'_>,
    left: Option<&[u8]>,
    right: Option<&[u8]>,
    field: &'static str,
    at: u64,
) -> Result<bool> {
    parent
        .execution()
        .charge_work(1)
        .map_err(|reason| Error::resource(reason, field, at))?;
    match (left, right) {
        (None, None) => Ok(true),
        (Some(left), Some(right)) => same_bytes(parent, left, right, field, at),
        _ => Ok(false),
    }
}