structured-cades 0.13.0

Source-bound CAdES baseline composition over CMS and long-term validation facts
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
//! Annex A value schemas, composed from the producing ASN.1/ESS/PKIX kernels.
//! Embedded evidence is read, never authenticated here. Reference timestamp
//! syntax uses the common timestamp inspection pass so mapped failures survive.

use super::{Fault, end, next, sequence, syntax};
use crate::{Error, Result};
use structured_asn1::{
    Element, Oid, Reader, Span, Tag,
    memory::{OwnedVec, Work},
    universal,
};
use structured_cms::{Octets, attribute::Attribute};
use structured_pkix::{
    Certificate, algorithm,
    crl::CertificateList,
    ocsp::{BasicResponse, ResponderId},
};

// EN319122-1 AnnexA/Table1: certificate/revocation references and values,
// reference timestamps, and credential references. These are wire identifiers.
pub(crate) const LEGACY: [Oid<'static>; 8] = [
    Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 2, 21]),
    Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 2, 22]),
    Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 2, 23]),
    Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 2, 24]),
    Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 2, 25]),
    Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 2, 26]),
    Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 2, 44]),
    Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 1, 9, 16, 2, 45]),
];
const FIELD: &str = "cades.legacy";

pub(super) fn inspect<'d, W: Work>(
    attribute: &Attribute<'d>,
    parent: &Reader<'d>,
    faults: &mut OwnedVec<Fault, W>,
    hints: &mut OwnedVec<Span, W>,
    values: &mut Option<super::values::Values<'d, W>>,
    work: &W,
) -> Result<()> {
    for (ordinal, kind) in LEGACY.into_iter().enumerate() {
        parent
            .charge(1 + attribute.kind().as_bytes().len().min(kind.as_bytes().len()) as u64)
            .map_err(|cause| Error::encoding(cause, FIELD))?;
        if attribute.kind() != kind {
            continue;
        }
        // AnnexA.1 specifies exactly one value, also when this signer is
        // inside a timestamp. CMS's open attribute catalogue cannot enforce
        // these registered schemas. Retain the fault before skipping decoding.
        // https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf
        if attribute.values().len() != 1 {
            faults
                .try_push(Fault {
                    attribute: kind,
                    field: "cades.legacy.values",
                    cause: Error::Syntax {
                        code: structured_cms::ErrorCode::AttributeCardinality,
                        field: "cades.legacy.values",
                        at: attribute.span().start,
                    },
                })
                .map_err(|cause| Error::resource(cause, FIELD, attribute.span().start))?;
            return Ok(());
        }
        // Reference timestamps use prepare::tokens' original SourceMap path.
        if matches!(ordinal, 4 | 5) {
            return Ok(());
        }
        let reading = read_attribute(attribute, ordinal, parent, hints, values, work);
        if let Err(cause) = reading {
            if cause.is_terminal() {
                return Err(cause);
            }
            let at = cause.offset();
            faults
                .try_push(Fault {
                    attribute: kind,
                    field: FIELD,
                    cause,
                })
                .map_err(|cause| Error::resource(cause, FIELD, at))?;
        }
        return Ok(());
    }
    Ok(())
}

fn read_attribute<'d, W: Work>(
    attribute: &Attribute<'d>,
    ordinal: usize,
    parent: &Reader<'d>,
    hints: &mut OwnedVec<Span, W>,
    values: &mut Option<super::values::Values<'d, W>>,
    work: &W,
) -> Result<()> {
    let mut reader = attribute
        .value_reader_in(0, parent, FIELD)?
        .ok_or_else(|| syntax(FIELD, attribute.span().start))?;
    let value = next(&mut reader, FIELD)?;
    end(&reader, FIELD)?;
    // AnnexA.1.1–A.1.4 and normative AnnexD define all four shapes below.
    // https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf
    match ordinal {
        0 => certificate_refs(&reader, &value, Some(hints)),
        6 => certificate_refs::<W>(&reader, &value, None),
        1 | 7 => revocation_refs(&reader, &value),
        2 => certificate_values(
            &reader,
            &value,
            attribute.span(),
            values.get_or_insert_with(|| super::values::Values::new(work)),
        ),
        3 => revocation_values(
            &reader,
            &value,
            attribute.span(),
            values.get_or_insert_with(|| super::values::Values::new(work)),
        ),
        _ => Err(Error::Foreign {
            at: value.span().start,
        }),
    }
}

