Skip to main content

utility_pki/
check.rs

1//! Checking against a profile: a negotiated [`Session`] with [`Profile::check`], and a
2//! configuration with [`Profile::audit`].
3
4use core::fmt;
5
6use crate::ids::{CipherSuite, NamedGroup, SignatureScheme, TlsVersion};
7use crate::profile::{Allowed, Level, Profile, PublicKey, VersionRules};
8
9/// What was negotiated, as the TLS library reports it after the handshake.
10///
11/// Start from [`Session::new`] and set what your library reports:
12///
13/// ```
14/// # use utility_pki::*;
15/// let s = Session {
16///     group: Some(NamedGroup::BRAINPOOLP256R1),
17///     mutual_auth: true,
18///     peer_key: Some(PublicKey::Ec(Curve::BrainpoolP256r1)),
19///     ..Session::new(TlsVersion::TLS12, CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
20/// };
21/// ```
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub struct Session {
24    /// The protocol version.
25    pub version: TlsVersion,
26    /// The cipher suite.
27    pub cipher_suite: CipherSuite,
28    /// The key-exchange group. If the profile restricts groups and this is `None`, the
29    /// check reports [`Violation::GroupUnknown`].
30    pub group: Option<NamedGroup>,
31    /// The peer's handshake signature scheme. Checked when reported.
32    pub signature_scheme: Option<SignatureScheme>,
33    /// Whether both sides authenticated with a certificate.
34    pub mutual_auth: bool,
35    /// The peer certificate's public key. If the profile restricts keys and this is
36    /// `None`, the check reports [`Violation::PeerKeyUnknown`].
37    pub peer_key: Option<PublicKey>,
38    /// The peer certificate's validity period (notAfter − notBefore) in days.
39    pub peer_cert_validity_days: Option<u32>,
40    /// Whether Encrypt-then-MAC (RFC 7366) is in use. Only matters for CBC suites.
41    pub encrypt_then_mac: Option<bool>,
42}
43
44impl Session {
45    /// A session with this version and suite, and nothing else known.
46    pub const fn new(version: TlsVersion, cipher_suite: CipherSuite) -> Self {
47        Self {
48            version,
49            cipher_suite,
50            group: None,
51            signature_scheme: None,
52            mutual_auth: false,
53            peer_key: None,
54            peer_cert_validity_days: None,
55            encrypt_then_mac: None,
56        }
57    }
58}
59
60/// One way a session breaks a profile.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62#[non_exhaustive]
63pub enum Violation {
64    /// The protocol version is not allowed.
65    Version(TlsVersion),
66    /// The cipher suite is not allowed with this version.
67    CipherSuite(CipherSuite),
68    /// A TLS 1.3 suite with TLS 1.2, or the other way round.
69    SuiteVersionMismatch(CipherSuite, TlsVersion),
70    /// The key-exchange group is not allowed with this version.
71    Group(NamedGroup),
72    /// The profile restricts groups, but the session does not say which was used.
73    GroupUnknown,
74    /// The signature scheme is not allowed with this version.
75    SignatureScheme(SignatureScheme),
76    /// A CBC suite without Encrypt-then-MAC, which the profile requires.
77    EncryptThenMacMissing,
78    /// The profile requires mutual authentication and the client presented no certificate.
79    MutualAuthMissing,
80    /// The peer's certificate key is not allowed.
81    PeerKey(PublicKey),
82    /// The profile restricts certificate keys, but the session does not say which was used.
83    PeerKeyUnknown,
84    /// The peer's certificate is valid for longer than the profile allows.
85    CertValidity {
86        /// The certificate's validity in days.
87        days: u32,
88        /// The profile's maximum.
89        max: u32,
90    },
91}
92
93impl fmt::Display for Violation {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        match self {
96            Self::Version(v) => write!(f, "{v} is not allowed"),
97            Self::CipherSuite(s) => write!(f, "cipher suite {s} is not allowed"),
98            Self::SuiteVersionMismatch(s, v) => write!(f, "cipher suite {s} cannot be used with {v}"),
99            Self::Group(g) => write!(f, "key-exchange group {g} is not allowed"),
100            Self::GroupUnknown => f.write_str("the key-exchange group is restricted but was not reported"),
101            Self::SignatureScheme(s) => write!(f, "signature scheme {s} is not allowed"),
102            Self::EncryptThenMacMissing => f.write_str("a CBC cipher suite requires Encrypt-then-MAC"),
103            Self::MutualAuthMissing => f.write_str("mutual authentication is required"),
104            Self::PeerKey(k) => write!(f, "certificate key {k} is not allowed"),
105            Self::PeerKeyUnknown => f.write_str("the certificate key is restricted but was not reported"),
106            Self::CertValidity { days, max } => {
107                write!(f, "certificate valid for {days} days, at most {max} allowed")
108            }
109        }
110    }
111}
112
113/// The result of [`Profile::check`]: every violation found, without allocating.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct Report {
116    items: [Option<Violation>; Report::CAPACITY],
117    len: usize,
118    truncated: bool,
119}
120
121impl Report {
122    /// The most violations one check can report: one per rule.
123    pub const CAPACITY: usize = 8;
124
125    const fn new() -> Self {
126        Self { items: [None; Self::CAPACITY], len: 0, truncated: false }
127    }
128
129    fn push(&mut self, v: Violation) {
130        match self.items.get_mut(self.len) {
131            Some(slot) => {
132                *slot = Some(v);
133                self.len += 1;
134            }
135            None => self.truncated = true,
136        }
137    }
138
139    /// Whether the session satisfies the profile. Never true for a truncated report.
140    pub const fn is_ok(&self) -> bool {
141        self.len == 0 && !self.truncated
142    }
143
144    /// Whether more violations were found than the report holds.
145    pub const fn truncated(&self) -> bool {
146        self.truncated
147    }
148
149    /// The violations, in rule order.
150    pub fn violations(&self) -> impl Iterator<Item = Violation> + '_ {
151        self.items.iter().take(self.len).filter_map(|v| *v)
152    }
153}
154
155/// What an endpoint is configured to offer: the lists it sends in its hello.
156///
157/// The lists are shared by all enabled versions, as in a real ClientHello. Each item is
158/// judged against every enabled version it applies to.
159#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
160pub struct Offer<'a> {
161    /// Enabled protocol versions.
162    pub versions: &'a [TlsVersion],
163    /// Enabled cipher suites, both versions together.
164    pub cipher_suites: &'a [CipherSuite],
165    /// `supported_groups`.
166    pub groups: &'a [NamedGroup],
167    /// `signature_algorithms`.
168    pub signature_schemes: &'a [SignatureScheme],
169    /// `signature_algorithms_cert`. Left empty, it is taken to equal `signature_schemes`
170    /// (RFC 8446 §4.2.3) and checked against the certificate signature rules too.
171    pub cert_signature_schemes: &'a [SignatureScheme],
172}
173
174/// One offered or configurable item.
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub enum Item {
177    /// A protocol version.
178    Version(TlsVersion),
179    /// A cipher suite.
180    CipherSuite(CipherSuite),
181    /// A key-exchange group.
182    Group(NamedGroup),
183    /// A handshake signature scheme.
184    SignatureScheme(SignatureScheme),
185    /// A certificate signature scheme.
186    CertSignatureScheme(SignatureScheme),
187}
188
189impl fmt::Display for Item {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        match self {
192            Self::Version(v) => write!(f, "{v}"),
193            Self::CipherSuite(s) => write!(f, "cipher suite {s}"),
194            Self::Group(g) => write!(f, "group {g}"),
195            Self::SignatureScheme(s) => write!(f, "signature scheme {s}"),
196            Self::CertSignatureScheme(s) => write!(f, "certificate signature scheme {s}"),
197        }
198    }
199}
200
201/// One way a configuration breaks a profile.
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub enum Finding {
204    /// The profile requires this item and the configuration does not offer it.
205    Missing(Item),
206    /// The configuration offers an item that no enabled version allows.
207    NotAllowed(Item),
208    /// The item is allowed with one enabled version but not with this one. One shared list
209    /// (as in OpenSSL's `SignatureAlgorithms`) cannot satisfy both; restrict it per version
210    /// where the library allows, or rely on the session check.
211    NotAllowedWith(Item, TlsVersion),
212}
213
214impl fmt::Display for Finding {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        match self {
217            Self::Missing(i) => write!(f, "{i} is required but not offered"),
218            Self::NotAllowed(i) => write!(f, "{i} is offered but not allowed"),
219            Self::NotAllowedWith(i, v) => write!(f, "{i} is offered but not allowed with {v}"),
220        }
221    }
222}
223
224fn restricted<T>(a: &Allowed<T>) -> bool {
225    matches!(a, Allowed::Only { .. })
226}
227
228fn required_items(r: VersionRules) -> impl Iterator<Item = Item> {
229    let suites = r.cipher_suites.required().iter().map(|&s| Item::CipherSuite(s));
230    let groups = r.groups.required().iter().map(|&g| Item::Group(g));
231    let sigs = r.signature_schemes.required().iter().map(|&s| Item::SignatureScheme(s));
232    let certs = r.cert_signature_schemes.required().iter().map(|&s| Item::CertSignatureScheme(s));
233    suites.chain(groups).chain(sigs).chain(certs)
234}
235
236/// Whether an item can be used with this version at all: Brainpool has separate code points
237/// for TLS 1.2 (26–28, RFC 7027) and TLS 1.3 (31–33 and the `…tls13` schemes, RFC 8734).
238fn applies(item: Item, version: TlsVersion) -> bool {
239    let tls13 = version == TlsVersion::TLS13;
240    match item {
241        Item::Version(v) => v == version,
242        Item::CipherSuite(s) => s.is_tls13() == tls13,
243        Item::Group(g) => match g.0 {
244            26..=28 => !tls13,
245            31..=33 => tls13,
246            _ => true,
247        },
248        Item::SignatureScheme(s) | Item::CertSignatureScheme(s) => tls13 || !matches!(s.0, 0x081A..=0x081C),
249    }
250}
251
252fn rules_allow(version: TlsVersion, r: &VersionRules, item: Item) -> bool {
253    match item {
254        Item::Version(v) => v == version,
255        Item::CipherSuite(s) => s.is_tls13() == (version == TlsVersion::TLS13) && r.cipher_suites.allows(&s),
256        Item::Group(g) => r.groups.allows(&g),
257        Item::SignatureScheme(s) => r.signature_schemes.allows(&s),
258        Item::CertSignatureScheme(s) => r.cert_signature_schemes.allows(&s),
259    }
260}
261
262impl Offer<'_> {
263    fn cert_schemes(&self) -> &[SignatureScheme] {
264        if self.cert_signature_schemes.is_empty() {
265            self.signature_schemes
266        } else {
267            self.cert_signature_schemes
268        }
269    }
270
271    fn offers(&self, item: Item) -> bool {
272        match item {
273            Item::Version(v) => self.versions.contains(&v),
274            Item::CipherSuite(s) => self.cipher_suites.contains(&s),
275            Item::Group(g) => self.groups.contains(&g),
276            Item::SignatureScheme(s) => self.signature_schemes.contains(&s),
277            Item::CertSignatureScheme(s) => self.cert_schemes().contains(&s),
278        }
279    }
280
281    /// Every offered item, and whether it is a certificate scheme defaulted from the
282    /// handshake list (RFC 8446 §4.2.3: an absent `signature_algorithms_cert` means the
283    /// `signature_algorithms` list applies to certificates too).
284    fn items(&self) -> impl Iterator<Item = (Item, bool)> + '_ {
285        let suites = self.cipher_suites.iter().map(|&s| (Item::CipherSuite(s), false));
286        let groups = self.groups.iter().map(|&g| (Item::Group(g), false));
287        let sigs = self.signature_schemes.iter().map(|&s| (Item::SignatureScheme(s), false));
288        let defaulted = self.cert_signature_schemes.is_empty();
289        let certs = self.cert_schemes().iter().map(move |&s| (Item::CertSignatureScheme(s), defaulted));
290        suites.chain(groups).chain(sigs).chain(certs)
291    }
292}
293
294impl Profile {
295    /// Check a negotiated session against this profile. Returns every violation, not
296    /// only the first.
297    pub fn check(&self, s: &Session) -> Report {
298        let mut r = Report::new();
299        match self.rules(s.version) {
300            None => r.push(Violation::Version(s.version)),
301            Some(rules) => {
302                if s.cipher_suite.is_tls13() != (s.version == TlsVersion::TLS13) {
303                    r.push(Violation::SuiteVersionMismatch(s.cipher_suite, s.version));
304                } else if !rules.cipher_suites.allows(&s.cipher_suite) {
305                    r.push(Violation::CipherSuite(s.cipher_suite));
306                }
307                match s.group {
308                    Some(g) if !rules.groups.allows(&g) => r.push(Violation::Group(g)),
309                    None if restricted(&rules.groups) => r.push(Violation::GroupUnknown),
310                    _ => {}
311                }
312                if let Some(sig) = s.signature_scheme {
313                    if !rules.signature_schemes.allows(&sig) {
314                        r.push(Violation::SignatureScheme(sig));
315                    }
316                }
317            }
318        }
319        if self.encrypt_then_mac == Level::Must && s.cipher_suite.is_cbc() && s.encrypt_then_mac != Some(true)
320        {
321            r.push(Violation::EncryptThenMacMissing);
322        }
323        if self.mutual_auth && !s.mutual_auth {
324            r.push(Violation::MutualAuthMissing);
325        }
326        match s.peer_key {
327            Some(k) if !self.cert.keys.iter().any(|rule| rule.accepts(k)) && restricted(&self.cert.keys) => {
328                r.push(Violation::PeerKey(k));
329            }
330            None if restricted(&self.cert.keys) => r.push(Violation::PeerKeyUnknown),
331            _ => {}
332        }
333        if let (Some(max), Some(days)) = (self.cert.max_validity_days, s.peer_cert_validity_days) {
334            if days > max {
335                r.push(Violation::CertValidity { days, max });
336            }
337        }
338        r
339    }
340
341    /// Audit what an endpoint is configured to offer: every item the profile requires
342    /// that is missing, and every offered item it does not allow. Run it once at
343    /// start-up, or in a test against your TLS library's configuration.
344    ///
345    /// ```
346    /// use utility_pki::profiles::BSI_TR_03116_3;
347    /// use utility_pki::{CipherSuite, Offer, TlsVersion};
348    ///
349    /// let offer = Offer {
350    ///     versions: &[TlsVersion::TLS12],
351    ///     cipher_suites: &[CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256],
352    ///     ..Offer::default()
353    /// };
354    /// for finding in BSI_TR_03116_3.audit(&offer) {
355    ///     println!("{finding}");
356    /// }
357    /// assert!(BSI_TR_03116_3.audit(&offer).next().is_some());
358    /// ```
359    pub fn audit<'a>(&'a self, offer: &'a Offer<'a>) -> impl Iterator<Item = Finding> + 'a {
360        // The versions both allowed here and enabled in the offer.
361        let active = move || {
362            self.versions()
363                .filter(|v| offer.versions.contains(v))
364                .filter_map(|v| self.rules(v).map(|r| (v, *r)))
365        };
366
367        let missing_versions = self
368            .versions()
369            .filter(move |&v| {
370                self.rules(v).is_some_and(|r| r.support == Level::Must) && !offer.versions.contains(&v)
371            })
372            .map(|v| Finding::Missing(Item::Version(v)));
373
374        // A required item shared by both versions (e.g. secp256r1) is reported once.
375        let missing_items = active().enumerate().flat_map(move |(i, (_, rules))| {
376            required_items(rules)
377                .filter(move |&item| !offer.offers(item))
378                .filter(move |&item| {
379                    !active().take(i).any(|(_, earlier)| required_items(earlier).any(|x| x == item))
380                })
381                .map(Finding::Missing)
382        });
383
384        let versions_not_allowed = offer
385            .versions
386            .iter()
387            .filter(move |&&v| self.rules(v).is_none())
388            .map(|&v| Finding::NotAllowed(Item::Version(v)));
389
390        // Each offered item is judged against every enabled version it applies to.
391        let verdict = move |item: Item| {
392            let applicable = move || active().filter(move |&(v, _)| applies(item, v));
393            let allowed_somewhere = applicable().any(|(v, rules)| rules_allow(v, &rules, item));
394            let nowhere = (!allowed_somewhere).then_some(Finding::NotAllowed(item));
395            let somewhere_not = applicable()
396                .filter(move |(v, rules)| allowed_somewhere && !rules_allow(*v, rules, item))
397                .map(move |(v, _)| Finding::NotAllowedWith(item, v));
398            nowhere.into_iter().chain(somewhere_not)
399        };
400        let items_not_allowed = offer.items().flat_map(move |(item, defaulted)| {
401            // A defaulted certificate scheme already reported as a handshake scheme is not
402            // reported twice.
403            let duplicate = match item {
404                Item::CertSignatureScheme(s) if defaulted => {
405                    verdict(Item::SignatureScheme(s)).next().is_some()
406                }
407                _ => false,
408            };
409            verdict(item).filter(move |_| !duplicate)
410        });
411
412        missing_versions.chain(missing_items).chain(versions_not_allowed).chain(items_not_allowed)
413    }
414}