pkix-path 0.7.0

RFC 5280 X.509 certificate path validation — pure Rust, no_std
Documentation
//! `NumericString` attribute values in RFC 5280 §7.1 name comparison.
//!
//! `DirectoryString` (§4.1.2.4) admits `PrintableString`, `UTF8String`,
//! `TeletexString`, `UniversalString` and `BMPString` — not
//! `NumericString`. But a `Name` is an `RDNSequence` of `AttributeTypeAndValue`
//! whose `value` is `ANY`, and an attribute type outside the standard set
//! defines its own syntax. Russia's registry identifiers do exactly that:
//! `OGRN` (1.2.643.100.1) and the legal-entity `INN` (1.2.643.100.4) are
//! `NumericString`, legitimately, and six of the eight roots in
//! `third_party/trust-stores/ru-national/` carry them.
//!
//! X.680 restricts `NumericString` to the digits `0`–`9` and SPACE, so its
//! content is ASCII and the same normalization the other ASCII string types
//! get applies without transcoding. LDAP agrees: the `Numeric String`
//! syntax has its own equality rule, `numericStringMatch`, which RFC 4517
//! §4.2.22 defines over the RFC 4518 preparation that §7.1 points at —
//! including insignificant-space handling.
//!
//! # The fixtures
//!
//! Both are the subject `Name` of the Russian Ministry of Digital
//! Development's root, lifted from `ru-national` and 319 bytes each:
//!
//! * `fixtures/ru-dn-numericstring.der` — as published. SHA-256 prefix
//!   `0786ebfbeee61151`.
//! * `fixtures/ru-dn-printablestring.der` — byte-identical except that the
//!   two `NumericString` tags are `PrintableString`. SHA-256 prefix
//!   `8368e7c9b40d60c3`.
//!
//! The re-tagging is legitimate: digits are in the `PrintableString`
//! character set, so the variant is a well-formed encoding of the same
//! name, and it is the encoding a different CA in the same hierarchy could
//! reasonably emit. That is the case §7.1 exists for — China's ePassport
//! CSCA is already in the corpus encoding one name as `UTF8String` in its
//! issuer field and `PrintableString` in its subject field (see
//! `names_match_mixed_string_types.rs`).
//!
//! The DN is a good specimen beyond the point at issue: Cyrillic
//! `UTF8String` values, an `IA5String` `emailAddress`, a `PrintableString`
//! country, and the two `NumericString` identifiers.

use der::{Decode as _, Encode as _};
use x509_cert::name::Name;

const NUMERIC_DER: &[u8] = include_bytes!("fixtures/ru-dn-numericstring.der");
const PRINTABLE_DER: &[u8] = include_bytes!("fixtures/ru-dn-printablestring.der");

/// `NumericString`, tag 0x12.
const TAG_NUMERIC_STRING: u8 = 0x12;

/// `PrintableString`, tag 0x13.
const TAG_PRINTABLE_STRING: u8 = 0x13;

/// The OGRN value, used to build a genuinely-different name.
const OGRN: &[u8] = b"1047702026701";

fn name(der: &[u8]) -> Name {
    Name::from_der(der).expect("the fixture should be a valid Name")
}

/// The two fixtures differ in exactly two bytes, and both are the string
/// tag of an attribute value.
///
/// The premise guard. If they differed in content as well as encoding, the
/// equality test below would be asserting something much weaker, and if
/// they did not differ at all it would be comparing a name to itself.
#[test]
fn the_two_fixtures_differ_only_in_two_string_tags() {
    assert_eq!(
        NUMERIC_DER.len(),
        PRINTABLE_DER.len(),
        "re-tagging must not change the encoded length"
    );

    let differing: Vec<usize> = NUMERIC_DER
        .iter()
        .zip(PRINTABLE_DER.iter())
        .enumerate()
        .filter(|(_, (a, b))| a != b)
        .map(|(i, _)| i)
        .collect();

    assert_eq!(
        differing.len(),
        2,
        "exactly two bytes should differ, one per NumericString value; \
         differences at {differing:?}"
    );
    for at in differing {
        assert_eq!(
            (NUMERIC_DER[at], PRINTABLE_DER[at]),
            (TAG_NUMERIC_STRING, TAG_PRINTABLE_STRING),
            "byte {at} should be a NumericString tag becoming PrintableString"
        );
    }
}

