pkix-path 0.7.0

RFC 5280 X.509 certificate path validation — pure Rust, no_std
Documentation
//! A `BOOLEAN` that is valid BER and invalid DER, on a sovereign root.
//!
//! X.690 §11.1 requires a DER `BOOLEAN` holding TRUE to have every bit of
//! its content octet set — `0xFF`. BER permits any non-zero octet, and
//! RFC 5280 §4.1 requires certificates to be DER-encoded, so `0x01` is a
//! non-conforming spelling of TRUE. A strict parser cannot read it; every
//! lenient one can, and agrees it means TRUE.
//!
//! # The fixture
//!
//! `fixtures/ua-csca-ber-boolean.der` is Ukraine's ePassport Country
//! Signing CA, taken from the vendored ICAO master list at
//! `third_party/trust-stores/icao-csca/`. SHA-256 of the DER:
//! `6a1f5136b12017c1721cf547cc8c5aa5d11383f14cdf2443f94817924f6b6016`.
//! Subject: `C=UA, serialNumber=UA-16286441-0001, O=Polygraph combine
//! UKRAINA for securities production, OU=SCPD PCU, CN=CSCA-UKRAINE`.
//!
//! Its `basicConstraints` value is `30 06 01 01 01 02 01 00`:
//!
//! ```text
//! 30 06        SEQUENCE, 6 octets
//!    01 01 01  BOOLEAN, 1 octet, content 0x01   <- BER TRUE, not DER TRUE
//!    02 01 00  INTEGER, 1 octet, value 0        <- pathLenConstraint 0
//! ```
//!
//! All five of its extensions are otherwise sound, and `openssl x509`
//! prints `CA:TRUE, pathlen:0` without complaint. Three certificates among
//! the 3,430 vendored under `third_party/trust-stores/` encode `cA` this
//! way — these are two eIDAS roots and this one — out of 1,923 that encode
//! the boolean at all.
//!
//! # Why a distinct defect, rather than `MalformedExtension`
//!
//! The certificate is refused either way: honouring a non-DER encoding
//! would mean concluding `cA` is TRUE on the strength of an encoding the
//! profile forbids. What changes is what the caller is told. A malformed
//! extension is unreadable and might say anything. This one is readable,
//! says TRUE, is accepted today by the peers a deployment interoperates
//! with, and becomes conformant the moment its issuer re-encodes it. Those
//! are different situations and they warrant different answers.

#![cfg(feature = "p256")]

use der::Decode as _;
use pkix_path::{AnchorDefect, Error, TrustAnchor};
use x509_cert::Certificate;

const UA_CSCA_DER: &[u8] = include_bytes!("fixtures/ua-csca-ber-boolean.der");

/// The fixture's `basicConstraints` extnValue, `cA=TRUE` in BER.
const BER_BASIC_CONSTRAINTS: [u8; 8] = [0x30, 0x06, 0x01, 0x01, 0x01, 0x02, 0x01, 0x00];

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

/// The fixture still encodes `cA` as BER `0x01`, and exactly once.
///
/// The premise guard, asserted on the DER because the encoding is the
/// subject. "Exactly once" matters for the mutation in
/// [`a_genuinely_malformed_basicconstraints_is_still_malformed`], which
/// rewrites this byte string and would silently patch the wrong place if it
/// appeared twice.
#[test]
fn the_fixture_encodes_ca_true_as_a_ber_boolean() {
    let occurrences = UA_CSCA_DER
        .windows(BER_BASIC_CONSTRAINTS.len())
        .filter(|w| *w == BER_BASIC_CONSTRAINTS)
        .count();
    assert_eq!(
        occurrences, 1,
        "the fixture should carry exactly one BER-encoded basicConstraints"
    );
    assert_eq!(
        BER_BASIC_CONSTRAINTS[4], 0x01,
        "the cA content octet should be 0x01, which is BER TRUE and not DER TRUE"
    );
}

