coqui_peer_tls/policy.rs
1use alloc::sync::Arc;
2use core::fmt;
3use core::str::FromStr;
4
5use rustls::crypto::CryptoProvider;
6
7use crate::error::PeerError;
8use crate::profiles::{CipherProfile, Crypto};
9use coqui_builder::Describe;
10use coqui_builder::NonDefault;
11use coqui_peer::{Digest, PeerId, WaitingLimits};
12
13/// A TLS protocol version. rustls offers 1.2 and 1.3 only: SSL 3, TLS 1.0 and 1.1 cannot be
14/// offered by this crate, and asking for them is an error, never ignored.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16#[non_exhaustive]
17pub enum TlsVersion {
18 /// TLS 1.2, text `"1.2"`.
19 V1_2,
20 /// TLS 1.3, text `"1.3"`.
21 V1_3,
22}
23
24impl TlsVersion {
25 /// The text form: `1.2` or `1.3`.
26 pub const fn as_str(self) -> &'static str {
27 match self {
28 Self::V1_2 => "1.2",
29 Self::V1_3 => "1.3",
30 }
31 }
32}
33
34impl fmt::Display for TlsVersion {
35 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
36 formatter.write_str(self.as_str())
37 }
38}
39
40impl FromStr for TlsVersion {
41 type Err = PeerError;
42
43 fn from_str(value: &str) -> Result<Self, Self::Err> {
44 match value.trim() {
45 "1.2" => Ok(Self::V1_2),
46 "1.3" => Ok(Self::V1_3),
47 "1.0" | "1.1" | "ssl3" | "SSL3" => Err(PeerError::Policy(
48 "TLS before 1.2 is not supported: rustls offers only TLS 1.2 and 1.3".to_owned(),
49 )),
50 _ => Err(PeerError::Policy(
51 "unknown TLS version; supported: \"1.2\", \"1.3\"".to_owned(),
52 )),
53 }
54 }
55}
56
57/// What a peer authenticates with: an X.509 certificate, or a raw public key (RFC 7250).
58///
59/// Text form: `x509`, `raw_public_key`. The choice is the whole connection's: both directions
60/// use it (the server's own, and the client's when it presents an identity), negotiated with
61/// the `server_certificate_type` and `client_certificate_type` extensions. A peer that holds
62/// one type and meets a peer that holds the other is refused, by the side that finds out as
63/// [`Refusal::CertificateType`](crate::Refusal::CertificateType); rustls offers no list of both
64/// types.
65///
66/// With a raw public key the peer sends its `SubjectPublicKeyInfo` and nothing else: it has no
67/// dates, names, issuer or chain, so [`check_validity`](Policy::check_validity) and
68/// [`allow_chain_when_pinned`](Policy::allow_chain_when_pinned) have nothing to decide, trust
69/// that needs a certificate ([`Trust::Roots`](crate::Trust::Roots), the CA trusts) is a
70/// [`PeerError::Policy`], and a peer is pinned by the SHA-256 id of its `SubjectPublicKeyInfo`.
71/// rustls verifies a raw key in TLS 1.3 only, so only TLS 1.3 is offered whatever
72/// [`tls_versions`](Policy::tls_versions) lists, and a policy without it is a
73/// [`PeerError::Policy`]. The cipher profiles apply as to a certificate: the key must sign with a
74/// scheme the profile verifies (`cnsa-1.0` takes ECDSA P-384, `cnsa-2.0` ML-DSA-87).
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum CertificateType {
78 /// `x509`: a certificate, as before. The default.
79 #[default]
80 X509,
81 /// `raw_public_key`: the key alone, RFC 7250.
82 RawPublicKey,
83}
84
85impl CertificateType {
86 /// The text form: `x509` or `raw_public_key`.
87 pub const fn as_str(self) -> &'static str {
88 match self {
89 Self::X509 => "x509",
90 Self::RawPublicKey => "raw_public_key",
91 }
92 }
93}
94
95impl fmt::Display for CertificateType {
96 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
97 formatter.write_str(self.as_str())
98 }
99}
100
101impl FromStr for CertificateType {
102 type Err = PeerError;
103
104 fn from_str(value: &str) -> Result<Self, Self::Err> {
105 match value.trim() {
106 "x509" => Ok(Self::X509),
107 "raw_public_key" => Ok(Self::RawPublicKey),
108 _ => Err(PeerError::Policy(
109 "unknown certificate type; known: x509, raw_public_key".to_owned(),
110 )),
111 }
112 }
113}
114
115/// Whether a client's `ClientHello` offers raw public keys (RFC 7250) in either direction: the
116/// server certificate type it will accept, or the client certificate type it will send.
117///
118/// A server that serves peers of both types on one port chooses between a raw-public-key
119/// configuration and an X.509 one by this, in the function it gives to
120/// `asynch::accept_with` (feature `tokio`) or a rustls `Acceptor`: rustls offers one
121/// certificate type per configuration, not a choice.
122pub fn offers_raw_public_key(hello: &rustls::server::ClientHello<'_>) -> bool {
123 use rustls::server::CertificateType as Offered;
124 let raw = |types: Option<&[Offered]>| {
125 types.is_some_and(|types| types.contains(&Offered::RawPublicKey))
126 };
127 raw(hello.server_cert_types()) || raw(hello.client_cert_types())
128}
129
130/// What a TLS configuration and a trust decision are allowed to do.
131///
132/// Start from [`Policy::modern`], [`Policy::intermediate`], [`Policy::legacy`] or a policy of
133/// your own, then change any field. [`Default`] is intermediate (TLS 1.2 and 1.3). Nothing is
134/// silently non-default: [`non_defaults`](Policy::non_defaults) lists every setting that differs from
135/// the default, and the configuration builders return that list.
136///
137/// A policy is [`Describe`]: its keys' defaults are the intermediate preset's, so a document
138/// names only what differs, and an unknown key is refused. A `coqui_builder::Partial<Policy>` is
139/// filled from text and built; with the `serde` feature the policy itself is also read through any
140/// serde format (it is not written).
141///
142/// The struct is `#[non_exhaustive]`: start from a preset and assign the fields to change.
143#[derive(Debug, Clone, PartialEq, Eq, Describe)]
144#[map(deny_unknown_fields)]
145#[non_exhaustive]
146pub struct Policy {
147 /// TLS versions offered and accepted. Non-empty.
148 #[map(default = base().tls_versions, as_text)]
149 pub tls_versions: Vec<TlsVersion>,
150 /// An allow-list of cipher suites by IANA name, for example `TLS13_AES_256_GCM_SHA384`.
151 /// `None` allows every suite the cipher profiles give for [`tls_versions`](Self::tls_versions).
152 /// An unknown name is an error that lists the supported ones.
153 pub cipher_suites: Option<Vec<String>>,
154 /// An allow-list of key-exchange groups by name, for example `X25519`; `None` allows all
155 /// the cipher profiles give.
156 pub kx_groups: Option<Vec<String>>,
157 /// The algorithm profiles allowed; what is offered is their union, in the order of the
158 /// first listed, narrowed by the versions, the provider, [`cipher_suites`](Self::cipher_suites)
159 /// and [`kx_groups`](Self::kx_groups). Every preset allows `[CipherProfile::Mozilla]`. Text
160 /// key `cipher_profiles`.
161 #[map(default = base().cipher_profiles, as_text)]
162 pub cipher_profiles: Vec<CipherProfile>,
163 /// The crypto provider; `Crypto::Ring` in every preset. Text key `crypto`.
164 #[map(default = base().crypto, as_text)]
165 pub crypto: Crypto,
166 /// What peers authenticate with: [`CertificateType::X509`] (the default in every preset) or
167 /// [`CertificateType::RawPublicKey`]. Text key `certificate`.
168 #[map(default = base().certificate, as_text)]
169 pub certificate: CertificateType,
170 /// Digests a pin may use. Pins are compared in constant time whatever their digest.
171 #[map(default = base().pin_digests)]
172 pub pin_digests: Vec<Digest>,
173 /// Whether a pinned certificate must be inside its validity dates.
174 #[map(default = base().check_validity)]
175 pub check_validity: bool,
176 /// Whether a pinned peer may present a chain; strict refuses one.
177 #[map(default = base().allow_chain_when_pinned)]
178 pub allow_chain_when_pinned: bool,
179 /// Whether TLS sessions may be resumed. A resumed handshake skips the certificate
180 /// verifiers, so a peer removed from the trust store or no longer pinned can reconnect
181 /// on a session it already holds, and the access control list's fingerprint rules are not
182 /// checked again (its address rules are). Every preset leaves it off; `non_defaults` reports it.
183 #[map(default = base().allow_resumption)]
184 pub allow_resumption: bool,
185 /// Whether a TLS 1.2 connection must use the extended master secret (RFC 7627). Without it
186 /// a TLS 1.2 session's keys and exporter are not bound to its handshake, which an attacker
187 /// can use to synchronise two sessions (the triple handshake). `modern` and `intermediate`
188 /// set it; `legacy` does not, for TLS 1.2 stacks older than RFC 7627. TLS 1.3 needs nothing
189 /// like it.
190 #[map(default = base().require_ems)]
191 pub require_ems: bool,
192 /// The bounds of a store-backed pin set's waiting queue: entries per source, entries in
193 /// all, and how long before the same certificate from the same source is recorded again.
194 /// In the text form a table: `per_source`, `total` and `rerecord` (a duration, a number of
195 /// seconds in a hand-written document).
196 #[map(default = base().waiting)]
197 pub waiting: WaitingLimits,
198 /// An ordered access control list for connecting clients, applied by every server
199 /// configuration built under this policy: by address when the `ClientHello` arrives
200 /// ([`Refusal::AddressDenied`](crate::Refusal::AddressDenied)) and by the client
201 /// certificate's fingerprint before the trust store is consulted
202 /// ([`Refusal::PeerDenied`](crate::Refusal::PeerDenied)). Its fingerprints may be written
203 /// in any spelling a [`PeerId`] parses, and are made canonical where a configuration is
204 /// built or a policy is read through serde; a
205 /// rule naming something else, or a digest other than SHA-256, is an error there and in
206 /// [`check`](Policy::check). `None` for none.
207 #[cfg(feature = "acl")]
208 pub acl: Option<coqui_net_acl::Acl>,
209}
210
211impl Default for Policy {
212 fn default() -> Self {
213 Self::intermediate()
214 }
215}
216
217impl Policy {
218 /// The intermediate preset, the default: TLS 1.2 and 1.3 (TLS 1.2 with ECDHE, AEAD suites
219 /// and the extended master secret); pins SHA-256, SHA-384 or SHA-512; validity dates
220 /// checked; no chain on a pinned path; no session resumption; waiting queues capped.
221 ///
222 /// Two peers that both allow TLS 1.3 negotiate it, and the TLS 1.3 downgrade protection
223 /// keeps an attacker from forcing 1.2 between them; allowing 1.2 only admits peers that
224 /// cannot speak 1.3.
225 pub fn intermediate() -> Self {
226 Self {
227 tls_versions: vec![TlsVersion::V1_2, TlsVersion::V1_3],
228 cipher_suites: None,
229 kx_groups: None,
230 cipher_profiles: vec![CipherProfile::Mozilla],
231 crypto: Crypto::Ring,
232 certificate: CertificateType::X509,
233 pin_digests: vec![Digest::Sha256, Digest::Sha384, Digest::Sha512],
234 check_validity: true,
235 allow_chain_when_pinned: false,
236 allow_resumption: false,
237 require_ems: true,
238 waiting: WaitingLimits::default(),
239 #[cfg(feature = "acl")]
240 acl: None,
241 }
242 }
243
244 /// The modern preset: intermediate with TLS 1.3 only. A choice, never required: it
245 /// refuses peers that speak only TLS 1.2, and keeps client certificates from passive
246 /// observers when such peers would otherwise be served (TLS 1.2 sends the client's
247 /// certificate unencrypted).
248 pub fn modern() -> Self {
249 Self {
250 tls_versions: vec![TlsVersion::V1_3],
251 ..Self::intermediate()
252 }
253 }
254
255 /// The legacy preset: intermediate, and SHA-1 pins and TLS 1.2 without the extended master
256 /// secret accepted, for interoperability with old peers only. A peer that cannot take a
257 /// TLS 1.3 `ClientHello` at all is served by setting `tls_versions` to TLS 1.2 alone.
258 pub fn legacy() -> Self {
259 let mut policy = Self::intermediate();
260 policy.pin_digests.push(Digest::Sha1);
261 policy.require_ems = false;
262 policy
263 }
264
265 /// The built-in preset called `name`: `modern`, `intermediate` or `legacy`.
266 ///
267 /// # Errors
268 ///
269 /// [`PeerError::Policy`] for any other name.
270 pub fn preset(name: &str) -> Result<Self, PeerError> {
271 match name.trim() {
272 "modern" => Ok(Self::modern()),
273 "intermediate" => Ok(Self::intermediate()),
274 "legacy" => Ok(Self::legacy()),
275 _ => Err(PeerError::Policy(
276 "unknown profile; built in: modern, intermediate, legacy".to_owned(),
277 )),
278 }
279 }
280}
281
282fn list<T: fmt::Display>(items: &[T]) -> String {
283 items
284 .iter()
285 .map(ToString::to_string)
286 .collect::<Vec<_>>()
287 .join(",")
288}
289
290impl Policy {
291 /// Every setting that differs from the default (intermediate) preset, as plain data named by
292 /// its key (`waiting.per_source`, `tls_versions`). Empty for `intermediate`; `modern` reports
293 /// `tls_versions` and `legacy` reports `pin_digests` and `require_ems`. A value prints as its
294 /// type and text (`bool(true)`, `[TlsVersion(1.3)]`). With the `acl` feature, a list present is
295 /// one entry, `acl`; `coqui_builder::non_defaults` over the list reports its own settings.
296 pub fn non_defaults(&self) -> Vec<NonDefault> {
297 coqui_builder::non_defaults(self)
298 }
299
300 /// As [`non_defaults`](Self::non_defaults), against `baseline` instead of the defaults, for a
301 /// consumer whose own baseline differs from them (`non_defaults_against(&Policy::modern())`
302 /// reports TLS 1.2).
303 pub fn non_defaults_against(&self, baseline: &Self) -> Vec<NonDefault> {
304 coqui_builder::differences(&Policy::description(), self, Some(baseline))
305 .findings()
306 .iter()
307 .map(NonDefault::from)
308 .collect()
309 }
310
311 /// Whether the access control list admits, by address, a client from `source` to `local`
312 /// that will present a certificate: a rule naming a fingerprint defers to the handshake.
313 /// Without a list, every address is admitted. For a host that refuses a connection before
314 /// its handshake, such as a quinn `Incoming`.
315 ///
316 /// # Errors
317 ///
318 /// [`Refusal::AddressDenied`](crate::Refusal::AddressDenied) with the deciding rule.
319 #[cfg(feature = "acl")]
320 pub fn admits_address(
321 &self,
322 source: core::net::SocketAddr,
323 local: core::net::SocketAddr,
324 ) -> Result<(), crate::Refusal> {
325 match &self.acl {
326 Some(acl) => crate::gate::decide_address(acl, source, local, true),
327 None => Ok(()),
328 }
329 }
330
331 /// [`admits_address`](Policy::admits_address) for a client that proves no identity at the
332 /// TLS layer: rules naming a fingerprint cannot match it.
333 ///
334 /// # Errors
335 ///
336 /// [`Refusal::AddressDenied`](crate::Refusal::AddressDenied) with the deciding rule.
337 #[cfg(feature = "acl")]
338 pub fn admits_anonymous(
339 &self,
340 source: core::net::SocketAddr,
341 local: core::net::SocketAddr,
342 ) -> Result<(), crate::Refusal> {
343 match &self.acl {
344 Some(acl) => crate::gate::decide_address(acl, source, local, false),
345 None => Ok(()),
346 }
347 }
348
349 /// Whether this policy lets a pin use the digest of `fingerprint`.
350 ///
351 /// # Errors
352 ///
353 /// [`PeerError::Policy`] naming the digest and the allowed ones.
354 pub fn check_pin(&self, fingerprint: &PeerId) -> Result<(), PeerError> {
355 if self.pin_digests.contains(&fingerprint.digest()) {
356 return Ok(());
357 }
358 Err(PeerError::Policy(format!(
359 "a {} pin is not allowed by this policy; allowed digests: {}",
360 fingerprint.digest(),
361 list(&self.pin_digests)
362 )))
363 }
364
365 /// Checks this policy as building a configuration under it does, without building one:
366 /// its versions, cipher profiles, cipher suites and key-exchange groups against the crypto
367 /// provider and this build, and, with the `acl` feature, that every fingerprint of its
368 /// access control list is a SHA-256 peer id. A host that builds its configurations later
369 /// (one per connection) checks the policy it read with this.
370 ///
371 /// # Errors
372 ///
373 /// [`PeerError::Policy`] naming the first setting that fails, as a configuration builder
374 /// would report it.
375 pub fn check(&self) -> Result<(), PeerError> {
376 crate::profiles::select(self)?;
377 #[cfg(feature = "acl")]
378 if let Some(acl) = &self.acl {
379 crate::gate::canonical(acl)?;
380 }
381 Ok(())
382 }
383
384 /// The provider, versions and FIPS requirement to build a configuration with.
385 pub(crate) fn selection(&self) -> Result<crate::profiles::Selection, PeerError> {
386 crate::profiles::select(self)
387 }
388
389 /// The crypto provider ([`crypto`](Self::crypto)) narrowed to what this policy offers: the
390 /// union of its [`cipher_profiles`](Self::cipher_profiles), its versions, and its
391 /// [`cipher_suites`](Self::cipher_suites) and [`kx_groups`](Self::kx_groups) when set.
392 ///
393 /// # Errors
394 ///
395 /// [`PeerError::Policy`] for an unknown suite or group name (listing the supported ones), a
396 /// provider or profile this build lacks, or when no suite or no group is left.
397 pub fn crypto_provider(&self) -> Result<Arc<CryptoProvider>, PeerError> {
398 Ok(self.selection()?.provider)
399 }
400
401 /// The cipher suite IANA names the provider this policy selects can offer, for choosing
402 /// [`cipher_suites`](Self::cipher_suites) from.
403 ///
404 /// # Errors
405 ///
406 /// [`PeerError::Policy`] when this build lacks that provider.
407 pub fn supported_cipher_suites(&self) -> Result<Vec<String>, PeerError> {
408 Ok(crate::profiles::supported(self)?.0)
409 }
410
411 /// The key-exchange group names the provider this policy selects can offer, for choosing
412 /// [`kx_groups`](Self::kx_groups) from.
413 ///
414 /// # Errors
415 ///
416 /// [`PeerError::Policy`] when this build lacks that provider.
417 pub fn supported_kx_groups(&self) -> Result<Vec<String>, PeerError> {
418 Ok(crate::profiles::supported(self)?.1)
419 }
420}
421
422/// The preset every field of a document defaults to.
423fn base() -> Policy {
424 Policy::intermediate()
425}
426
427#[cfg(feature = "serde")]
428mod text {
429 use coqui_builder::Partial;
430 use serde::de::Error as _;
431 use serde::{Deserialize, Deserializer};
432
433 use super::{Policy, base};
434
435 impl Policy {
436 /// Reads a policy document over `base` instead of the intermediate preset: the keys it
437 /// names replace the base's (a table such as `waiting` key by key, a list whole), and the
438 /// rest are kept. A consumer with its own default profile reads its configuration with
439 /// this.
440 ///
441 /// # Errors
442 ///
443 /// The deserializer's error for an unknown key or a value of the wrong type or form, and,
444 /// with the `acl` feature, for a rule whose fingerprint is not a SHA-256 peer id; the
445 /// list's fingerprints are made canonical.
446 pub fn deserialize_over<'de, D: Deserializer<'de>>(
447 base: Policy,
448 deserializer: D,
449 ) -> Result<Policy, D::Error> {
450 let mut partial = Partial::from(base);
451 partial.overlay(Partial::<Policy>::deserialize(deserializer)?);
452 #[cfg_attr(not(feature = "acl"), expect(unused_mut))]
453 let mut policy = partial.build().map_err(D::Error::custom)?;
454 #[cfg(feature = "acl")]
455 if let Some(acl) = &policy.acl {
456 policy.acl = Some(crate::gate::canonical(acl).map_err(D::Error::custom)?);
457 }
458 Ok(policy)
459 }
460 }
461
462 impl<'de> Deserialize<'de> for Policy {
463 /// Reads the document over the intermediate preset.
464 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
465 Policy::deserialize_over(base(), deserializer)
466 }
467 }
468}