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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Checking against a profile: a negotiated [`Session`] with [`Profile::check`], and a
//! configuration with [`Profile::audit`].

use core::fmt;

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

/// What was negotiated, as the TLS library reports it after the handshake.
///
/// Start from [`Session::new`] and set what your library reports:
///
/// ```
/// # use utility_pki::*;
/// let s = Session {
///     group: Some(NamedGroup::BRAINPOOLP256R1),
///     mutual_auth: true,
///     peer_key: Some(PublicKey::Ec(Curve::BrainpoolP256r1)),
///     ..Session::new(TlsVersion::TLS12, CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
/// };
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Session {
    /// The protocol version.
    pub version: TlsVersion,
    /// The cipher suite.
    pub cipher_suite: CipherSuite,
    /// The key-exchange group. If the profile restricts groups and this is `None`, the
    /// check reports [`Violation::GroupUnknown`].
    pub group: Option<NamedGroup>,
    /// The peer's handshake signature scheme. Checked when reported.
    pub signature_scheme: Option<SignatureScheme>,
    /// Whether both sides authenticated with a certificate.
    pub mutual_auth: bool,
    /// The peer certificate's public key. If the profile restricts keys and this is
    /// `None`, the check reports [`Violation::PeerKeyUnknown`].
    pub peer_key: Option<PublicKey>,
    /// The peer certificate's validity period (notAfter − notBefore) in days.
    pub peer_cert_validity_days: Option<u32>,
    /// Whether Encrypt-then-MAC (RFC 7366) is in use. Only matters for CBC suites.
    pub encrypt_then_mac: Option<bool>,
}

impl Session {
    /// A session with this version and suite, and nothing else known.
    pub const fn new(version: TlsVersion, cipher_suite: CipherSuite) -> Self {
        Self {
            version,
            cipher_suite,
            group: None,
            signature_scheme: None,
            mutual_auth: false,
            peer_key: None,
            peer_cert_validity_days: None,
            encrypt_then_mac: None,
        }
    }
}

/// One way a session breaks a profile.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Violation {
    /// The protocol version is not allowed.
    Version(TlsVersion),
    /// The cipher suite is not allowed with this version.
    CipherSuite(CipherSuite),
    /// A TLS 1.3 suite with TLS 1.2, or the other way round.
    SuiteVersionMismatch(CipherSuite, TlsVersion),
    /// The key-exchange group is not allowed with this version.
    Group(NamedGroup),
    /// The profile restricts groups, but the session does not say which was used.
    GroupUnknown,
    /// The signature scheme is not allowed with this version.
    SignatureScheme(SignatureScheme),
    /// A CBC suite without Encrypt-then-MAC, which the profile requires.
    EncryptThenMacMissing,
    /// The profile requires mutual authentication and the client presented no certificate.
    MutualAuthMissing,
    /// The peer's certificate key is not allowed.
    PeerKey(PublicKey),
    /// The profile restricts certificate keys, but the session does not say which was used.
    PeerKeyUnknown,
    /// The peer's certificate is valid for longer than the profile allows.
    CertValidity {
        /// The certificate's validity in days.
        days: u32,
        /// The profile's maximum.
        max: u32,
    },
}

impl fmt::Display for Violation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Version(v) => write!(f, "{v} is not allowed"),
            Self::CipherSuite(s) => write!(f, "cipher suite {s} is not allowed"),
            Self::SuiteVersionMismatch(s, v) => write!(f, "cipher suite {s} cannot be used with {v}"),
            Self::Group(g) => write!(f, "key-exchange group {g} is not allowed"),
            Self::GroupUnknown => f.write_str("the key-exchange group is restricted but was not reported"),
            Self::SignatureScheme(s) => write!(f, "signature scheme {s} is not allowed"),
            Self::EncryptThenMacMissing => f.write_str("a CBC cipher suite requires Encrypt-then-MAC"),
            Self::MutualAuthMissing => f.write_str("mutual authentication is required"),
            Self::PeerKey(k) => write!(f, "certificate key {k} is not allowed"),
            Self::PeerKeyUnknown => f.write_str("the certificate key is restricted but was not reported"),
            Self::CertValidity { days, max } => {
                write!(f, "certificate valid for {days} days, at most {max} allowed")
            }
        }
    }
}