/// The anchor is refused, and refused *as* a non-DER boolean.
///
/// Would catch the behaviour this replaced, where the same certificate came
/// back as `MalformedExtension` — true, but telling a caller that an
/// extension could not be parsed when the real situation is that it was
/// parsed by everyone else and says TRUE. Pinned to the variant rather than
/// to "some error" for exactly that reason.
#[test]
fn a_ber_encoded_ca_boolean_is_refused_as_such() {
    let result = TrustAnchor::from_cert(cert_from(UA_CSCA_DER));

    assert_eq!(
        result.as_ref().err(),
        Some(&Error::TrustAnchorRejected {
            defect: AnchorDefect::NonDerBoolean,
        }),
        "a BER cA boolean should be named, not reported as unparseable, got: {result:?}"
    );
}

/// A `basicConstraints` that is genuinely unreadable is still
/// `MalformedExtension`.
///
/// The negative half, and the one that gives the test above its meaning: a
/// detector that answered "non-DER boolean" for any unparseable
/// `basicConstraints` would pass that test while destroying the
/// distinction it exists to draw.
///
/// The fixture's 8-byte extnValue is replaced in place with `30 06 05 00 05
/// 00 05 00` — a `SEQUENCE` of `NULL`s, the same length, so every enclosing
/// length stays correct and the certificate still decodes. Its first member
/// is tag `0x05` rather than `0x01`, so it is not a boolean of any
/// encoding. The signature no longer matches the body, which is irrelevant
/// here: `from_cert` applies the CA profile and verifies nothing.
#[test]
fn a_genuinely_malformed_basicconstraints_is_still_malformed() {
    let position = UA_CSCA_DER
        .windows(BER_BASIC_CONSTRAINTS.len())
        .position(|w| w == BER_BASIC_CONSTRAINTS)
        .expect("the fixture's basicConstraints should be findable");

    let mut mutated = UA_CSCA_DER.to_vec();
    mutated[position..position + 8]
        .copy_from_slice(&[0x30, 0x06, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00]);

    let result = TrustAnchor::from_cert(cert_from(&mutated));

    assert_eq!(
        result.as_ref().err(),
        Some(&Error::TrustAnchorRejected {
            defect: AnchorDefect::MalformedExtension,
        }),
        "a SEQUENCE of NULLs is not a boolean in any encoding, so this is \
         unparseable rather than merely non-canonical, got: {result:?}"
    );
}

/// Correcting the encoding to DER makes the same certificate a usable
/// anchor.
///
/// This is the claim that justifies refusing it in the first place while
/// still naming the defect: nothing about the certificate is wrong except
/// the encoding of one octet, and the fix belongs to its issuer. Would also
/// catch a check that refused this root for some *other* reason as well,
/// which would make the distinction academic.
#[test]
fn the_same_certificate_with_a_der_boolean_is_accepted() {
    let position = UA_CSCA_DER
        .windows(BER_BASIC_CONSTRAINTS.len())
        .position(|w| w == BER_BASIC_CONSTRAINTS)
        .expect("the fixture's basicConstraints should be findable");

    let mut corrected = UA_CSCA_DER.to_vec();
    corrected[position + 4] = 0xFF;

    let anchor = TrustAnchor::from_cert(cert_from(&corrected))
        .expect("with cA encoded as DER TRUE, this root meets the anchor profile");

    // Oracle: `date -u -d 'Mar 24 12:57:40 2015' +%s` -> 1427201860 and
    // `date -u -d 'Jun 24 12:57:40 2030' +%s` -> 1908536260, both computed
    // outside this workspace and round-tripped back to the dates
    // `openssl x509 -dates` prints for the fixture.
    assert_eq!(
        anchor.validity_unix,
        (1_427_201_860, 1_908_536_260),
        "the corrected certificate is the same one, so its validity is unchanged"
    );
}