1use core::fmt;
5
6use crate::ids::{CipherSuite, NamedGroup, SignatureScheme, TlsVersion};
7use crate::profile::{Allowed, Level, Profile, PublicKey, VersionRules};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub struct Session {
24 pub version: TlsVersion,
26 pub cipher_suite: CipherSuite,
28 pub group: Option<NamedGroup>,
31 pub signature_scheme: Option<SignatureScheme>,
33 pub mutual_auth: bool,
35 pub peer_key: Option<PublicKey>,
38 pub peer_cert_validity_days: Option<u32>,
40 pub encrypt_then_mac: Option<bool>,
42}
43
44impl Session {
45 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62#[non_exhaustive]
63pub enum Violation {
64 Version(TlsVersion),
66 CipherSuite(CipherSuite),
68 SuiteVersionMismatch(CipherSuite, TlsVersion),
70 Group(NamedGroup),
72 GroupUnknown,
74 SignatureScheme(SignatureScheme),
76 EncryptThenMacMissing,
78 MutualAuthMissing,
80 PeerKey(PublicKey),
82 PeerKeyUnknown,
84 CertValidity {
86 days: u32,
88 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#[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 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 pub const fn is_ok(&self) -> bool {
141 self.len == 0 && !self.truncated
142 }
143
144 pub const fn truncated(&self) -> bool {
146 self.truncated
147 }
148
149 pub fn violations(&self) -> impl Iterator<Item = Violation> + '_ {
151 self.items.iter().take(self.len).filter_map(|v| *v)
152 }
153}
154
155#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
160pub struct Offer<'a> {
161 pub versions: &'a [TlsVersion],
163 pub cipher_suites: &'a [CipherSuite],
165 pub groups: &'a [NamedGroup],
167 pub signature_schemes: &'a [SignatureScheme],
169 pub cert_signature_schemes: &'a [SignatureScheme],
172}
173
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub enum Item {
177 Version(TlsVersion),
179 CipherSuite(CipherSuite),
181 Group(NamedGroup),
183 SignatureScheme(SignatureScheme),
185 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub enum Finding {
204 Missing(Item),
206 NotAllowed(Item),
208 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
236fn 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 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 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 pub fn audit<'a>(&'a self, offer: &'a Offer<'a>) -> impl Iterator<Item = Finding> + 'a {
360 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 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 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 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}