fn certificate_refs<W: Work>(
    parent: &Reader<'_>,
    value: &Element<'_>,
    mut hints: Option<&mut OwnedVec<Span, W>>,
) -> Result<()> {
    let mut list = sequence(parent, value, FIELD)?;
    while let Some(value) = list
        .next_element()
        .map_err(|cause| Error::encoding(cause, FIELD))?
    {
        let mut fields = sequence(&list, &value, FIELD)?;
        let hash = next(&mut fields, FIELD)?;
        other_hash(&fields, &hash)?;
        if let Some(issuer) = fields
            .next_element()
            .map_err(|cause| Error::encoding(cause, FIELD))?
        {
            // Table1(g) names complete-certificate-references specifically.
            // Retain the original hint before decoding it: malformed issuer
            // fields still exist and also receive their independent fault.
            if let Some(hints) = hints.as_mut() {
                hints
                    .try_push(issuer.span())
                    .map_err(|cause| Error::resource(cause, FIELD, issuer.span().start))?;
            }
            let reading = structured_cms::ess::IssuerSerialReading::read(&fields, &issuer, FIELD)?;
            let (_, faults) = reading.into_parts();
            fields
                .charge(1)
                .map_err(|cause| Error::encoding(cause, FIELD))?;
            if let Some(cause) = faults.into_iter().next() {
                return Err(Error::Cms(cause));
            }
        }
        end(&fields, FIELD)?;
    }
    Ok(())
}

fn other_hash(parent: &Reader<'_>, value: &Element<'_>) -> Result<()> {
    if value.tag() == Tag::primitive(universal::OCTET_STRING)
        || value.tag() == Tag::constructed(universal::OCTET_STRING)
    {
        Octets::read(parent, value, FIELD)?;
    } else {
        let mut fields = sequence(parent, value, FIELD)?;
        let identifier = next(&mut fields, FIELD)?;
        let algorithm = algorithm::read(&fields, &identifier, FIELD).map_err(Error::Pkix)?;
        let md5 = Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 2, 5]);
        fields
            .charge(
                1 + algorithm
                    .algorithm()
                    .as_bytes()
                    .len()
                    .min(md5.as_bytes().len()) as u64,
            )
            .map_err(|cause| Error::encoding(cause, FIELD))?;
        // EN319122-1 §6.2.1 forbids MD5 in actual digest use, including
        // advisory legacy references. OID recognition is not provider policy.
        // https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf
        if algorithm.algorithm() == md5 {
            return Err(Error::Syntax {
                code: structured_cms::ErrorCode::AlgorithmSyntax,
                field: "cades.legacy.digest",
                at: identifier.span().start,
            });
        }
        let hash = next(&mut fields, FIELD)?;
        Octets::read(&fields, &hash, FIELD)?;
        end(&fields, FIELD)?;
    }
    Ok(())
}

fn certificate_values<'d, W: Work>(
    parent: &Reader<'d>,
    value: &Element<'d>,
    property: Span,
    saved: &mut super::values::Values<'d, W>,
) -> Result<()> {
    let mut list = sequence(parent, value, FIELD)?;
    let enclosure = crate::source::Node::of(value.span());
    let mut ordinal = 0;
    while let Some(value) = list
        .next_element()
        .map_err(|cause| Error::encoding(cause, FIELD))?
    {
        let certificate = Certificate::read_element(&list, &value).map_err(Error::Pkix)?;
        saved
            .certificates
            .try_push(super::values::Located {
                property: crate::source::Node::of(property),
                enclosure,
                ordinal,
                value: certificate,
            })
            .map_err(|cause| Error::resource(cause, FIELD, value.span().start))?;
        ordinal += 1;
    }
    Ok(())
}

