pkix-path 0.7.1

RFC 5280 X.509 certificate path validation — pure Rust, no_std
Documentation
//! Where algorithm support is enforced, and where it deliberately is not.
//!
//! [`TrustAnchor::from_cert`] applies the CA profile: what the certificate
//! asserts about what it may be used for. It does not ask whether this
//! build can verify a signature made with the key, and it could not — it
//! takes no [`pkix_path::SignatureVerifier`], and the supported set is a
//! property of the verifier rather than of the certificate. So a
//! certificate whose key this build cannot use still becomes an anchor, and
//! the limit is reported at validation.
//!
//! That split is deliberate, and it is the opposite of the choice made for
//! a BER-encoded `cA` boolean (see `ber_boolean.rs`), so the distinction is
//! worth stating:
//!
//! * A BER boolean means **the certificate's own claim cannot be read**.
//!   The profile check needs `cA` and cannot get it, so refusing is the
//!   only way to avoid guessing a security-relevant value.
//! * An unsupported key algorithm means **everything the certificate says
//!   is legible and satisfied** — `cA=TRUE`, critical, `keyCertSign`
//!   permitted. What is missing is a capability of this build, not a fact
//!   about the certificate. `SignatureVerifier` is public, so a caller may
//!   well supply one that handles the algorithm; refusing at construction
//!   would make that caller's valid configuration impossible to express.
//!
//! Refuse when the certificate is unreadable; do not refuse when the
//! limitation is ours.
//!
//! # What this costs, and what makes it tolerable
//!
//! A caller loading `third_party/trust-stores/ru-national/` gets eight
//! anchors, six of which cannot verify anything in this build, with an
//! empty `rejected` list. The cost is discoverability, and what keeps it
//! bounded is that the eventual error is specific:
//! [`Error::SignatureNotVerified`] carrying
//! [`VerificationErrorKind::UnsupportedAlgorithm`], naming the chain index.
//! Not `NoTrustedPath`, not `SignatureInvalid`, not a panic. A caller told
//! "unsupported algorithm at index 0" can act; one told "no path" cannot.
//!
//! That is the contract these tests exist to defend. It was untested, which
//! for a behaviour justified by the quality of its error message is the
//! wrong way round.
//!
//! # The fixtures
//!
//! Two Головной удостоверяющий центр roots — Russia's Head Certification
//! Authority, the apex of its accredited-CA system — from the vendored
//! `ru-national` store, on the two different GOST arcs:
//!
//! * `fixtures/ru-root-gost2012.der`, SHA-256 prefix `4bb37cc7c0ff4bf2`.
//!   `CN=Минцифры России`, key GOST R 34.10-2012 (1.2.643.7.1.1.1.1),
//!   signature 1.2.643.7.1.1.3.2, valid 2022-01-08 to 2040-01-08.
//! * `fixtures/ru-root-gost2001.der`, SHA-256 prefix `4e450e4971f2d77d`.
//!   `CN=Головной удостоверяющий центр`, key GOST R 34.10-2001
//!   (1.2.643.2.2.19) on the older CryptoPro arc, signature 1.2.643.2.2.3,
//!   valid 2012-07-20 to 2027-07-17.
//!
//! Both are real, in-window national roots. OpenSSL without a GOST
//! provider cannot even load their public keys.

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

use der::Decode as _;
use pkix_path::{DefaultVerifier, Error, TrustAnchor, ValidationPolicy};
// Only the `cfg(not(feature = "gost"))` arm of
// `a_path_through_a_gost_anchor_validates` names this: with the feature
// on the path validates, so there is no error kind left to match.
#[cfg(not(feature = "gost"))]
use pkix_path::VerificationErrorKind;
use x509_cert::Certificate;

const GOST_2012: &[u8] = include_bytes!("fixtures/ru-root-gost2012.der");
const GOST_2001: &[u8] = include_bytes!("fixtures/ru-root-gost2001.der");

/// GOST R 34.10-2012 public key.
const OID_GOST_2012_KEY: &str = "1.2.643.7.1.1.1.1";

/// GOST R 34.10-2001 public key, CryptoPro arc.
const OID_GOST_2001_KEY: &str = "1.2.643.2.2.19";

/// `(fixture, key OID, notBefore, notAfter)`.
///
/// Validity oracles, computed outside this workspace with
/// `date -u -d '<the date openssl x509 -dates prints>' +%s`:
/// 2022-01-08T13:32:39Z, 2040-01-08T13:32:39Z, 2012-07-20T12:31:14Z,
/// 2027-07-17T12:31:14Z.
const ROOTS: &[(&[u8], &str, u64, u64)] = &[
    (GOST_2012, OID_GOST_2012_KEY, 1_641_648_759, 2_209_642_359),
    (GOST_2001, OID_GOST_2001_KEY, 1_342_787_474, 1_815_827_474),
];

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

