utility-pki 0.1.0

TLS and certificate profiles of the German energy sector (BDEW AS4, BSI TR-03116-3, BSI TR-02102-2) as Rust data: check sessions, SM-PKI certificates and OpenSSL configurations
Documentation
//! A security profile: what a standard allows for TLS and certificates, as data.

use core::time::Duration;

use crate::cert::CertRules;
use crate::ids::{CipherSuite, NamedGroup, SignatureScheme, TlsVersion};

/// A requirement level, as the standard words it (RFC 2119; German texts use MUSS,
/// SOLLTE, KANN, SOLLTE NICHT, DARF NICHT).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Level {
    /// MUST / MUSS.
    Must,
    /// SHOULD / SOLLTE, EMPFOHLEN.
    Should,
    /// MAY / KANN, or the standard does not say.
    May,
    /// SHOULD NOT / SOLLTE NICHT.
    ShouldNot,
    /// MUST NOT / DARF NICHT.
    MustNot,
}

/// Which items of one kind (suites, groups, schemes, keys) a profile allows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Allowed<T: 'static> {
    /// The profile does not restrict this item.
    Any,
    /// Only these items. `required` must be supported by a conforming implementation;
    /// `optional` may be. Anything else must not be used.
    Only {
        /// Mandatory to support.
        required: &'static [T],
        /// Allowed, not mandatory (SHOULD or MAY).
        optional: &'static [T],
    },
}

impl<T: PartialEq + Copy> Allowed<T> {
    /// Whether `item` may be used.
    pub fn allows(&self, item: &T) -> bool {
        match self {
            Self::Any => true,
            Self::Only { required, optional } => required.contains(item) || optional.contains(item),
        }
    }

    /// The items that must be supported.
    pub const fn required(&self) -> &'static [T] {
        match self {
            Self::Any => &[],
            Self::Only { required, .. } => required,
        }
    }

    /// The items that may be supported but need not be.
    pub const fn optional(&self) -> &'static [T] {
        match self {
            Self::Any => &[],
            Self::Only { optional, .. } => optional,
        }
    }

    /// Every allowed item, required first. Empty for [`Allowed::Any`].
    pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
        let (required, optional): (&[T], &[T]) = match self {
            Self::Any => (&[], &[]),
            Self::Only { required, optional } => (required, optional),
        };
        required.iter().chain(optional).copied()
    }
}

/// The rules for one TLS version.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VersionRules {
    /// Whether this version must be supported ([`Level::Must`]) or may be ([`Level::Should`],
    /// [`Level::May`]).
    pub support: Level,
    /// Cipher suites.
    pub cipher_suites: Allowed<CipherSuite>,
    /// Key-exchange groups.
    pub groups: Allowed<NamedGroup>,
    /// Signature schemes in the handshake (`signature_algorithms`, CertificateVerify).
    pub signature_schemes: Allowed<SignatureScheme>,
    /// Signature schemes in certificates (`signature_algorithms_cert`).
    pub cert_signature_schemes: Allowed<SignatureScheme>,
}

/// An elliptic curve of a certificate key.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Curve {
    /// NIST P-256 (secp256r1).
    P256,
    /// NIST P-384 (secp384r1).
    P384,
    /// NIST P-521 (secp521r1).
    P521,
    /// brainpoolP256r1 (RFC 5639).
    BrainpoolP256r1,
    /// brainpoolP384r1 (RFC 5639).
    BrainpoolP384r1,
    /// brainpoolP512r1 (RFC 5639).
    BrainpoolP512r1,
}

impl Curve {
    /// The curve with this object identifier, given as the DER content bytes (what an
    /// X.509 parser returns for `namedCurve`).
    pub fn from_oid(oid: &[u8]) -> Option<Self> {
        Some(match oid {
            [0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07] => Self::P256,
            [0x2B, 0x81, 0x04, 0x00, 0x22] => Self::P384,
            [0x2B, 0x81, 0x04, 0x00, 0x23] => Self::P521,
            [0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07] => Self::BrainpoolP256r1,
            [0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B] => Self::BrainpoolP384r1,
            [0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D] => Self::BrainpoolP512r1,
            _ => return None,
        })
    }
}

