Skip to main content

structured_pkix/
der.rs

1//! Holding a range to the distinguished rules.
2//!
3//! Certificates are not the only structure whose schema fixes its encoding
4//! regardless of the envelope carrying it. A signed message is BER, and the
5//! attributes inside it that a signature covers "MUST be DER encoded, even if
6//! the rest of the structure is BER encoded" (RFC 5652 5.3). The walk that
7//! decides that question already exists here, so it is exposed rather than
8//! written a second time: two answers to what counts as DER is one answer more
9//! than a product can defend.
10
11use crate::error::{Error, ErrorCode, Result};
12use structured_asn1::{Element, Reader};
13
14/// Whether a range and everything under it is DER.
15///
16/// Definite lengths in their shortest form, primitive encodings where the
17/// distinguished rules require them, assigned universal types, and the members
18/// of a set in ascending order of their encodings (X.690 11.6).
19///
20/// The reader decides which rules apply to the outermost header, so a caller
21/// holding a range to DER inside a BER document reads it again under DER first;
22/// [`structured_asn1::Reader::reread`] is what that is for.
23///
24/// # Errors
25///
26/// Reports which rule was broken and where.
27pub fn conforms<'a>(parent: &Reader<'a>, element: &Element<'a>, field: &'static str) -> Result<()> {
28    crate::name::walk_der(parent, element, field, crate::name::Strings::Checked)
29}
30
31/// Validates the contents of a schema-selected IMPLICIT BIT STRING.
32/// The enclosing schema checks its context tag; this reuses the same iterative
33/// BER fragment/padding kernel as universal BIT STRINGs. DER requires primitive.
34pub fn implicit_bit_string<'a>(
35    parent: &Reader<'a>,
36    element: &Element<'a>,
37    field: &'static str,
38) -> Result<()> {
39    if !crate::name::segments::implicit(parent, element, field, true)? {
40        return Err(Error::new(
41            ErrorCode::MalformedValue,
42            field,
43            element.span().start,
44        ));
45    }
46    Ok(())
47}
48
49/// Whether two members of a set are in the order the distinguished rules put
50/// them in.
51///
52/// "The encodings of the component values of a set-of value shall appear in
53/// ascending order" (X.690 11.6), comparing octet by octet with the shorter
54/// encoding treated as though padded with zeros.
55///
56/// It is separate from [`conforms`] because a set is not always written under
57/// a set's own tag: a signed message writes its attributes under a context tag
58/// and signs them under `SET OF`, so the ordering is the schema's to check
59/// where the tag no longer says so.
60///
61/// `parent` supplies the current execution account and original parser-local
62/// cumulative ceiling. Before comparison, one work unit per possible octet
63/// pair is admitted: the longer length, because X.690 compares the shorter
64/// encoding with virtual zero padding. A minimum of one unit covers an empty
65/// comparison. This is an upper bound; an unequal pair may stop the walk early.
66/// `parent` must belong to the session and source that produced `next`; this
67/// is a caller precondition, not a provenance check.
68///
69/// # Errors
70/// Returns a resource refusal at `next`'s original offset before comparing
71/// bytes. `Ok(false)` means incorrect order, independently of resource errors.
72pub fn set_ordered(
73    parent: &Reader<'_>,
74    previous: &[u8],
75    next: &Element<'_>,
76    field: &'static str,
77) -> Result<bool> {
78    let work = previous.len().max(next.as_bytes().len()).max(1) as u64;
79    parent
80        .charge(work)
81        .map_err(|error| Error::new(ErrorCode::Encoding(error.code()), field, next.span().start))?;
82    Ok(crate::name::der_set_ordered(previous, next.as_bytes()))
83}
84
85/// Visits primitive fragments using the SAME iterative BER BIT STRING kernel
86/// as validation. Only final nested padding is permitted (X.690 ยง8.6.4).
87/// The caller may retain original borrowed bits/spans; no payload is joined.
88/// A later error does not undo side effects of earlier visitor calls.
89/// DER admits only the primitive form. Current/origin work and depth apply.
90pub fn bit_fragments<'a>(
91    parent: &structured_asn1::ScopedReader<'a, '_>,
92    element: &Element<'a>,
93    field: &'static str,
94    visitor: impl FnMut(Element<'a>, structured_asn1::BitString<'a>) -> Result<()>,
95) -> Result<()> {
96    crate::name::segments::bit_fragments(parent, element, field, visitor)
97}