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
//! What a profile requires of a TLS certificate, as data. The check itself, which reads
//! DER, is in the `x509` module behind the feature of the same name.

use core::fmt;

use crate::profile::{Allowed, KeyRule};

macro_rules! oid_enum {
    (
        $(#[$meta:meta])*
        $name:ident {
            $( $(#[$vmeta:meta])* $variant:ident = [$($byte:literal),+] => $label:literal, )+
        }
    ) => {
        $(#[$meta])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
        #[non_exhaustive]
        pub enum $name {
            $( $(#[$vmeta])* $variant, )+
        }

        impl $name {
            /// Every variant.
            pub const ALL: &'static [Self] = &[$(Self::$variant),+];

            /// The object identifier, as DER content bytes.
            pub const fn oid(self) -> &'static [u8] {
                match self {
                    $( Self::$variant => &[$($byte),+], )+
                }
            }

            /// The variant with this object identifier.
            pub fn from_oid(oid: &[u8]) -> Option<Self> {
                Self::ALL.iter().copied().find(|v| v.oid() == oid)
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(match self {
                    $( Self::$variant => $label, )+
                })
            }
        }
    };
}

oid_enum! {
    /// An X.509 certificate extension (RFC 5280 §4.2).
    Extension {
        /// 2.5.29.35
        AuthorityKeyIdentifier = [0x55, 0x1D, 0x23] => "AuthorityKeyIdentifier",
        /// 2.5.29.14
        SubjectKeyIdentifier = [0x55, 0x1D, 0x0E] => "SubjectKeyIdentifier",
        /// 2.5.29.15
        KeyUsage = [0x55, 0x1D, 0x0F] => "KeyUsage",
        /// 2.5.29.16
        PrivateKeyUsagePeriod = [0x55, 0x1D, 0x10] => "PrivateKeyUsagePeriod",
        /// 2.5.29.32
        CertificatePolicies = [0x55, 0x1D, 0x20] => "CertificatePolicies",
        /// 2.5.29.17
        SubjectAltName = [0x55, 0x1D, 0x11] => "SubjectAltName",
        /// 2.5.29.18
        IssuerAltName = [0x55, 0x1D, 0x12] => "IssuerAltName",
        /// 2.5.29.19
        BasicConstraints = [0x55, 0x1D, 0x13] => "BasicConstraints",
        /// 2.5.29.37
        ExtendedKeyUsage = [0x55, 0x1D, 0x25] => "ExtendedKeyUsage",
        /// 2.5.29.31
        CrlDistributionPoints = [0x55, 0x1D, 0x1F] => "CRLDistributionPoints",
        /// 1.3.6.1.5.5.7.1.1
        AuthorityInfoAccess = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01] => "AuthorityInfoAccess",
    }
}

oid_enum! {
    /// An extended key usage purpose (RFC 5280 §4.2.1.12).
    ExtendedKeyUsage {
        /// TLS server authentication, 1.3.6.1.5.5.7.3.1.
        ServerAuth = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01] => "serverAuth",
        /// TLS client authentication, 1.3.6.1.5.5.7.3.2.
        ClientAuth = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02] => "clientAuth",
    }
}

/// The algorithm the issuer signed a certificate with.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CertSignature {
    /// ecdsa-with-SHA256.
    EcdsaSha256,
    /// ecdsa-with-SHA384.
    EcdsaSha384,
    /// ecdsa-with-SHA512.
    EcdsaSha512,
    /// sha256WithRSAEncryption (PKCS#1 v1.5).
    RsaPkcs1Sha256,
    /// sha384WithRSAEncryption (PKCS#1 v1.5).
    RsaPkcs1Sha384,
    /// sha512WithRSAEncryption (PKCS#1 v1.5).
    RsaPkcs1Sha512,
    /// RSASSA-PSS with SHA-256.
    RsaPssSha256,
    /// RSASSA-PSS with SHA-384.
    RsaPssSha384,
    /// RSASSA-PSS with SHA-512.
    RsaPssSha512,
    /// Ed25519.
    Ed25519,
}

impl fmt::Display for CertSignature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::EcdsaSha256 => "ecdsa-with-SHA256",
            Self::EcdsaSha384 => "ecdsa-with-SHA384",
            Self::EcdsaSha512 => "ecdsa-with-SHA512",
            Self::RsaPkcs1Sha256 => "sha256WithRSAEncryption",
            Self::RsaPkcs1Sha384 => "sha384WithRSAEncryption",
            Self::RsaPkcs1Sha512 => "sha512WithRSAEncryption",
            Self::RsaPssSha256 => "RSASSA-PSS with SHA-256",
            Self::RsaPssSha384 => "RSASSA-PSS with SHA-384",
            Self::RsaPssSha512 => "RSASSA-PSS with SHA-512",
            Self::Ed25519 => "Ed25519",
        })
    }
}

