use core::fmt;
use crate::ids::{CipherSuite, NamedGroup, SignatureScheme, TlsVersion};
use crate::profile::{Allowed, Level, Profile, VersionRules};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Unsupported {
CipherSuite(CipherSuite),
Group(NamedGroup),
SignatureScheme(SignatureScheme),
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 {}
#[derive(Clone, Copy, Debug)]
pub struct OpensslConfig<'p> {
profile: &'p Profile,
}
#[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,
}
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(":")?;
}
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)),
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}\"")
}
}
fn options(p: &Profile) -> impl Iterator<Item = (bool, &'static str)> {
[
(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 }
}
pub const fn min_protocol(&self) -> Value<'p> {
self.value(Kind::MinProtocol)
}
pub const fn max_protocol(&self) -> Value<'p> {
self.value(Kind::MaxProtocol)
}
pub const fn cipher_string(&self) -> Value<'p> {
self.value(Kind::CipherString)
}
pub const fn ciphersuites(&self) -> Value<'p> {
self.value(Kind::Ciphersuites)
}
pub const fn groups(&self) -> Value<'p> {
self.value(Kind::Groups)
}
pub const fn signature_algorithms(&self) -> Value<'p> {
self.value(Kind::SignatureAlgorithms)
}
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;
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 {
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 })
}
}