/// The result of [`Profile::check`]: every violation found, without allocating.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Report {
    items: [Option<Violation>; Report::CAPACITY],
    len: usize,
    truncated: bool,
}

impl Report {
    /// The most violations one check can report: one per rule.
    pub const CAPACITY: usize = 8;

    const fn new() -> Self {
        Self { items: [None; Self::CAPACITY], len: 0, truncated: false }
    }

    fn push(&mut self, v: Violation) {
        match self.items.get_mut(self.len) {
            Some(slot) => {
                *slot = Some(v);
                self.len += 1;
            }
            None => self.truncated = true,
        }
    }

    /// Whether the session satisfies the profile. Never true for a truncated report.
    pub const fn is_ok(&self) -> bool {
        self.len == 0 && !self.truncated
    }

    /// Whether more violations were found than the report holds.
    pub const fn truncated(&self) -> bool {
        self.truncated
    }

    /// The violations, in rule order.
    pub fn violations(&self) -> impl Iterator<Item = Violation> + '_ {
        self.items.iter().take(self.len).filter_map(|v| *v)
    }
}

/// What an endpoint is configured to offer: the lists it sends in its hello.
///
/// The lists are shared by all enabled versions, as in a real ClientHello. Each item is
/// judged against every enabled version it applies to.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Offer<'a> {
    /// Enabled protocol versions.
    pub versions: &'a [TlsVersion],
    /// Enabled cipher suites, both versions together.
    pub cipher_suites: &'a [CipherSuite],
    /// `supported_groups`.
    pub groups: &'a [NamedGroup],
    /// `signature_algorithms`.
    pub signature_schemes: &'a [SignatureScheme],
    /// `signature_algorithms_cert`. Left empty, it is taken to equal `signature_schemes`
    /// (RFC 8446 §4.2.3) and checked against the certificate signature rules too.
    pub cert_signature_schemes: &'a [SignatureScheme],
}

/// One offered or configurable item.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Item {
    /// A protocol version.
    Version(TlsVersion),
    /// A cipher suite.
    CipherSuite(CipherSuite),
    /// A key-exchange group.
    Group(NamedGroup),
    /// A handshake signature scheme.
    SignatureScheme(SignatureScheme),
    /// A certificate signature scheme.
    CertSignatureScheme(SignatureScheme),
}

impl fmt::Display for Item {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Version(v) => write!(f, "{v}"),
            Self::CipherSuite(s) => write!(f, "cipher suite {s}"),
            Self::Group(g) => write!(f, "group {g}"),
            Self::SignatureScheme(s) => write!(f, "signature scheme {s}"),
            Self::CertSignatureScheme(s) => write!(f, "certificate signature scheme {s}"),
        }
    }
}

/// One way a configuration breaks a profile.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Finding {
    /// The profile requires this item and the configuration does not offer it.
    Missing(Item),
    /// The configuration offers an item that no enabled version allows.
    NotAllowed(Item),
    /// The item is allowed with one enabled version but not with this one. One shared list
    /// (as in OpenSSL's `SignatureAlgorithms`) cannot satisfy both; restrict it per version
    /// where the library allows, or rely on the session check.
    NotAllowedWith(Item, TlsVersion),
}

impl fmt::Display for Finding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Missing(i) => write!(f, "{i} is required but not offered"),
            Self::NotAllowed(i) => write!(f, "{i} is offered but not allowed"),
            Self::NotAllowedWith(i, v) => write!(f, "{i} is offered but not allowed with {v}"),
        }
    }
}

fn restricted<T>(a: &Allowed<T>) -> bool {
    matches!(a, Allowed::Only { .. })
}