fn explicit<'a>(parent: &Reader<'a>, value: &Element<'a>, number: u32) -> Result<Reader<'a>> {
    if value.tag() != Tag::context(true, number) {
        return Err(syntax(FIELD, value.span().start));
    }
    let mut wrapper = parent
        .enter(value)
        .map_err(|cause| Error::encoding(cause, FIELD))?;
    let value = next(&mut wrapper, FIELD)?;
    end(&wrapper, FIELD)?;
    sequence(&wrapper, &value, FIELD)
}

fn next_choice(previous: &mut Option<u32>, value: &Element<'_>) -> Result<u32> {
    let Some(number) = value.tag().number() else {
        return Err(syntax(FIELD, value.span().start));
    };
    if number > 2
        || value.tag() != Tag::context(true, number)
        || previous.is_some_and(|previous| number <= previous)
    {
        return Err(syntax(FIELD, value.span().start));
    }
    *previous = Some(number);
    Ok(number)
}

fn revocation_values<'d, W: Work>(
    parent: &Reader<'d>,
    value: &Element<'d>,
    property: Span,
    saved: &mut super::values::Values<'d, W>,
) -> Result<()> {
    let mut fields = sequence(parent, value, FIELD)?;
    let enclosure = crate::source::Node::of(value.span());
    let mut previous = None;
    while let Some(value) = fields
        .next_element()
        .map_err(|cause| Error::encoding(cause, FIELD))?
    {
        let number = next_choice(&mut previous, &value)?;
        let mut entries = explicit(&fields, &value, number)?;
        if number == 2 {
            let (kind, values) = open_revocation(&mut entries)?;
            saved
                .other
                .try_push(super::values::OtherRevocation {
                    property: crate::source::Node::of(property),
                    kind,
                    enclosure: value,
                    values,
                })
                .map_err(|cause| Error::resource(cause, FIELD, value.span().start))?;
        } else {
            let mut ordinal = 0;
            while let Some(entry) = entries
                .next_element()
                .map_err(|cause| Error::encoding(cause, FIELD))?
            {
                if number == 0 {
                    let value =
                        CertificateList::read_element(&entries, &entry).map_err(Error::Pkix)?;
                    saved
                        .crls
                        .try_push(super::values::Located {
                            property: crate::source::Node::of(property),
                            enclosure,
                            ordinal,
                            value,
                        })
                        .map_err(|cause| Error::resource(cause, FIELD, entry.span().start))?;
                } else {
                    let value =
                        BasicResponse::read_element(&entries, &entry).map_err(Error::Pkix)?;
                    saved
                        .ocsp
                        .try_push(super::values::Located {
                            property: crate::source::Node::of(property),
                            enclosure,
                            ordinal,
                            value,
                        })
                        .map_err(|cause| Error::resource(cause, FIELD, entry.span().start))?;
                }
                ordinal += 1;
            }
        }
    }
    Ok(())
}

fn revocation_refs(parent: &Reader<'_>, value: &Element<'_>) -> Result<()> {
    let mut list = sequence(parent, value, FIELD)?;
    while let Some(value) = list
        .next_element()
        .map_err(|cause| Error::encoding(cause, FIELD))?
    {
        let mut fields = sequence(&list, &value, FIELD)?;
        let mut previous = None;
        while let Some(value) = fields
            .next_element()
            .map_err(|cause| Error::encoding(cause, FIELD))?
        {
            let number = next_choice(&mut previous, &value)?;
            let mut entries = explicit(&fields, &value, number)?;
            if number == 2 {
                open_revocation(&mut entries)?;
            } else {
                let list = next(&mut entries, FIELD)?;
                end(&entries, FIELD)?;
                let mut list = sequence(&entries, &list, FIELD)?;
                while let Some(entry) = list
                    .next_element()
                    .map_err(|cause| Error::encoding(cause, FIELD))?
                {
                    if number == 0 {
                        crl_reference(&list, &entry)?;
                    } else {
                        ocsp_reference(&list, &entry)?;
                    }
                }
            }
        }
    }
    Ok(())
}