impl core::fmt::Display for Curve {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(match self {
            Self::P256 => "P-256",
            Self::P384 => "P-384",
            Self::P521 => "P-521",
            Self::BrainpoolP256r1 => "brainpoolP256r1",
            Self::BrainpoolP384r1 => "brainpoolP384r1",
            Self::BrainpoolP512r1 => "brainpoolP512r1",
        })
    }
}

/// The kind and size of a certificate's public key.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PublicKey {
    /// RSA with this modulus length in bits.
    Rsa(u16),
    /// ECDSA on this curve.
    Ec(Curve),
    /// Ed25519.
    Ed25519,
}

impl core::fmt::Display for PublicKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Rsa(bits) => write!(f, "RSA-{bits}"),
            Self::Ec(curve) => write!(f, "ECDSA {curve}"),
            Self::Ed25519 => f.write_str("Ed25519"),
        }
    }
}

/// A rule a certificate key must meet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyRule {
    /// RSA with at least this many bits.
    RsaMin(u16),
    /// ECDSA on this curve.
    Ec(Curve),
    /// Ed25519.
    Ed25519,
}

impl KeyRule {
    /// Whether `key` satisfies this rule.
    pub const fn accepts(self, key: PublicKey) -> bool {
        match (self, key) {
            (Self::RsaMin(min), PublicKey::Rsa(bits)) => bits >= min,
            (Self::Ec(want), PublicKey::Ec(have)) => want as u8 == have as u8,
            (Self::Ed25519, PublicKey::Ed25519) => true,
            _ => false,
        }
    }
}

/// How certificate revocation is checked.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Revocation {
    /// The profile does not say.
    Unspecified,
    /// Must be checked, by CRL only (no OCSP).
    CrlRequired,
    /// Must be checked, by CRL or OCSP.
    Required,
}

/// A TLS and certificate profile from one standard.
///
/// Every field is what the cited text says, no more: a deployment may be stricter.
/// Rules a negotiated session cannot show are in [`Profile::notes`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Profile {
    /// Short stable identifier, e.g. `"bdew-as4"`.
    pub id: &'static str,
    /// Human-readable name.
    pub name: &'static str,
    /// The primary texts, each with version and date, that every rule below comes from.
    pub sources: &'static [&'static str],
    /// TLS 1.2 rules, or `None` if the profile does not allow TLS 1.2.
    pub tls12: Option<VersionRules>,
    /// TLS 1.3 rules, or `None` if the profile does not allow TLS 1.3.
    pub tls13: Option<VersionRules>,
    /// What the certificates of both sides must meet.
    pub cert: CertRules,
    /// Both sides must present a certificate.
    pub mutual_auth: bool,
    /// Revocation checking.
    pub revocation: Revocation,
    /// Longest TLS session, including resumptions, before a full handshake.
    pub max_session_lifetime: Option<Duration>,
    /// Encrypt-then-MAC (RFC 7366) with CBC suites.
    pub encrypt_then_mac: Level,
    /// Extended Master Secret (RFC 7627) in TLS 1.2.
    pub extended_master_secret: Level,
    /// TLS 1.2 renegotiation.
    pub renegotiation: Level,
    /// TLS 1.3 0-RTT early data.
    pub early_data: Level,
    /// Server Name Indication (RFC 6066).
    pub sni: Level,
    /// Rules a session check cannot see (key usage, SAN content, CRL timing). For people
    /// building the configuration.
    pub notes: &'static [&'static str],
}

impl Profile {
    /// The rules for `version`, or `None` if the profile does not allow it.
    pub const fn rules(&self, version: TlsVersion) -> Option<&VersionRules> {
        match version {
            TlsVersion::TLS12 => self.tls12.as_ref(),
            TlsVersion::TLS13 => self.tls13.as_ref(),
            _ => None,
        }
    }

    /// The allowed versions, newest first.
    pub fn versions(&self) -> impl Iterator<Item = TlsVersion> {
        let v13 = self.tls13.map(|_| TlsVersion::TLS13);
        let v12 = self.tls12.map(|_| TlsVersion::TLS12);
        v13.into_iter().chain(v12)
    }
}