fn required_items(r: VersionRules) -> impl Iterator<Item = Item> {
    let suites = r.cipher_suites.required().iter().map(|&s| Item::CipherSuite(s));
    let groups = r.groups.required().iter().map(|&g| Item::Group(g));
    let sigs = r.signature_schemes.required().iter().map(|&s| Item::SignatureScheme(s));
    let certs = r.cert_signature_schemes.required().iter().map(|&s| Item::CertSignatureScheme(s));
    suites.chain(groups).chain(sigs).chain(certs)
}

/// Whether an item can be used with this version at all: Brainpool has separate code points
/// for TLS 1.2 (26–28, RFC 7027) and TLS 1.3 (31–33 and the `…tls13` schemes, RFC 8734).
fn applies(item: Item, version: TlsVersion) -> bool {
    let tls13 = version == TlsVersion::TLS13;
    match item {
        Item::Version(v) => v == version,
        Item::CipherSuite(s) => s.is_tls13() == tls13,
        Item::Group(g) => match g.0 {
            26..=28 => !tls13,
            31..=33 => tls13,
            _ => true,
        },
        Item::SignatureScheme(s) | Item::CertSignatureScheme(s) => tls13 || !matches!(s.0, 0x081A..=0x081C),
    }
}

fn rules_allow(version: TlsVersion, r: &VersionRules, item: Item) -> bool {
    match item {
        Item::Version(v) => v == version,
        Item::CipherSuite(s) => s.is_tls13() == (version == TlsVersion::TLS13) && r.cipher_suites.allows(&s),
        Item::Group(g) => r.groups.allows(&g),
        Item::SignatureScheme(s) => r.signature_schemes.allows(&s),
        Item::CertSignatureScheme(s) => r.cert_signature_schemes.allows(&s),
    }
}

impl Offer<'_> {
    fn cert_schemes(&self) -> &[SignatureScheme] {
        if self.cert_signature_schemes.is_empty() {
            self.signature_schemes
        } else {
            self.cert_signature_schemes
        }
    }

    fn offers(&self, item: Item) -> bool {
        match item {
            Item::Version(v) => self.versions.contains(&v),
            Item::CipherSuite(s) => self.cipher_suites.contains(&s),
            Item::Group(g) => self.groups.contains(&g),
            Item::SignatureScheme(s) => self.signature_schemes.contains(&s),
            Item::CertSignatureScheme(s) => self.cert_schemes().contains(&s),
        }
    }

    /// Every offered item, and whether it is a certificate scheme defaulted from the
    /// handshake list (RFC 8446 §4.2.3: an absent `signature_algorithms_cert` means the
    /// `signature_algorithms` list applies to certificates too).
    fn items(&self) -> impl Iterator<Item = (Item, bool)> + '_ {
        let suites = self.cipher_suites.iter().map(|&s| (Item::CipherSuite(s), false));
        let groups = self.groups.iter().map(|&g| (Item::Group(g), false));
        let sigs = self.signature_schemes.iter().map(|&s| (Item::SignatureScheme(s), false));
        let defaulted = self.cert_signature_schemes.is_empty();
        let certs = self.cert_schemes().iter().map(move |&s| (Item::CertSignatureScheme(s), defaulted));
        suites.chain(groups).chain(sigs).chain(certs)
    }
}

impl Profile {
    /// Check a negotiated session against this profile. Returns every violation, not
    /// only the first.
    pub fn check(&self, s: &Session) -> Report {
        let mut r = Report::new();
        match self.rules(s.version) {
            None => r.push(Violation::Version(s.version)),
            Some(rules) => {
                if s.cipher_suite.is_tls13() != (s.version == TlsVersion::TLS13) {
                    r.push(Violation::SuiteVersionMismatch(s.cipher_suite, s.version));
                } else if !rules.cipher_suites.allows(&s.cipher_suite) {
                    r.push(Violation::CipherSuite(s.cipher_suite));
                }
                match s.group {
                    Some(g) if !rules.groups.allows(&g) => r.push(Violation::Group(g)),
                    None if restricted(&rules.groups) => r.push(Violation::GroupUnknown),
                    _ => {}
                }
                if let Some(sig) = s.signature_scheme {
                    if !rules.signature_schemes.allows(&sig) {
                        r.push(Violation::SignatureScheme(sig));
                    }
                }
            }
        }
        if self.encrypt_then_mac == Level::Must && s.cipher_suite.is_cbc() && s.encrypt_then_mac != Some(true)
        {
            r.push(Violation::EncryptThenMacMissing);
        }
        if self.mutual_auth && !s.mutual_auth {
            r.push(Violation::MutualAuthMissing);
        }
        match s.peer_key {
            Some(k) if !self.cert.keys.iter().any(|rule| rule.accepts(k)) && restricted(&self.cert.keys) => {
                r.push(Violation::PeerKey(k));
            }
            None if restricted(&self.cert.keys) => r.push(Violation::PeerKeyUnknown),
            _ => {}
        }
        if let (Some(max), Some(days)) = (self.cert.max_validity_days, s.peer_cert_validity_days) {
            if days > max {
                r.push(Violation::CertValidity { days, max });
            }
        }
        r
    }

