Skip to main content

coqui_peer_tls/profiles/
mod.rs

1//! Cipher profiles and crypto providers: which algorithms a policy allows, apart from its TLS
2//! versions, and the provider that runs them.
3
4use alloc::sync::Arc;
5use core::fmt;
6use core::str::FromStr;
7
8use rustls::crypto::{CryptoProvider, SupportedKxGroup};
9use rustls::{CipherSuite, NamedGroup, SupportedCipherSuite, SupportedProtocolVersion};
10
11use crate::error::PeerError;
12use crate::policy::{CertificateType, Policy, TlsVersion};
13
14mod tables;
15
16/// A named set of algorithms a [`Policy`] allows: cipher suites, key-exchange groups and
17/// signature schemes, each profile exactly what its name claims.
18///
19/// A policy lists the profiles it allows ([`Policy::cipher_profiles`]); what it offers is their
20/// union, in the order of the first listed, narrowed to its TLS versions, to what the crypto
21/// provider has, and to [`Policy::cipher_suites`] and [`Policy::kx_groups`] when set. A TLS
22/// version left with no suite is dropped; none left is [`PeerError::Policy`]. Profiles are
23/// choices, not non-default settings: [`Policy::non_defaults`] does not report them.
24///
25/// Text form: `mozilla`, `fips-140-3-compliant`, `fips-140-2-compliant`, `fips-140-3-validated`,
26/// `cnsa-1.0`, `cnsa-2.0`.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28#[non_exhaustive]
29pub enum CipherProfile {
30    /// `mozilla`: Mozilla's server-side TLS guideline 6.0, intermediate (which holds modern's):
31    /// TLS 1.3 AES-128-GCM, AES-256-GCM and ChaCha20-Poly1305; TLS 1.2 ECDHE-ECDSA and
32    /// ECDHE-RSA with the same three, in Mozilla's order; X25519MLKEM768 (`aws-lc` only),
33    /// X25519, P-256 and P-384; every signature scheme the provider verifies. The default.
34    Mozilla,
35    /// `fips-140-3-compliant`: the FIPS 140-3 approved algorithms for TLS, per NIST SP 800-52
36    /// Rev. 2 and SP 800-131A Rev. 2: TLS 1.3 AES-128-GCM and AES-256-GCM; TLS 1.2 ECDHE-ECDSA
37    /// and ECDHE-RSA with AES-GCM; P-256 and P-384, and with `aws-lc` SecP256r1MLKEM768,
38    /// X25519MLKEM768, MLKEM768 and MLKEM1024; RSA-PSS and RSA PKCS#1 with SHA-256/384/512,
39    /// ECDSA P-256 with SHA-256 and P-384 with SHA-384. No ChaCha20, no X25519 alone, no
40    /// Ed25519, no ML-DSA. **Algorithm selection only; not a FIPS 140-3 validated module;
41    /// makes no validation claim.** It works on either provider.
42    Fips1403Compliant,
43    /// `fips-140-2-compliant`: `fips-140-3-compliant` without the ML-KEM groups, which only a
44    /// FIPS 140-3 module can have approved. Algorithm selection only, no validation claim. On
45    /// `ring` the two lists are the same. Every FIPS 140-2 certificate moved to the CMVP
46    /// Historical List in September 2026 (usable for existing systems only); the TLS rules
47    /// themselves (SP 800-52r2, SP 800-131A) are the same for both.
48    Fips1402Compliant,
49    /// `fips-140-3-validated`: the `fips-140-3-compliant` list on rustls's FIPS provider
50    /// (AWS-LC's FIPS module, feature `fips`), whatever [`Policy::crypto`] says. Listed alone
51    /// or with others, the configuration uses that provider, keeps only what the module
52    /// reports approved (so other listed profiles lose ChaCha20 and X25519), and is refused
53    /// unless rustls reports it FIPS (`ClientConfig::fips()` / `ServerConfig::fips()`, which
54    /// also needs [`Policy::require_ems`]). Validated only as AWS-LC's CMVP certificate and
55    /// its tested operating environments state. Without the feature it is
56    /// [`PeerError::Policy`]; [`CipherProfile::FIPS_VALIDATED_AVAILABLE`] says which.
57    Fips1403Validated,
58    /// `cnsa-1.0`: NSA's CNSA 1.0 (CNSSP 15, RFC 9151) as far as rustls goes, on either
59    /// provider: TLS 1.3 AES-256-GCM-SHA384; TLS 1.2 ECDHE-ECDSA and ECDHE-RSA
60    /// AES-256-GCM-SHA384; secp384r1; ECDSA P-384 with SHA-384, RSA-PSS with SHA-384 and RSA
61    /// PKCS#1 with SHA-384 (keys of 3072 bits or more). Not met: the static-RSA and DHE suites
62    /// and the ffdhe3072/4096 groups RFC 9151 also lists (absent from rustls, and SP 800-131A
63    /// disallows static RSA), and the 3072-bit floor for RSA-PSS keys (2048-bit keys pass).
64    /// Needs an identity of P-384 or RSA 3072+: generated identities are P-256.
65    Cnsa1,
66    /// `cnsa-2.0`: NSA's CNSA 2.0 (ML-KEM-1024, ML-DSA-87, AES-256, SHA-384) in the TLS shape of
67    /// draft-becker-cnsa2-tls-profile-05: TLS 1.3 only, AES-256-GCM-SHA384, MLKEM1024 only,
68    /// ML-DSA-87 only. Met in full with [`Crypto::AwsLc`]; with `ring`, which has no ML-KEM
69    /// or ML-DSA, it is [`PeerError::Policy`]. The ML-KEM-768 hybrids are category 3, not CNSA
70    /// 2.0, and are left out; SecP384r1MLKEM1024 is not in rustls and the draft does not use it.
71    /// Certificates must be signed with ML-DSA-87 along the chain, so the consumer brings its
72    /// own identity and CA. The TLS profile is an individual draft and this list follows it.
73    Cnsa2,
74}
75
76impl CipherProfile {
77    /// Every profile, in the order of the text form's documentation.
78    pub const ALL: &'static [CipherProfile] = &[
79        Self::Mozilla,
80        Self::Fips1403Compliant,
81        Self::Fips1402Compliant,
82        Self::Fips1403Validated,
83        Self::Cnsa1,
84        Self::Cnsa2,
85    ];
86
87    /// Whether this build has the FIPS module `fips-140-3-validated` needs (feature `fips`).
88    pub const FIPS_VALIDATED_AVAILABLE: bool = cfg!(feature = "fips");
89
90    /// The text form, such as `fips-140-3-compliant`.
91    pub const fn as_str(self) -> &'static str {
92        match self {
93            Self::Mozilla => "mozilla",
94            Self::Fips1403Compliant => "fips-140-3-compliant",
95            Self::Fips1402Compliant => "fips-140-2-compliant",
96            Self::Fips1403Validated => "fips-140-3-validated",
97            Self::Cnsa1 => "cnsa-1.0",
98            Self::Cnsa2 => "cnsa-2.0",
99        }
100    }
101
102    fn spec(self) -> &'static Spec {
103        match self {
104            Self::Mozilla => &MOZILLA,
105            Self::Fips1403Compliant | Self::Fips1403Validated => &FIPS_140_3,
106            Self::Fips1402Compliant => &FIPS_140_2,
107            Self::Cnsa1 => &CNSA_1,
108            Self::Cnsa2 => &CNSA_2,
109        }
110    }
111}
112
113impl fmt::Display for CipherProfile {
114    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
115        formatter.write_str(self.as_str())
116    }
117}
118
119impl FromStr for CipherProfile {
120    type Err = PeerError;
121
122    fn from_str(text: &str) -> Result<Self, Self::Err> {
123        Self::ALL
124            .iter()
125            .copied()
126            .find(|profile| profile.as_str() == text.trim())
127            .ok_or_else(|| {
128                let known: Vec<&str> = Self::ALL.iter().map(|profile| profile.as_str()).collect();
129                PeerError::Policy(format!(
130                    "unknown cipher profile; known: {}",
131                    known.join(", ")
132                ))
133            })
134    }
135}
136
137/// The crypto provider a policy's configurations run on.
138///
139/// A field of [`Policy`], not a build switch: a feature makes a provider available, and only
140/// a policy that asks for it uses it. Text form: `ring`, `aws-lc`.
141#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
142#[non_exhaustive]
143pub enum Crypto {
144    /// `ring`: rustls's ring provider. The default.
145    #[default]
146    Ring,
147    /// `aws-lc`: rustls's aws-lc-rs provider (feature `aws-lc`), which adds the ML-KEM groups
148    /// (X25519MLKEM768, SecP256r1MLKEM768, MLKEM768, MLKEM1024) and ML-DSA signatures. Without
149    /// the feature a policy asking for it is [`PeerError::Policy`].
150    AwsLc,
151}
152
153impl Crypto {
154    /// Whether this build has the aws-lc-rs provider (feature `aws-lc`).
155    pub const AWS_LC_AVAILABLE: bool = cfg!(feature = "aws-lc");
156
157    /// The text form: `ring` or `aws-lc`.
158    pub const fn as_str(self) -> &'static str {
159        match self {
160            Self::Ring => "ring",
161            Self::AwsLc => "aws-lc",
162        }
163    }
164}
165
166impl fmt::Display for Crypto {
167    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
168        formatter.write_str(self.as_str())
169    }
170}
171
172impl FromStr for Crypto {
173    type Err = PeerError;
174
175    fn from_str(text: &str) -> Result<Self, Self::Err> {
176        match text.trim() {
177            "ring" => Ok(Self::Ring),
178            "aws-lc" => Ok(Self::AwsLc),
179            _ => Err(PeerError::Policy(
180                "unknown crypto provider; known: ring, aws-lc".to_owned(),
181            )),
182        }
183    }
184}
185
186/// Which signature table a set of profiles needs.
187#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
188enum Signatures {
189    /// ML-DSA-87 only (CNSA 2.0); merged as a flag.
190    None,
191    Cnsa1,
192    Fips,
193    /// Every scheme the provider verifies.
194    All,
195}
196
197/// One profile's lists, in preference order.
198struct Spec {
199    tls13: &'static [CipherSuite],
200    tls12: &'static [CipherSuite],
201    groups: &'static [NamedGroup],
202    signatures: Signatures,
203    ml_dsa_87: bool,
204}
205
206const MOZILLA: Spec = Spec {
207    tls13: &[
208        CipherSuite::TLS13_AES_128_GCM_SHA256,
209        CipherSuite::TLS13_AES_256_GCM_SHA384,
210        CipherSuite::TLS13_CHACHA20_POLY1305_SHA256,
211    ],
212    tls12: &[
213        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
214        CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
215        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
216        CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
217        CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
218        CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
219    ],
220    groups: &[
221        NamedGroup::X25519MLKEM768,
222        NamedGroup::X25519,
223        NamedGroup::secp256r1,
224        NamedGroup::secp384r1,
225    ],
226    signatures: Signatures::All,
227    ml_dsa_87: false,
228};
229
230const FIPS_140_3: Spec = Spec {
231    tls13: &[
232        CipherSuite::TLS13_AES_128_GCM_SHA256,
233        CipherSuite::TLS13_AES_256_GCM_SHA384,
234    ],
235    tls12: &[
236        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
237        CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
238        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
239        CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
240    ],
241    groups: &[
242        NamedGroup::secp256r1MLKEM768,
243        NamedGroup::X25519MLKEM768,
244        NamedGroup::secp256r1,
245        NamedGroup::secp384r1,
246        NamedGroup::MLKEM768,
247        NamedGroup::MLKEM1024,
248    ],
249    signatures: Signatures::Fips,
250    ml_dsa_87: false,
251};
252
253const FIPS_140_2: Spec = Spec {
254    groups: &[NamedGroup::secp256r1, NamedGroup::secp384r1],
255    ..FIPS_140_3
256};
257
258const CNSA_1: Spec = Spec {
259    tls13: &[CipherSuite::TLS13_AES_256_GCM_SHA384],
260    tls12: &[
261        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
262        CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
263    ],
264    groups: &[NamedGroup::secp384r1],
265    signatures: Signatures::Cnsa1,
266    ml_dsa_87: false,
267};
268
269const CNSA_2: Spec = Spec {
270    tls13: &[CipherSuite::TLS13_AES_256_GCM_SHA384],
271    tls12: &[],
272    groups: &[NamedGroup::MLKEM1024],
273    signatures: Signatures::None,
274    ml_dsa_87: true,
275};
276
277/// The provider a policy's configurations are built with, and the TLS versions left.
278pub(crate) struct Selection {
279    pub(crate) provider: Arc<CryptoProvider>,
280    pub(crate) versions: Vec<&'static SupportedProtocolVersion>,
281    /// Whether a configuration must be one rustls reports FIPS (`fips-140-3-validated`).
282    pub(crate) validated: bool,
283}
284
285/// What a provider can offer: its every suite and group, and the provider to narrow.
286struct Pool {
287    provider: CryptoProvider,
288    suites: &'static [SupportedCipherSuite],
289    groups: &'static [&'static dyn SupportedKxGroup],
290    backend: Crypto,
291}
292
293impl Pool {
294    fn of(policy: &Policy, validated: bool) -> Result<Self, PeerError> {
295        if validated {
296            return Self::fips();
297        }
298        match policy.crypto {
299            Crypto::Ring => Ok(Self {
300                provider: rustls::crypto::ring::default_provider(),
301                suites: rustls::crypto::ring::ALL_CIPHER_SUITES,
302                groups: rustls::crypto::ring::ALL_KX_GROUPS,
303                backend: Crypto::Ring,
304            }),
305            #[cfg(feature = "aws-lc")]
306            Crypto::AwsLc => Ok(Self {
307                provider: rustls::crypto::aws_lc_rs::default_provider(),
308                suites: rustls::crypto::aws_lc_rs::ALL_CIPHER_SUITES,
309                groups: rustls::crypto::aws_lc_rs::ALL_KX_GROUPS,
310                backend: Crypto::AwsLc,
311            }),
312            #[cfg(not(feature = "aws-lc"))]
313            Crypto::AwsLc => Err(PeerError::Policy(
314                "crypto = \"aws-lc\" needs this build's aws-lc feature".to_owned(),
315            )),
316        }
317    }
318
319    #[cfg(feature = "fips")]
320    fn fips() -> Result<Self, PeerError> {
321        Ok(Self {
322            provider: rustls::crypto::default_fips_provider(),
323            suites: rustls::crypto::aws_lc_rs::ALL_CIPHER_SUITES,
324            groups: rustls::crypto::aws_lc_rs::ALL_KX_GROUPS,
325            backend: Crypto::AwsLc,
326        })
327    }
328
329    #[cfg(not(feature = "fips"))]
330    fn fips() -> Result<Self, PeerError> {
331        Err(PeerError::Policy(
332            "this build has no FIPS module: feature fips".to_owned(),
333        ))
334    }
335}
336
337/// The text name of a suite, its IANA name where rustls has one.
338pub(crate) fn suite_name(suite: &SupportedCipherSuite) -> String {
339    suite
340        .suite()
341        .as_str()
342        .map_or_else(|| format!("{:?}", suite.suite()), str::to_owned)
343}
344
345/// The text name of a key-exchange group, as rustls spells it (`X25519`, `secp256r1`).
346pub(crate) fn group_name(group: &&'static dyn SupportedKxGroup) -> String {
347    format!("{:?}", group.name())
348}
349
350fn version_of(suite: &SupportedCipherSuite) -> TlsVersion {
351    match suite {
352        SupportedCipherSuite::Tls13(_) => TlsVersion::V1_3,
353        SupportedCipherSuite::Tls12(_) => TlsVersion::V1_2,
354    }
355}
356
357/// The names `pool` knows, for an error listing them.
358fn known<T>(items: &[T], name: impl Fn(&T) -> String) -> String {
359    items.iter().map(name).collect::<Vec<_>>().join(", ")
360}
361
362/// The cipher suite and key-exchange group names the provider `policy` selects can offer.
363pub(crate) fn supported(policy: &Policy) -> Result<(Vec<String>, Vec<String>), PeerError> {
364    let validated = policy
365        .cipher_profiles
366        .contains(&CipherProfile::Fips1403Validated);
367    let pool = Pool::of(policy, validated)?;
368    Ok((
369        pool.suites.iter().map(suite_name).collect(),
370        pool.groups.iter().map(group_name).collect(),
371    ))
372}
373
374/// The provider, versions and FIPS requirement `policy` builds its configurations with.
375pub(crate) fn select(policy: &Policy) -> Result<Selection, PeerError> {
376    if policy.tls_versions.is_empty() {
377        return Err(PeerError::Policy("tls_versions is empty".to_owned()));
378    }
379    if policy.cipher_profiles.is_empty() {
380        return Err(PeerError::Policy("cipher_profiles is empty".to_owned()));
381    }
382    let validated = policy
383        .cipher_profiles
384        .contains(&CipherProfile::Fips1403Validated);
385    let pool = Pool::of(policy, validated)?;
386    if pool.backend == Crypto::Ring && policy.cipher_profiles.contains(&CipherProfile::Cnsa2) {
387        return Err(PeerError::Policy(
388            "cnsa-2.0 needs crypto = aws-lc: ring has no ML-KEM or ML-DSA".to_owned(),
389        ));
390    }
391    if let Some(wanted) = &policy.cipher_suites {
392        let names: Vec<String> = pool.suites.iter().map(suite_name).collect();
393        if let Some(position) = wanted.iter().position(|name| !names.contains(name)) {
394            return Err(PeerError::Policy(format!(
395                "cipher_suites[{position}] is not a supported cipher suite; supported: {}",
396                known(pool.suites, suite_name)
397            )));
398        }
399    }
400    if let Some(wanted) = &policy.kx_groups {
401        let names: Vec<String> = pool.groups.iter().map(group_name).collect();
402        if let Some(position) = wanted.iter().position(|name| !names.contains(name)) {
403            return Err(PeerError::Policy(format!(
404                "kx_groups[{position}] is not a supported key-exchange group; supported: {}",
405                known(pool.groups, group_name)
406            )));
407        }
408    }
409    let specs: Vec<&Spec> = policy
410        .cipher_profiles
411        .iter()
412        .map(|profile| profile.spec())
413        .collect();
414
415    let mut suites: Vec<SupportedCipherSuite> = Vec::new();
416    for id in specs
417        .iter()
418        .flat_map(|spec| spec.tls13.iter().chain(spec.tls12))
419    {
420        let Some(suite) = pool.suites.iter().find(|suite| suite.suite() == *id) else {
421            continue;
422        };
423        let allowed = policy.tls_versions.contains(&version_of(suite))
424            && (!validated || suite.fips())
425            && policy
426                .cipher_suites
427                .as_ref()
428                .is_none_or(|wanted| wanted.contains(&suite_name(suite)));
429        if allowed && !suites.iter().any(|had| had.suite() == *id) {
430            suites.push(*suite);
431        }
432    }
433    let mut groups: Vec<&'static dyn SupportedKxGroup> = Vec::new();
434    for name in specs.iter().flat_map(|spec| spec.groups) {
435        let Some(group) = pool.groups.iter().find(|group| group.name() == *name) else {
436            continue;
437        };
438        let allowed = (!validated || group.fips())
439            && policy
440                .kx_groups
441                .as_ref()
442                .is_none_or(|wanted| wanted.contains(&group_name(group)));
443        if allowed && !groups.iter().any(|had| had.name() == *name) {
444            groups.push(*group);
445        }
446    }
447    // A version the allowed profiles give no suite is dropped.
448    let versions: Vec<&'static SupportedProtocolVersion> = policy
449        .tls_versions
450        .iter()
451        .filter(|version| suites.iter().any(|suite| version_of(suite) == **version))
452        .map(|version| match version {
453            TlsVersion::V1_3 => &rustls::version::TLS13,
454            TlsVersion::V1_2 => &rustls::version::TLS12,
455        })
456        .collect();
457    if versions.is_empty() {
458        return Err(PeerError::Policy(
459            "no cipher suite is left for any allowed TLS version".to_owned(),
460        ));
461    }
462    // rustls verifies a raw public key's signature in TLS 1.3 only.
463    let versions = if policy.certificate == CertificateType::RawPublicKey {
464        let versions: Vec<_> = versions
465            .into_iter()
466            .filter(|version| version.version == rustls::ProtocolVersion::TLSv1_3)
467            .collect();
468        if versions.is_empty() {
469            return Err(PeerError::Policy(
470                "certificate = raw_public_key needs TLS 1.3: tls_versions must list it and the \
471                 profiles must give it a suite"
472                    .to_owned(),
473            ));
474        }
475        versions
476    } else {
477        versions
478    };
479    if groups.is_empty() {
480        return Err(PeerError::Policy(
481            "no key-exchange group is allowed".to_owned(),
482        ));
483    }
484    let signatures = specs
485        .iter()
486        .map(|spec| spec.signatures)
487        .max()
488        .unwrap_or(Signatures::None);
489    let ml_dsa_87 = specs.iter().any(|spec| spec.ml_dsa_87);
490    let algorithms = tables::table(
491        pool.backend,
492        signatures,
493        ml_dsa_87,
494        pool.provider.signature_verification_algorithms,
495    )?;
496    Ok(Selection {
497        provider: Arc::new(CryptoProvider {
498            cipher_suites: suites,
499            kx_groups: groups,
500            signature_verification_algorithms: algorithms,
501            ..pool.provider
502        }),
503        versions,
504        validated,
505    })
506}
507
508/// [`PeerError::Policy`] unless a configuration that must be FIPS is (`fips` is rustls's
509/// `ClientConfig::fips()` or `ServerConfig::fips()`).
510pub(crate) fn require_fips(selection: &Selection, fips: bool) -> Result<(), PeerError> {
511    if selection.validated && !fips {
512        return Err(PeerError::Policy(
513            "fips-140-3-validated: rustls does not report this configuration FIPS (an \
514             unapproved algorithm, or require_ems is off)"
515                .to_owned(),
516        ));
517    }
518    Ok(())
519}