fn crl_reference(parent: &Reader<'_>, value: &Element<'_>) -> Result<()> {
    let mut fields = sequence(parent, value, FIELD)?;
    let hash = next(&mut fields, FIELD)?;
    other_hash(&fields, &hash)?;
    if let Some(identifier) = fields
        .next_element()
        .map_err(|cause| Error::encoding(cause, FIELD))?
    {
        let mut identifier = sequence(&fields, &identifier, FIELD)?;
        let issuer = next(&mut identifier, FIELD)?;
        structured_pkix::name::read(&identifier, &issuer, FIELD).map_err(Error::Pkix)?;
        let time = next(&mut identifier, FIELD)?;
        time_value(&identifier, &time, universal::UTC_TIME)?;
        if !identifier.is_empty() {
            identifier
                .read_integer()
                .map_err(|cause| Error::encoding(cause, FIELD))?;
        }
        end(&identifier, FIELD)?;
    }
    end(&fields, FIELD)
}

fn ocsp_reference(parent: &Reader<'_>, value: &Element<'_>) -> Result<()> {
    let mut fields = sequence(parent, value, FIELD)?;
    let identifier = next(&mut fields, FIELD)?;
    let mut identifier = sequence(&fields, &identifier, FIELD)?;
    let responder = next(&mut identifier, FIELD)?;
    ResponderId::read_element(&identifier, &responder).map_err(Error::Pkix)?;
    let time = next(&mut identifier, FIELD)?;
    time_value(&identifier, &time, universal::GENERALIZED_TIME)?;
    end(&identifier, FIELD)?;
    if let Some(hash) = fields
        .next_element()
        .map_err(|cause| Error::encoding(cause, FIELD))?
    {
        other_hash(&fields, &hash)?;
    }
    end(&fields, FIELD)
}

fn time_value(parent: &Reader<'_>, value: &Element<'_>, number: u32) -> Result<()> {
    if value.tag() != Tag::primitive(number) && value.tag() != Tag::constructed(number) {
        return Err(syntax(FIELD, value.span().start));
    }
    // A reference uses its declared ASN.1 time under the producing BER/DER
    // rules. Embedded certificate/CRL/OCSP models retain their own DER profile.
    // Despite its module name, conforms follows parent.encoding(); it does
    // NOT reread under DER. BER useful times inherit VisibleString's
    // constructed OCTET STRING fragments (X.690 §§8.23, 8.25), which DER
    // alone forbids (§10.2). Forcing DER here would reject valid AnnexA data.
    // https://www.itu.int/rec/T-REC-X.690-202102-I/en
    structured_pkix::der::conforms(parent, value, FIELD).map_err(Error::Pkix)
}

fn open_revocation<'d>(fields: &mut Reader<'d>) -> Result<(Oid<'d>, crate::source::Value<'d>)> {
    let kind = fields
        .read_oid()
        .map_err(|cause| Error::encoding(cause, FIELD))?;
    let values = next(fields, FIELD)?;
    end(fields, FIELD)?;
    let original = crate::source::Value::of(fields, values, FIELD);
    let mut values = sequence(fields, &values, FIELD)?;
    while let Some(value) = values
        .next_element()
        .map_err(|cause| Error::encoding(cause, FIELD))?
    {
        // AnnexD defines a SEQUENCE OF open values. Their OID-owned semantics
        // remain outside this format; original ASN.1 syntax is still accounted.
        structured_pkix::der::conforms(&values, &value, FIELD).map_err(Error::Pkix)?;
    }
    Ok((kind, original))
}