    /// Audit what an endpoint is configured to offer: every item the profile requires
    /// that is missing, and every offered item it does not allow. Run it once at
    /// start-up, or in a test against your TLS library's configuration.
    ///
    /// ```
    /// use utility_pki::profiles::BSI_TR_03116_3;
    /// use utility_pki::{CipherSuite, Offer, TlsVersion};
    ///
    /// let offer = Offer {
    ///     versions: &[TlsVersion::TLS12],
    ///     cipher_suites: &[CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256],
    ///     ..Offer::default()
    /// };
    /// for finding in BSI_TR_03116_3.audit(&offer) {
    ///     println!("{finding}");
    /// }
    /// assert!(BSI_TR_03116_3.audit(&offer).next().is_some());
    /// ```
    pub fn audit<'a>(&'a self, offer: &'a Offer<'a>) -> impl Iterator<Item = Finding> + 'a {
        // The versions both allowed here and enabled in the offer.
        let active = move || {
            self.versions()
                .filter(|v| offer.versions.contains(v))
                .filter_map(|v| self.rules(v).map(|r| (v, *r)))
        };

        let missing_versions = self
            .versions()
            .filter(move |&v| {
                self.rules(v).is_some_and(|r| r.support == Level::Must) && !offer.versions.contains(&v)
            })
            .map(|v| Finding::Missing(Item::Version(v)));

        // A required item shared by both versions (e.g. secp256r1) is reported once.
        let missing_items = active().enumerate().flat_map(move |(i, (_, rules))| {
            required_items(rules)
                .filter(move |&item| !offer.offers(item))
                .filter(move |&item| {
                    !active().take(i).any(|(_, earlier)| required_items(earlier).any(|x| x == item))
                })
                .map(Finding::Missing)
        });

        let versions_not_allowed = offer
            .versions
            .iter()
            .filter(move |&&v| self.rules(v).is_none())
            .map(|&v| Finding::NotAllowed(Item::Version(v)));

        // Each offered item is judged against every enabled version it applies to.
        let verdict = move |item: Item| {
            let applicable = move || active().filter(move |&(v, _)| applies(item, v));
            let allowed_somewhere = applicable().any(|(v, rules)| rules_allow(v, &rules, item));
            let nowhere = (!allowed_somewhere).then_some(Finding::NotAllowed(item));
            let somewhere_not = applicable()
                .filter(move |(v, rules)| allowed_somewhere && !rules_allow(*v, rules, item))
                .map(move |(v, _)| Finding::NotAllowedWith(item, v));
            nowhere.into_iter().chain(somewhere_not)
        };
        let items_not_allowed = offer.items().flat_map(move |(item, defaulted)| {
            // A defaulted certificate scheme already reported as a handshake scheme is not
            // reported twice.
            let duplicate = match item {
                Item::CertSignatureScheme(s) if defaulted => {
                    verdict(Item::SignatureScheme(s)).next().is_some()
                }
                _ => false,
            };
            verdict(item).filter(move |_| !duplicate)
        });

        missing_versions.chain(missing_items).chain(versions_not_allowed).chain(items_not_allowed)
    }
}