/// The fixtures really carry GOST keys on the two arcs, and really are
/// certificates this build cannot verify.
///
/// The premise guard. If a refresh replaced either with an RSA root, every
/// test below would pass while testing nothing: the anchor would build and
/// the path would validate, and "builds an anchor" would no longer be the
/// interesting half.
#[test]
fn the_fixtures_carry_gost_keys_on_the_two_arcs() {
    for (der, expected_oid, _, _) in ROOTS {
        let cert = cert(der);
        let oid = cert
            .tbs_certificate()
            .subject_public_key_info()
            .algorithm
            .oid
            .to_string();
        assert_eq!(
            oid, *expected_oid,
            "the fixture should carry the GOST key algorithm it was chosen for"
        );
    }
    assert_ne!(
        OID_GOST_2012_KEY, OID_GOST_2001_KEY,
        "the two fixtures should exercise different arcs"
    );
}

/// A certificate whose key algorithm this build cannot use still becomes a
/// trust anchor.
///
/// The deliberate half. Would catch a well-meaning change that screened
/// anchors against the verifier's supported set at construction — which
/// `from_cert` cannot do correctly anyway, since it is given no verifier
/// and a caller may supply one that handles GOST.
#[test]
fn a_gost_root_becomes_a_trust_anchor() {
    for (der, oid, not_before, not_after) in ROOTS {
        let anchor = TrustAnchor::from_cert(cert(der)).unwrap_or_else(|e| {
            panic!("the {oid} root satisfies the CA profile and should build: {e:?}")
        });
        assert_eq!(
            anchor.validity_unix,
            (*not_before, *not_after),
            "the anchor should carry the certificate's own validity"
        );
    }
}

/// A path through a GOST anchor now VALIDATES.
///
/// This test asserted the opposite until `pkix_path::gost_r3410` landed:
/// that a GOST path failed with `SignatureNotVerified { reason:
/// UnsupportedAlgorithm }`, naming the algorithm so a caller learned
/// precisely why rather than being told their trust store held no path.
/// That was the right behaviour for a build with no GOST, and the
/// argument it justified -- accept the anchor, explain at the point it
/// matters -- is unchanged.
///
/// What changed is that there is no longer anything to explain. These
/// are the Russian national roots, and a one-certificate path through
/// each of them verifies end to end: both GOST generations, the
/// CryptoPro-A curve, and RFC 4491's two disagreeing byte orders.
///
/// Kept pointed at `validate_path` rather than at the verifier directly,
/// because that is the layer the old assertion was about and the layer a
/// caller uses.
#[test]
fn a_path_through_a_gost_anchor_validates() {
    for (der, oid, not_before, _) in ROOTS {
        let anchor = TrustAnchor::from_cert(cert(der)).expect("builds");
        let policy = ValidationPolicy::new(not_before + 1);
        let result = pkix_path::validate_path(&[cert(der)], &[anchor], &policy, &DefaultVerifier);

        #[cfg(feature = "gost")]
        assert!(
            result.is_ok(),
            "{oid}: a path through a Russian national root should validate \
             now that GOST R 34.10 is implemented; got {result:?}"
        );
        // Without the feature the original assertion still holds, and
        // still matters: the caller must be told the algorithm is
        // unsupported rather than that no path exists.
        #[cfg(not(feature = "gost"))]
        assert_eq!(
            result.as_ref().err(),
            Some(&Error::SignatureNotVerified {
                index: 0,
                reason: VerificationErrorKind::UnsupportedAlgorithm,
            }),
            "{oid}: without `gost`, the failure must still name the \
             unsupported algorithm, got: {result:?}"
        );
    }
}

/// It is specifically not reported as an invalid signature.
///
/// Pinned apart from the test above because the difference is what a
/// caller acts on. `SignatureInvalid` says the issuer did not sign this
/// certificate — a statement about the certificates, and grounds for
/// suspicion. `SignatureNotVerified` with an unsupported algorithm says
/// this build cannot tell. Conflating them would turn a missing feature
/// into an accusation.
#[test]
fn an_unsupported_algorithm_is_not_reported_as_an_invalid_signature() {
    for (der, oid, not_before, _) in ROOTS {
        let anchor = TrustAnchor::from_cert(cert(der)).expect("builds");
        let policy = ValidationPolicy::new(not_before + 1);
        let result = pkix_path::validate_path(&[cert(der)], &[anchor], &policy, &DefaultVerifier);

        assert!(
            !matches!(result, Err(Error::SignatureInvalid { .. })),
            "{oid}: not being able to check a signature is not the same as \
             the signature being wrong"
        );
        assert!(
            !matches!(result, Err(Error::NoTrustedPath)),
            "{oid}: NoTrustedPath would hide that an anchor matched and \
             could not be used"
        );
    }
}

/// Loading such a root through a bundle reports nothing as rejected.
///
/// The cost of the design, pinned so it is a stated consequence rather
/// than a surprise: `is_clean` is true and `rejected` is empty, because
/// nothing about these certificates is wrong. A caller counting usable
/// anchors from `anchors.len()` will over-count by six on Russia's store,
/// and the only way to find out is to validate.
#[test]
fn a_gost_root_is_not_reported_as_a_rejected_anchor() {
    for (der, oid, _, _) in ROOTS {
        let anchor = TrustAnchor::from_cert(cert(der));
        assert!(
            anchor.is_ok(),
            "{oid}: nothing about this certificate's own claims is wrong"
        );
    }
}