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 profile as OpenSSL configuration (`openssl.cnf`, `SSL_CONF_cmd`), without allocating.
//!
//! ```
//! use utility_pki::profiles::BDEW_AS4;
//!
//! let config = BDEW_AS4.openssl().expect("every shipped profile has OpenSSL names");
//! println!("{config}"); // the lines of an openssl.cnf SSL section
//! let tls13 = config.ciphersuites().to_string(); // one value, e.g. for SSL_CTX_set_ciphersuites
//! assert_eq!(tls13, "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_AES_128_CCM_SHA256");
//! ```
//!
//! The names target OpenSSL 3.2 or later, the first release with the RFC 8734 Brainpool
//! groups for TLS 1.3.
//!
//! OpenSSL has one `Groups` and one `SignatureAlgorithms` list for both TLS versions, so
//! the export writes what either version allows. Where the versions differ (TR-03116-3
//! Tab. 9 wants ECDSA-SHA512 in TLS 1.2, Tab. 15 has no P-521 scheme in TLS 1.3),
//! [`Profile::audit`] reports `NotAllowedWith` and [`Profile::check`] catches the rare
//! session that uses it.
//!
//! OpenSSL cannot express these rules at all; enforce them in code:
//!
//! - mutual TLS;
//! - the session lifetime (TR-03116-3 ยง4.1.2: 48 hours);
//! - a separate `signature_algorithms_cert` list (TR-03116-3 Tab. 16). OpenSSL has no
//!   setting for it; [`Profile::check_certificate`] judges the certificate instead.

use core::fmt;

use crate::ids::{CipherSuite, NamedGroup, SignatureScheme, TlsVersion};
use crate::profile::{Allowed, Level, Profile, VersionRules};

/// A profile item that has no OpenSSL name, so the profile cannot be exported.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Unsupported {
    /// A cipher suite.
    CipherSuite(CipherSuite),
    /// A key-exchange group.
    Group(NamedGroup),
    /// A signature scheme.
    SignatureScheme(SignatureScheme),
    /// The profile allows no TLS version.
    NoVersion,
}

impl fmt::Display for Unsupported {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CipherSuite(s) => write!(f, "cipher suite {s} has no OpenSSL name"),
            Self::Group(g) => write!(f, "group {g} has no OpenSSL name"),
            Self::SignatureScheme(s) => write!(f, "signature scheme {s} has no OpenSSL name"),
            Self::NoVersion => f.write_str("the profile allows no TLS version"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Unsupported {}

/// A profile rendered as OpenSSL directives.
///
/// `Display` writes the lines of an `openssl.cnf` SSL configuration section. Each accessor
/// gives one value on its own. A list neither version restricts gets no line; a list only
/// one version restricts is written as that version's list and so applies to both.
#[derive(Clone, Copy, Debug)]
pub struct OpensslConfig<'p> {
    profile: &'p Profile,
}

/// One OpenSSL value: a `:`-separated list, a protocol, or the options.
#[derive(Clone, Copy)]
pub struct Value<'p> {
    profile: &'p Profile,
    kind: Kind,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    MinProtocol,
    MaxProtocol,
    CipherString,
    Ciphersuites,
    Groups,
    SignatureAlgorithms,
    Options,
}

/// Required items of every version first (newest version first), then optional ones,
/// each once.
fn ordered<'p, T: Copy + PartialEq + 'static>(
    p: &'p Profile,
    versions: &'static [TlsVersion],
    pick: fn(&VersionRules) -> Allowed<T>,
) -> impl Iterator<Item = T> + 'p {
    let lists =
        move || p.versions().filter(|v| versions.contains(v)).filter_map(move |v| p.rules(v).map(pick));
    let all = move || {
        let required = lists().flat_map(|a| a.required().iter().copied());
        required.chain(lists().flat_map(|a| a.optional().iter().copied()))
    };
    all().enumerate().filter(move |&(i, x)| !all().take(i).any(|y| y == x)).map(|(_, x)| x)
}

const TLS12: &[TlsVersion] = &[TlsVersion::TLS12];
const TLS13: &[TlsVersion] = &[TlsVersion::TLS13];
const BOTH: &[TlsVersion] = &[TlsVersion::TLS13, TlsVersion::TLS12];

fn restricts<T>(p: &Profile, versions: &[TlsVersion], pick: fn(&VersionRules) -> Allowed<T>) -> bool {
    p.versions()
        .filter(|v| versions.contains(v))
        .any(|v| p.rules(v).is_some_and(|r| matches!(pick(r), Allowed::Only { .. })))
}

const fn suites(r: &VersionRules) -> Allowed<CipherSuite> {
    r.cipher_suites
}
const fn groups(r: &VersionRules) -> Allowed<NamedGroup> {
    r.groups
}
const fn sigs(r: &VersionRules) -> Allowed<SignatureScheme> {
    r.signature_schemes
}

fn list<T: Copy>(
    f: &mut fmt::Formatter<'_>,
    items: impl Iterator<Item = T>,
    name: fn(T) -> Option<&'static str>,
) -> fmt::Result {
    for (i, item) in items.enumerate() {
        if i > 0 {
            f.write_str(":")?;
        }
        // `Profile::openssl` checked every name; skip defensively instead of panicking.
        f.write_str(name(item).unwrap_or(""))?;
    }
    Ok(())
}

