Skip to main content

utility_pki/
profile.rs

1//! A security profile: what a standard allows for TLS and certificates, as data.
2
3use core::time::Duration;
4
5use crate::cert::CertRules;
6use crate::ids::{CipherSuite, NamedGroup, SignatureScheme, TlsVersion};
7
8/// A requirement level, as the standard words it (RFC 2119; German texts use MUSS,
9/// SOLLTE, KANN, SOLLTE NICHT, DARF NICHT).
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub enum Level {
12    /// MUST / MUSS.
13    Must,
14    /// SHOULD / SOLLTE, EMPFOHLEN.
15    Should,
16    /// MAY / KANN, or the standard does not say.
17    May,
18    /// SHOULD NOT / SOLLTE NICHT.
19    ShouldNot,
20    /// MUST NOT / DARF NICHT.
21    MustNot,
22}
23
24/// Which items of one kind (suites, groups, schemes, keys) a profile allows.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Allowed<T: 'static> {
27    /// The profile does not restrict this item.
28    Any,
29    /// Only these items. `required` must be supported by a conforming implementation;
30    /// `optional` may be. Anything else must not be used.
31    Only {
32        /// Mandatory to support.
33        required: &'static [T],
34        /// Allowed, not mandatory (SHOULD or MAY).
35        optional: &'static [T],
36    },
37}
38
39impl<T: PartialEq + Copy> Allowed<T> {
40    /// Whether `item` may be used.
41    pub fn allows(&self, item: &T) -> bool {
42        match self {
43            Self::Any => true,
44            Self::Only { required, optional } => required.contains(item) || optional.contains(item),
45        }
46    }
47
48    /// The items that must be supported.
49    pub const fn required(&self) -> &'static [T] {
50        match self {
51            Self::Any => &[],
52            Self::Only { required, .. } => required,
53        }
54    }
55
56    /// The items that may be supported but need not be.
57    pub const fn optional(&self) -> &'static [T] {
58        match self {
59            Self::Any => &[],
60            Self::Only { optional, .. } => optional,
61        }
62    }
63
64    /// Every allowed item, required first. Empty for [`Allowed::Any`].
65    pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
66        let (required, optional): (&[T], &[T]) = match self {
67            Self::Any => (&[], &[]),
68            Self::Only { required, optional } => (required, optional),
69        };
70        required.iter().chain(optional).copied()
71    }
72}
73
74/// The rules for one TLS version.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub struct VersionRules {
77    /// Whether this version must be supported ([`Level::Must`]) or may be ([`Level::Should`],
78    /// [`Level::May`]).
79    pub support: Level,
80    /// Cipher suites.
81    pub cipher_suites: Allowed<CipherSuite>,
82    /// Key-exchange groups.
83    pub groups: Allowed<NamedGroup>,
84    /// Signature schemes in the handshake (`signature_algorithms`, CertificateVerify).
85    pub signature_schemes: Allowed<SignatureScheme>,
86    /// Signature schemes in certificates (`signature_algorithms_cert`).
87    pub cert_signature_schemes: Allowed<SignatureScheme>,
88}
89
90/// An elliptic curve of a certificate key.
91#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
92pub enum Curve {
93    /// NIST P-256 (secp256r1).
94    P256,
95    /// NIST P-384 (secp384r1).
96    P384,
97    /// NIST P-521 (secp521r1).
98    P521,
99    /// brainpoolP256r1 (RFC 5639).
100    BrainpoolP256r1,
101    /// brainpoolP384r1 (RFC 5639).
102    BrainpoolP384r1,
103    /// brainpoolP512r1 (RFC 5639).
104    BrainpoolP512r1,
105}
106
107impl Curve {
108    /// The curve with this object identifier, given as the DER content bytes (what an
109    /// X.509 parser returns for `namedCurve`).
110    pub fn from_oid(oid: &[u8]) -> Option<Self> {
111        Some(match oid {
112            [0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07] => Self::P256,
113            [0x2B, 0x81, 0x04, 0x00, 0x22] => Self::P384,
114            [0x2B, 0x81, 0x04, 0x00, 0x23] => Self::P521,
115            [0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07] => Self::BrainpoolP256r1,
116            [0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B] => Self::BrainpoolP384r1,
117            [0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D] => Self::BrainpoolP512r1,
118            _ => return None,
119        })
120    }
121}
122
123impl core::fmt::Display for Curve {
124    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
125        f.write_str(match self {
126            Self::P256 => "P-256",
127            Self::P384 => "P-384",
128            Self::P521 => "P-521",
129            Self::BrainpoolP256r1 => "brainpoolP256r1",
130            Self::BrainpoolP384r1 => "brainpoolP384r1",
131            Self::BrainpoolP512r1 => "brainpoolP512r1",
132        })
133    }
134}
135
136/// The kind and size of a certificate's public key.
137#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
138pub enum PublicKey {
139    /// RSA with this modulus length in bits.
140    Rsa(u16),
141    /// ECDSA on this curve.
142    Ec(Curve),
143    /// Ed25519.
144    Ed25519,
145}
146
147impl core::fmt::Display for PublicKey {
148    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
149        match self {
150            Self::Rsa(bits) => write!(f, "RSA-{bits}"),
151            Self::Ec(curve) => write!(f, "ECDSA {curve}"),
152            Self::Ed25519 => f.write_str("Ed25519"),
153        }
154    }
155}
156
157/// A rule a certificate key must meet.
158#[derive(Clone, Copy, Debug, PartialEq, Eq)]
159pub enum KeyRule {
160    /// RSA with at least this many bits.
161    RsaMin(u16),
162    /// ECDSA on this curve.
163    Ec(Curve),
164    /// Ed25519.
165    Ed25519,
166}
167
168impl KeyRule {
169    /// Whether `key` satisfies this rule.
170    pub const fn accepts(self, key: PublicKey) -> bool {
171        match (self, key) {
172            (Self::RsaMin(min), PublicKey::Rsa(bits)) => bits >= min,
173            (Self::Ec(want), PublicKey::Ec(have)) => want as u8 == have as u8,
174            (Self::Ed25519, PublicKey::Ed25519) => true,
175            _ => false,
176        }
177    }
178}
179
180/// How certificate revocation is checked.
181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
182pub enum Revocation {
183    /// The profile does not say.
184    Unspecified,
185    /// Must be checked, by CRL only (no OCSP).
186    CrlRequired,
187    /// Must be checked, by CRL or OCSP.
188    Required,
189}
190
191/// A TLS and certificate profile from one standard.
192///
193/// Every field is what the cited text says, no more: a deployment may be stricter.
194/// Rules a negotiated session cannot show are in [`Profile::notes`].
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub struct Profile {
197    /// Short stable identifier, e.g. `"bdew-as4"`.
198    pub id: &'static str,
199    /// Human-readable name.
200    pub name: &'static str,
201    /// The primary texts, each with version and date, that every rule below comes from.
202    pub sources: &'static [&'static str],
203    /// TLS 1.2 rules, or `None` if the profile does not allow TLS 1.2.
204    pub tls12: Option<VersionRules>,
205    /// TLS 1.3 rules, or `None` if the profile does not allow TLS 1.3.
206    pub tls13: Option<VersionRules>,
207    /// What the certificates of both sides must meet.
208    pub cert: CertRules,
209    /// Both sides must present a certificate.
210    pub mutual_auth: bool,
211    /// Revocation checking.
212    pub revocation: Revocation,
213    /// Longest TLS session, including resumptions, before a full handshake.
214    pub max_session_lifetime: Option<Duration>,
215    /// Encrypt-then-MAC (RFC 7366) with CBC suites.
216    pub encrypt_then_mac: Level,
217    /// Extended Master Secret (RFC 7627) in TLS 1.2.
218    pub extended_master_secret: Level,
219    /// TLS 1.2 renegotiation.
220    pub renegotiation: Level,
221    /// TLS 1.3 0-RTT early data.
222    pub early_data: Level,
223    /// Server Name Indication (RFC 6066).
224    pub sni: Level,
225    /// Rules a session check cannot see (key usage, SAN content, CRL timing). For people
226    /// building the configuration.
227    pub notes: &'static [&'static str],
228}
229
230impl Profile {
231    /// The rules for `version`, or `None` if the profile does not allow it.
232    pub const fn rules(&self, version: TlsVersion) -> Option<&VersionRules> {
233        match version {
234            TlsVersion::TLS12 => self.tls12.as_ref(),
235            TlsVersion::TLS13 => self.tls13.as_ref(),
236            _ => None,
237        }
238    }
239
240    /// The allowed versions, newest first.
241    pub fn versions(&self) -> impl Iterator<Item = TlsVersion> {
242        let v13 = self.tls13.map(|_| TlsVersion::TLS13);
243        let v12 = self.tls12.map(|_| TlsVersion::TLS12);
244        v13.into_iter().chain(v12)
245    }
246}