/// A `NumericString` name is equal to itself.
///
/// Trivial, and worth pinning: before `NumericString` reached the string
/// path it was compared by tag and raw bytes, which also gets this right.
/// So this test passing says nothing about the fix — it is here so that a
/// change which broke the easy case could not hide behind the interesting
/// one below.
#[test]
fn a_numericstring_name_equals_itself() {
    let n = name(NUMERIC_DER);
    assert!(
        pkix_path::names_match(&n, &n),
        "a name must equal itself whatever its attribute encodings"
    );
}

/// The same name is equal whether its registry identifiers are
/// `NumericString` or `PrintableString`.
///
/// This is the claim. Before the fix `NumericString` fell outside the
/// string dispatch and was compared by tag plus raw bytes, so these two
/// names — the same name, differing in two tag bytes — compared as
/// different. The failure mode was a false negative: a path that should
/// chain would not, and the symptom would be `NoTrustedPath` with nothing
/// to indicate that an encoding was the reason.
///
/// Would catch a dispatch that handles `NumericString` in only one
/// direction, since the comparison would then depend on argument order —
/// which [`the_comparison_is_symmetric`] pins separately.
#[test]
fn numericstring_and_printablestring_hold_the_same_name() {
    assert!(
        pkix_path::names_match(&name(NUMERIC_DER), &name(PRINTABLE_DER)),
        "§7.1 exists so that re-encoding an attribute value does not break \
         chaining; digits are digits in either string type"
    );
}

/// The comparison does not depend on argument order.
#[test]
fn the_comparison_is_symmetric() {
    let a = name(NUMERIC_DER);
    let b = name(PRINTABLE_DER);
    assert_eq!(
        pkix_path::names_match(&a, &b),
        pkix_path::names_match(&b, &a),
        "§7.1 name comparison must be symmetric"
    );
}

/// A different registry number is a different name.
///
/// The negative half, and the one that stops the test above from being
/// satisfied by a comparison that ignores `NumericString` content
/// altogether — which is exactly the shape a careless dispatch addition
/// could take. One digit of the OGRN is changed, so the two names differ
/// in content while agreeing in every encoding.
#[test]
fn a_different_numericstring_value_is_a_different_name() {
    let occurrences = NUMERIC_DER
        .windows(OGRN.len())
        .filter(|w| *w == OGRN)
        .count();
    assert_eq!(
        occurrences, 1,
        "the OGRN digits should appear once, so the substitution below is unambiguous"
    );

    let at = NUMERIC_DER
        .windows(OGRN.len())
        .position(|w| w == OGRN)
        .expect("the OGRN should be findable");
    let mut altered = NUMERIC_DER.to_vec();
    altered[at] = b'9'; // 1047702026701 -> 9047702026701

    assert!(
        !pkix_path::names_match(&name(NUMERIC_DER), &name(&altered)),
        "two different registry numbers must not compare equal"
    );
}

/// Re-encoding a parsed `Name` is byte-identical, so the fixtures really do
/// round-trip and the comparison is being handed what is on disk.
///
/// Guards against a fixture that only appears to differ because the parser
/// normalised something on the way in.
#[test]
fn both_fixtures_round_trip_to_their_own_bytes() {
    for (label, der) in [("numeric", NUMERIC_DER), ("printable", PRINTABLE_DER)] {
        let encoded = name(der).to_der().expect("a parsed Name should re-encode");
        assert_eq!(
            encoded, der,
            "{label} fixture should re-encode to its own bytes"
        );
    }
}