impl fmt::Display for Value<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let p = self.profile;
        match self.kind {
            Kind::MinProtocol => f.write_str(p.versions().last().map_or("", version_name)),
            Kind::MaxProtocol => f.write_str(p.versions().next().map_or("", version_name)),
            // AEAD before CBC, so an OpenSSL client never prefers CBC (ordered() keeps the
            // required-first order within each half).
            Kind::CipherString => list(
                f,
                ordered(p, TLS12, suites)
                    .filter(|s| !s.is_cbc())
                    .chain(ordered(p, TLS12, suites).filter(|s| s.is_cbc())),
                CipherSuite::openssl_name,
            ),
            Kind::Ciphersuites => list(f, ordered(p, TLS13, suites), CipherSuite::openssl_name),
            Kind::Groups => list(f, ordered(p, BOTH, groups), NamedGroup::name),
            Kind::SignatureAlgorithms => list(f, ordered(p, BOTH, sigs), SignatureScheme::name),
            Kind::Options => {
                for (i, name) in options(p).filter_map(|(on, name)| on.then_some(name)).enumerate() {
                    if i > 0 {
                        f.write_str(",")?;
                    }
                    f.write_str(name)?;
                }
                Ok(())
            }
        }
    }
}

impl fmt::Debug for Value<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"{self}\"")
    }
}

/// The `SSL_CONF_cmd` options the profile asks for (all documented in OpenSSL 4.1).
fn options(p: &Profile) -> impl Iterator<Item = (bool, &'static str)> {
    [
        // The server picks from its own (profile) order, not the client's.
        (true, "ServerPreference"),
        (p.renegotiation == Level::MustNot, "NoRenegotiation"),
        (matches!(p.encrypt_then_mac, Level::Must | Level::Should), "EncryptThenMac"),
        (matches!(p.extended_master_secret, Level::Must | Level::Should), "ExtendedMasterSecret"),
    ]
    .into_iter()
}

const fn version_name(v: TlsVersion) -> &'static str {
    if v.0 == TlsVersion::TLS13.0 { "TLSv1.3" } else { "TLSv1.2" }
}

impl<'p> OpensslConfig<'p> {
    const fn value(self, kind: Kind) -> Value<'p> {
        Value { profile: self.profile, kind }
    }

    /// `MinProtocol`: the oldest allowed version, e.g. `TLSv1.2`.
    pub const fn min_protocol(&self) -> Value<'p> {
        self.value(Kind::MinProtocol)
    }

    /// `MaxProtocol`: the newest allowed version.
    pub const fn max_protocol(&self) -> Value<'p> {
        self.value(Kind::MaxProtocol)
    }

    /// `CipherString`: the TLS 1.2 suites in OpenSSL names, required first.
    pub const fn cipher_string(&self) -> Value<'p> {
        self.value(Kind::CipherString)
    }

    /// `Ciphersuites`: the TLS 1.3 suites, required first.
    pub const fn ciphersuites(&self) -> Value<'p> {
        self.value(Kind::Ciphersuites)
    }

    /// `Groups`: every allowed group of both versions, required first.
    pub const fn groups(&self) -> Value<'p> {
        self.value(Kind::Groups)
    }

    /// `SignatureAlgorithms`: every allowed handshake signature scheme, required first.
    pub const fn signature_algorithms(&self) -> Value<'p> {
        self.value(Kind::SignatureAlgorithms)
    }

    /// `Options`: `NoRenegotiation`, `EncryptThenMac`, `ExtendedMasterSecret`, as the
    /// profile asks for them.
    pub const fn options(&self) -> Value<'p> {
        self.value(Kind::Options)
    }
}

impl fmt::Display for OpensslConfig<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let p = self.profile;
        // Free text only as one comment line, without control characters (THREAT_MODEL.md SR-007).
        f.write_str("# ")?;
        for c in p.name.chars().filter(|c| !c.is_control()) {
            fmt::Write::write_char(f, c)?;
        }
        f.write_str(" (utility-pki)\n")?;
        writeln!(f, "MinProtocol = {}", self.min_protocol())?;
        writeln!(f, "MaxProtocol = {}", self.max_protocol())?;
        if restricts(p, TLS12, suites) {
            writeln!(f, "CipherString = {}", self.cipher_string())?;
        }
        if restricts(p, TLS13, suites) {
            writeln!(f, "Ciphersuites = {}", self.ciphersuites())?;
        }
        if restricts(p, BOTH, groups) {
            writeln!(f, "Groups = {}", self.groups())?;
        }
        if restricts(p, BOTH, sigs) {
            writeln!(f, "SignatureAlgorithms = {}", self.signature_algorithms())?;
        }
        if options(p).any(|(on, _)| on) {
            writeln!(f, "Options = {}", self.options())?;
        }
        Ok(())
    }
}

impl Profile {
    /// This profile as OpenSSL configuration.
    ///
    /// # Errors
    ///
    /// [`Unsupported`] names the first suite, group or signature scheme that has no
    /// verified OpenSSL name. Every shipped profile exports.
    pub fn openssl(&self) -> Result<OpensslConfig<'_>, Unsupported> {
        if self.versions().next().is_none() {
            return Err(Unsupported::NoVersion);
        }
        for v in self.versions() {
            let Some(r) = self.rules(v) else { continue };
            if let Some(s) = r.cipher_suites.iter().find(|s| s.openssl_name().is_none()) {
                return Err(Unsupported::CipherSuite(s));
            }
            if let Some(g) = r.groups.iter().find(|g| g.name().is_none()) {
                return Err(Unsupported::Group(g));
            }
            if let Some(s) = r.signature_schemes.iter().find(|s| s.name().is_none()) {
                return Err(Unsupported::SignatureScheme(s));
            }
        }
        Ok(OpensslConfig { profile: self })
    }
}