/// A KeyUsage bit (RFC 5280 §4.2.1.3).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum KeyUsage {
    /// Bit 0.
    DigitalSignature,
    /// Bit 1 (contentCommitment).
    NonRepudiation,
    /// Bit 2.
    KeyEncipherment,
    /// Bit 3.
    DataEncipherment,
    /// Bit 4.
    KeyAgreement,
    /// Bit 5.
    KeyCertSign,
    /// Bit 6.
    CrlSign,
    /// Bit 7.
    EncipherOnly,
    /// Bit 8.
    DecipherOnly,
}

impl KeyUsage {
    /// The bit number in the KeyUsage BIT STRING.
    pub const fn bit(self) -> u8 {
        self as u8
    }
}

impl fmt::Display for KeyUsage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::DigitalSignature => "digitalSignature",
            Self::NonRepudiation => "nonRepudiation",
            Self::KeyEncipherment => "keyEncipherment",
            Self::DataEncipherment => "dataEncipherment",
            Self::KeyAgreement => "keyAgreement",
            Self::KeyCertSign => "keyCertSign",
            Self::CrlSign => "cRLSign",
            Self::EncipherOnly => "encipherOnly",
            Self::DecipherOnly => "decipherOnly",
        })
    }
}

/// Rules for the SubjectAltName extension.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SanRules {
    /// Whether `*` may appear in any name.
    pub wildcards: bool,
    /// Most dNSName entries, if limited.
    pub max_dns_names: Option<u8>,
    /// A certificate with the serverAuth purpose must carry a dNSName.
    pub dns_name_for_server_auth: bool,
    /// Exact number of uniformResourceIdentifier entries, if prescribed.
    pub uris: Option<u8>,
}

/// Rules for the subject's distinguished name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SubjectRules {
    /// The organisation (O) must be exactly this.
    pub organization: Option<&'static str>,
    /// Exactly one organisational unit (OU) must be present.
    pub organizational_unit: bool,
    /// The common name (CN) must contain this after at least one character (the `<org>` of
    /// CP SM-PKI Tab. 23's `<org>.EMT.MAK[<extension>]`).
    pub common_name_contains: Option<&'static str>,
}

/// What a profile requires of a TLS certificate (its own or the peer's).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CertRules {
    /// The certificate's public key.
    pub keys: Allowed<KeyRule>,
    /// The issuer's signature algorithm.
    pub signatures: Allowed<CertSignature>,
    /// Longest validity (notAfter − notBefore) in days. "Two years" is encoded as 731, so a
    /// two-year certificate across a leap day passes; one without a leap day may be one day
    /// longer than two calendar years and still pass.
    pub max_validity_days: Option<u32>,
    /// Extensions: with `Only`, any extension not listed is not allowed.
    pub extensions: Allowed<Extension>,
    /// `Some`: exactly these extensions must be critical, every other present one must not
    /// be. `None`: criticality is not restricted.
    pub critical: Option<&'static [Extension]>,
    /// KeyUsage bits that must be set. Other bits are not restricted.
    pub key_usage: &'static [KeyUsage],
    /// Extended key usage purposes.
    pub extended_key_usage: Allowed<ExtendedKeyUsage>,
    /// BasicConstraints must not say cA = TRUE.
    pub end_entity: bool,
    /// SubjectAltName.
    pub san: SanRules,
    /// Subject name.
    pub subject: SubjectRules,
}

impl CertRules {
    /// No certificate rules.
    pub const ANY: Self = Self {
        keys: Allowed::Any,
        signatures: Allowed::Any,
        max_validity_days: None,
        extensions: Allowed::Any,
        critical: None,
        key_usage: &[],
        extended_key_usage: Allowed::Any,
        end_entity: false,
        san: SanRules { wildcards: true, max_dns_names: None, dns_name_for_server_auth: false, uris: None },
        subject: SubjectRules { organization: None, organizational_unit: false, common_name_contains: None },
    };
}