Skip to main content

crypto_profile/
profile.rs

1//! Named profiles: algorithm sets a backend resolves into a TLS policy and the key algorithms it
2//! admits. A profile is an algorithm set, not a validation claim; whether the running module is
3//! validated for it is a separate check.
4use crate::algorithm::{
5    Algorithm, CipherSuite as C, KxGroup as K, SignatureAlgorithm as S, TlsSignatureScheme as T,
6    TlsVersion as V,
7};
8use crate::capability::{Module, capability};
9use crate::error::{CryptoError, Family};
10use std::fmt;
11use std::str::FromStr;
12
13/// A named profile. Each one that is named for a regime follows that regime's published text, in
14/// the edition [`Profile::governing_text`] names, and changes only when a new edition is published.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum Profile {
17    /// Every algorithm in the inventory, post-quantum key exchange first. Not a government profile.
18    Unrestricted,
19    /// The crate's recommendation. Not a government profile; see `docs/profiles.md`.
20    Preferred,
21    /// The CNSA 2.0 algorithm set of CNSSP 15 (December 2024), Annex B, on TLS 1.3.
22    Cnsa2,
23    /// The CNSA 1.0 algorithm set of CNSSP 15 (20 October 2016), Annex B, in RFC 9151's TLS
24    /// profile. A transition profile for CNSA 1.0 counterparts. Not every RFC 9151 requirement is
25    /// met: `docs/profiles.md` names the algorithm gaps (the `cnsa1` entry in section 3, sections 4
26    /// and 5), and the RFC 8603 certificate profile that §5.4 requires is not implemented.
27    Cnsa1,
28    /// BSI TR-02102-2 and TR-02102-1, version 2026-01.
29    Bsi,
30    /// What a FIPS 140-3 boundary approves under the published texts.
31    Fips1403,
32    /// What a FIPS 140-2 boundary approves under the published texts.
33    Fips1402,
34}
35
36/// The text a profile follows.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum GoverningText {
39    /// The crate's own recommendation, following no published text.
40    CrateRecommendation,
41    /// Published documents, each with its edition.
42    Published {
43        /// The documents, each naming its edition.
44        documents: &'static [&'static str],
45    },
46}
47
48impl Profile {
49    /// Every profile.
50    pub const ALL: [Profile; 7] = [
51        Profile::Unrestricted,
52        Profile::Preferred,
53        Profile::Cnsa2,
54        Profile::Cnsa1,
55        Profile::Bsi,
56        Profile::Fips1403,
57        Profile::Fips1402,
58    ];
59
60    /// The position of `self` in [`Self::ALL`].
61    #[cfg(test)]
62    pub(crate) const fn ordinal(self) -> usize {
63        match self {
64            Profile::Unrestricted => 0,
65            Profile::Preferred => 1,
66            Profile::Cnsa2 => 2,
67            Profile::Cnsa1 => 3,
68            Profile::Bsi => 4,
69            Profile::Fips1403 => 5,
70            Profile::Fips1402 => 6,
71        }
72    }
73
74    /// The profile's stable configuration name.
75    pub const fn as_str(self) -> &'static str {
76        match self {
77            Profile::Unrestricted => "unrestricted",
78            Profile::Preferred => "preferred",
79            Profile::Cnsa2 => "cnsa2",
80            Profile::Cnsa1 => "cnsa1",
81            Profile::Bsi => "bsi",
82            Profile::Fips1403 => "fips1403",
83            Profile::Fips1402 => "fips1402",
84        }
85    }
86
87    /// The texts the profile follows, with each document's edition. The profile constant's doc
88    /// comment also cites the standards and implementation guidance these texts rely on.
89    pub const fn governing_text(self) -> GoverningText {
90        match self {
91            Profile::Unrestricted | Profile::Preferred => GoverningText::CrateRecommendation,
92            Profile::Cnsa2 => GoverningText::Published {
93                documents: &["CNSSP 15 (December 2024), Annex B, pp. B-1 to B-2"],
94            },
95            Profile::Cnsa1 => GoverningText::Published {
96                documents: &[
97                    "CNSSP 15 (20 October 2016), Annex B, p. B-1",
98                    "RFC 9151 (April 2022)",
99                ],
100            },
101            Profile::Bsi => GoverningText::Published {
102                documents: &[
103                    "BSI TR-02102-2, version 2026-01",
104                    "BSI TR-02102-1, version 2026-01",
105                ],
106            },
107            Profile::Fips1403 => GoverningText::Published {
108                documents: &[
109                    "NIST SP 800-140C r2 and SP 800-140D r2, with the CMVP lists (August 2026)",
110                    "FIPS 140-3 Implementation Guidance (August 2026): IG C.K, D.Q, D.S",
111                    "NIST SP 800-52r2",
112                    "NIST SP 800-131A r2",
113                ],
114            },
115            Profile::Fips1402 => GoverningText::Published {
116                documents: &[
117                    "FIPS 140-2 Annex A and Annex D (2021)",
118                    "FIPS 186-4",
119                    "NIST SP 800-131A r2",
120                    "NIST SP 800-52r2",
121                ],
122            },
123        }
124    }
125}
126
127impl fmt::Display for Profile {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str(self.as_str())
130    }
131}
132
133/// A name that is not one of the crate's profiles. Names are matched exactly: no trimming and no
134/// case folding.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct ParseProfileError(pub String);
137
138impl fmt::Display for ParseProfileError {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        write!(f, "unknown profile {:?}", self.0)
141    }
142}
143
144impl std::error::Error for ParseProfileError {}
145
146impl FromStr for Profile {
147    type Err = ParseProfileError;
148    fn from_str(s: &str) -> Result<Self, Self::Err> {
149        Profile::ALL
150            .into_iter()
151            .find(|p| p.as_str() == s)
152            .ok_or_else(|| ParseProfileError(s.to_string()))
153    }
154}
155
156/// Narrowing applied on top of any profile. The default narrows nothing.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
158pub struct Options {
159    /// Keep only post-quantum key exchange (pure ML-KEM and hybrid groups), and so remove TLS 1.2,
160    /// which has none. Signatures are not narrowed.
161    pub pq_key_exchange_required: bool,
162    /// Require peer leaf keys and certification paths to match the profile. Off by default.
163    pub peer_certificates_match_profile: bool,
164}
165
166impl fmt::Display for Options {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        f.write_str(
169            match (
170                self.pq_key_exchange_required,
171                self.peer_certificates_match_profile,
172            ) {
173                (false, false) => "no options",
174                (true, false) => "post-quantum key exchange required",
175                (false, true) => "peer certificates match profile",
176                (true, true) => {
177                    "post-quantum key exchange required, peer certificates match profile"
178                }
179            },
180        )
181    }
182}
183
184/// A profile's contents, each list in preference order.
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub struct ProfileSpec {
187    /// Protocol versions.
188    pub versions: &'static [V],
189    /// Cipher suites.
190    pub cipher_suites: &'static [C],
191    /// Key-exchange groups.
192    pub kx_groups: &'static [K],
193    /// Handshake signature schemes accepted from the peer.
194    pub signature_schemes: &'static [T],
195    /// Key algorithms the profile admits for keys generated or used under it.
196    pub key_algorithms: &'static [S],
197}
198
199impl Profile {
200    /// The profile's contents. Each entry's source is cited on the constant it comes from.
201    pub const fn spec(self) -> &'static ProfileSpec {
202        match self {
203            Profile::Unrestricted => &UNRESTRICTED,
204            Profile::Preferred => &PREFERRED,
205            Profile::Cnsa2 => &CNSA2,
206            Profile::Cnsa1 => &CNSA1,
207            Profile::Bsi => &BSI,
208            Profile::Fips1403 => &FIPS1403,
209            Profile::Fips1402 => &FIPS1402,
210        }
211    }
212}
213
214/// `unrestricted`: the crate's own set, following no published text. Not a government profile.
215///
216/// - Versions: TLS 1.3, TLS 1.2. Suites: all nine. Groups: all seven. Schemes: all eleven. Keys:
217///   all nine (`crypto_profile::algorithm`, each family's `ALL`).
218pub const UNRESTRICTED: ProfileSpec = ProfileSpec {
219    versions: &[V::Tls13, V::Tls12],
220    cipher_suites: &[
221        C::Tls13Aes256GcmSha384,
222        C::Tls13Aes128GcmSha256,
223        C::Tls13Chacha20Poly1305Sha256,
224        C::Tls12EcdheEcdsaAes256GcmSha384,
225        C::Tls12EcdheRsaAes256GcmSha384,
226        C::Tls12EcdheEcdsaAes128GcmSha256,
227        C::Tls12EcdheRsaAes128GcmSha256,
228        C::Tls12EcdheEcdsaChacha20Poly1305Sha256,
229        C::Tls12EcdheRsaChacha20Poly1305Sha256,
230    ],
231    kx_groups: &[
232        K::MlKem1024,
233        K::Secp384r1MlKem1024,
234        K::X25519MlKem768,
235        K::Secp256r1MlKem768,
236        K::Secp384r1,
237        K::Secp256r1,
238        K::X25519,
239    ],
240    signature_schemes: &[
241        T::MlDsa87,
242        T::EcdsaNistp384Sha384,
243        T::EcdsaNistp256Sha256,
244        T::EcdsaNistp521Sha512,
245        T::Ed25519,
246        T::RsaPssSha384,
247        T::RsaPssSha512,
248        T::RsaPssSha256,
249        T::RsaPkcs1Sha384,
250        T::RsaPkcs1Sha512,
251        T::RsaPkcs1Sha256,
252    ],
253    key_algorithms: &[
254        S::MlDsa87,
255        S::EcdsaP384Sha384,
256        S::EcdsaP256Sha256,
257        S::EcdsaP521Sha512,
258        S::EcdsaP521Sha384,
259        S::Ed25519,
260        S::Rsa3072Sha384,
261        S::Rsa4096Sha384,
262        S::Rsa2048Sha384,
263    ],
264};
265
266/// `preferred`: the crate's recommendation. Not a government profile; see `docs/profiles.md`.
267///
268/// "ISM" is ASD, *Information security manual, Guidelines for cryptography*, September 2026;
269/// SECRET-level controls ISM-1761 and ISM-1763 (p. 8), ISM-1765 (p. 10), ISM-1769 (p. 11).
270/// - TLS 1.3 only: ISM-1139, p. 19.
271/// - TLS_AES_256_GCM_SHA384, TLS_AES_128_GCM_SHA256: ISM-1369, p. 20; ISM-1769, p. 11.
272/// - ML-KEM-1024: ISM-1995, p. 10.
273/// - SecP384r1MLKEM1024, X25519MLKEM768, SecP256r1MLKEM768: ISM p. 12; ISM-1996, p. 13; FIPS 140-3 IG D.S
274///   Scenario 2 and Additional Comment 8a (August 2026, pp. 223-226), which names all three.
275/// - secp384r1, secp256r1: ISM-0474 and ISM-1761, p. 8; ISM-1446, p. 7.
276/// - X25519 on its own excluded: FIPS 140-3 IG C.K Resolution 5 (p. 160).
277/// - ChaCha20-Poly1305 excluded: ISM p. 6; SP 800-140Cr2 §6.1.
278/// - Schemes ML-DSA-87 (ISM-1991, p. 9), ECDSA P-384, P-256, P-521 (ISM-1763, p. 8), RSA-PSS
279///   with SHA-2 (ISM-1765, p. 10; ISM-1374, p. 20).
280/// - Ed25519 excluded: ISM pp. 5-6.
281/// - RSA PKCS#1 v1.5 schemes excluded: RFC 8446 §4.2.3.
282/// - Keys ML-DSA-87 (ISM-1991, p. 9), ECDSA P-384, P-256, P-521 (ISM-1763, p. 8), RSA 3072 and
283///   4096 (ISM-1765, p. 10); RSA 2048 excluded: ISM-1765, p. 10.
284/// - ECDSA P-521 with SHA-384: ISM-1763, p. 8; SHA-2 output of at least 256 bits, ISM-1767,
285///   p. 11.
286pub const PREFERRED: ProfileSpec = ProfileSpec {
287    versions: &[V::Tls13],
288    cipher_suites: &[C::Tls13Aes256GcmSha384, C::Tls13Aes128GcmSha256],
289    kx_groups: &[
290        K::MlKem1024,
291        K::Secp384r1MlKem1024,
292        K::X25519MlKem768,
293        K::Secp256r1MlKem768,
294        K::Secp384r1,
295        K::Secp256r1,
296    ],
297    signature_schemes: &[
298        T::MlDsa87,
299        T::EcdsaNistp384Sha384,
300        T::EcdsaNistp256Sha256,
301        T::EcdsaNistp521Sha512,
302        T::RsaPssSha384,
303        T::RsaPssSha512,
304        T::RsaPssSha256,
305    ],
306    key_algorithms: &[
307        S::MlDsa87,
308        S::EcdsaP384Sha384,
309        S::EcdsaP256Sha256,
310        S::EcdsaP521Sha512,
311        S::EcdsaP521Sha384,
312        S::Rsa3072Sha384,
313        S::Rsa4096Sha384,
314    ],
315};
316
317/// `cnsa2`: the CNSA 2.0 algorithm set of CNSSP 15 (December 2024), Annex B, pp. B-1 to B-2, on
318/// TLS 1.3. No CNSA 2.0 TLS profile is published: CNSSP 15 ¶8a, footnote 1 (p. 5).
319/// - ML-KEM-1024: Annex B ¶1 table, p. B-1.
320/// - ML-DSA-87 scheme and key: Annex B ¶1 table, p. B-1.
321/// - TLS_AES_256_GCM_SHA384: Annex B ¶1 table, p. B-1.
322/// - TLS 1.3 only: ML-KEM-1024 is the set's only key establishment (Annex B ¶1 table, p. B-1);
323///   TLS 1.2 key exchange is ECDHE or FFDHE (RFC 8422, RFC 7919).
324pub const CNSA2: ProfileSpec = ProfileSpec {
325    versions: &[V::Tls13],
326    cipher_suites: &[C::Tls13Aes256GcmSha384],
327    kx_groups: &[K::MlKem1024],
328    signature_schemes: &[T::MlDsa87],
329    key_algorithms: &[S::MlDsa87],
330};
331
332/// `cnsa1`: the CNSA 1.0 algorithm set of CNSSP 15 (20 October 2016), Annex B (p. B-1), in the
333/// TLS 1.2 and 1.3 profile of RFC 9151 (April 2022). Transition dates: CNSSP 15 (December 2024)
334/// ¶18 (pp. 7-8).
335/// - AES-256, ECDH and ECDSA on P-384, SHA-384, RSA of at least 3072 bits: CNSSP 15 (2016)
336///   Annex B ¶1 table, p. B-1.
337/// - TLS 1.3 and 1.2: RFC 9151 §5. The § references below are RFC 9151's.
338/// - TLS_AES_256_GCM_SHA384: §7.
339/// - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: §6.
340/// - secp384r1: §5.1, §7.
341/// - ecdsa_secp384r1_sha384: §6.2, §7.1. rsa_pss_rsae_sha384: §6.2, §7.1. rsa_pkcs1_sha384:
342///   §6.2; TLS 1.2 only, §7.1.
343/// - Keys ECDSA P-384 with SHA-384 (§5.1); RSA 3072 and 4096 (§5.2).
344/// - Not implemented by the stack: TLS_RSA_WITH_AES_256_GCM_SHA384 and
345///   TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (§6), ffdhe3072 and ffdhe4096 (§5.3, §7).
346pub const CNSA1: ProfileSpec = ProfileSpec {
347    versions: &[V::Tls13, V::Tls12],
348    cipher_suites: &[
349        C::Tls13Aes256GcmSha384,
350        C::Tls12EcdheEcdsaAes256GcmSha384,
351        C::Tls12EcdheRsaAes256GcmSha384,
352    ],
353    kx_groups: &[K::Secp384r1],
354    signature_schemes: &[T::EcdsaNistp384Sha384, T::RsaPssSha384, T::RsaPkcs1Sha384],
355    key_algorithms: &[S::EcdsaP384Sha384, S::Rsa3072Sha384, S::Rsa4096Sha384],
356};
357
358/// `bsi`: BSI TR-02102-2 (TLS) and TR-02102-1, version 2026-01.
359/// - TLS 1.3 and TLS 1.2: TR-02102-2 §3.2, Table 2.
360/// - TLS_AES_256_GCM_SHA384, TLS_AES_128_GCM_SHA256: TR-02102-2 §3.4.4, Table 13.
361/// - ECDHE-ECDSA and ECDHE-RSA with AES-128-GCM and AES-256-GCM: TR-02102-2 §3.3.1.1, Table 3.
362/// - secp384r1, secp256r1: TR-02102-2 Table 10 (TLS 1.3) and Table 6 (TLS 1.2).
363/// - ecdsa_secp384r1_sha384, ecdsa_secp256r1_sha256, ecdsa_secp521r1_sha512 and rsa_pss_rsae
364///   with SHA-384, 512, 256: TR-02102-2 §3.4.3, Table 11; for TLS 1.2, the Table 7 note.
365/// - rsa_pkcs1_* excluded: TR-02102-2 Table 7 and Table 12 notes.
366/// - Keys ECDSA P-384/SHA-384, P-256/SHA-256, P-521/SHA-512: TR-02102-2 Table 12 and Table 14.
367/// - RSA keys excluded: TR-02102-2 Table 12.
368/// - ML-DSA excluded: TR-02102-1 §5.3.4.
369/// - Hybrid groups excluded: TR-02102-2 Table 10 note.
370pub const BSI: ProfileSpec = ProfileSpec {
371    versions: &[V::Tls13, V::Tls12],
372    cipher_suites: &[
373        C::Tls13Aes256GcmSha384,
374        C::Tls13Aes128GcmSha256,
375        C::Tls12EcdheEcdsaAes256GcmSha384,
376        C::Tls12EcdheRsaAes256GcmSha384,
377        C::Tls12EcdheEcdsaAes128GcmSha256,
378        C::Tls12EcdheRsaAes128GcmSha256,
379    ],
380    kx_groups: &[K::Secp384r1, K::Secp256r1],
381    signature_schemes: &[
382        T::EcdsaNistp384Sha384,
383        T::EcdsaNistp256Sha256,
384        T::EcdsaNistp521Sha512,
385        T::RsaPssSha384,
386        T::RsaPssSha512,
387        T::RsaPssSha256,
388    ],
389    key_algorithms: &[S::EcdsaP384Sha384, S::EcdsaP256Sha256, S::EcdsaP521Sha512],
390};
391
392/// `fips1403`: NIST SP 800-140C r2 and SP 800-140D r2 with the CMVP lists (updated August 21,
393/// 2026), the FIPS 140-3 Implementation Guidance (August 19, 2026), SP 800-52r2 and SP 800-131A
394/// r2. An algorithm set, not a validation claim.
395/// - TLS 1.3 and 1.2: SP 800-52r2 §3.1 (p. 8), §4.1 (p. 33). TLS 1.2 extended master secret
396///   (RFC 7627): IG D.Q (pp. 220-221).
397/// - TLS_AES_256_GCM_SHA384, TLS_AES_128_GCM_SHA256: SP 800-52r2 §3.3.1.2 (p. 19); CMVP
398///   SP 800-140C list §6.2.2.1.
399/// - ECDHE-ECDSA and ECDHE-RSA with AES-128-GCM and AES-256-GCM: SP 800-52r2 §3.3.1.1.1-2
400///   (pp. 16-17).
401/// - ChaCha20-Poly1305 excluded: SP 800-140Cr2 §6.1; SP 800-52r2 §3.3.1.2.
402/// - ML-KEM-1024: CMVP SP 800-140D list §6.2.10; IG D.S Scenario 1 (p. 223).
403/// - SecP384r1MLKEM1024, X25519MLKEM768, SecP256r1MLKEM768: IG D.S Scenario 2 and Additional
404///   Comment 8a (pp. 223-226), the three IANA parameter sets it names.
405/// - secp384r1, secp256r1: SP 800-56A r3 Appendix D, Table 24 (p. 132); SP 800-52r2 §3.4.2.2
406///   (pp. 24-25).
407/// - X25519 on its own excluded: IG C.K Resolution 5 (p. 160).
408/// - ECDSA P-256, P-384, P-521 schemes and keys: SP 800-140C list §6.2.3.1; SP 800-186 Table 2
409///   (p. 7); SP 800-131A r2 Table 2 (p. 9).
410/// - ECDSA P-521 with SHA-384: FIPS 186-5 §6.4 (p. 23).
411/// - Ed25519 scheme and key: SP 800-140C list §6.2.3.1; IG C.A (p. 136); IG C.K Additional
412///   Comment 8 (p. 161).
413/// - RSA-PSS and RSA PKCS#1 v1.5 with SHA-256, 384, 512: FIPS 186-5 §5.4; IG C.F (pp. 142-143);
414///   PKCS#1 v1.5 on TLS 1.2 only, RFC 8446 §4.2.3.
415/// - RSA 2048, 3072, 4096 keys: FIPS 186-5 §5.1; SP 800-131A r2 Table 2.
416/// - ML-DSA-87 scheme and key: SP 800-140C list §6.2.3.1 (FIPS 204).
417pub const FIPS1403: ProfileSpec = ProfileSpec {
418    versions: &[V::Tls13, V::Tls12],
419    cipher_suites: &[
420        C::Tls13Aes256GcmSha384,
421        C::Tls13Aes128GcmSha256,
422        C::Tls12EcdheEcdsaAes256GcmSha384,
423        C::Tls12EcdheRsaAes256GcmSha384,
424        C::Tls12EcdheEcdsaAes128GcmSha256,
425        C::Tls12EcdheRsaAes128GcmSha256,
426    ],
427    kx_groups: &[
428        K::MlKem1024,
429        K::Secp384r1MlKem1024,
430        K::X25519MlKem768,
431        K::Secp256r1MlKem768,
432        K::Secp384r1,
433        K::Secp256r1,
434    ],
435    signature_schemes: &[
436        T::MlDsa87,
437        T::EcdsaNistp384Sha384,
438        T::EcdsaNistp256Sha256,
439        T::EcdsaNistp521Sha512,
440        T::Ed25519,
441        T::RsaPssSha384,
442        T::RsaPssSha512,
443        T::RsaPssSha256,
444        T::RsaPkcs1Sha384,
445        T::RsaPkcs1Sha512,
446        T::RsaPkcs1Sha256,
447    ],
448    key_algorithms: &[
449        S::MlDsa87,
450        S::EcdsaP384Sha384,
451        S::EcdsaP256Sha256,
452        S::EcdsaP521Sha512,
453        S::EcdsaP521Sha384,
454        S::Ed25519,
455        S::Rsa3072Sha384,
456        S::Rsa4096Sha384,
457        S::Rsa2048Sha384,
458    ],
459};
460
461/// `fips1402`: FIPS 140-2 Annex A and Annex D (2021-10-12 editions), FIPS 186-4, SP 800-131A r2
462/// and SP 800-52r2. An algorithm set, not a validation claim.
463/// - TLS 1.3 and 1.2, and the AES-GCM suites: SP 800-52r2 §3.1, §3.3.1.1.1-2, §3.3.1.2; TLS 1.3
464///   key schedule, Annex D item 11 (RFC 8446 §7.1).
465/// - ChaCha20-Poly1305 excluded: Annex A.
466/// - secp384r1, secp256r1: Annex D item 3 (SP 800-56A r3), Table 24.
467/// - ML-KEM and the hybrids excluded: Annex A; Annex D items 12-13.
468/// - X25519 excluded: SP 800-56A r3 Table 24.
469/// - ECDSA P-256, P-384, P-521 schemes; RSA-PSS and PKCS#1 v1.5 with SHA-256, 384, 512: FIPS 186-4
470///   (Annex A, p. 2), §5.4-5.5, Appendix D.1.2; SP 800-131A r2 Table 2 (p. 9).
471/// - Ed25519 and ML-DSA excluded: Annex A.
472/// - ECDSA keys P-384/SHA-384, P-256/SHA-256, P-521/SHA-512, P-521/SHA-384: FIPS 186-4 §6.4
473///   (pp. 29-30).
474/// - RSA 3072 and 2048 keys: FIPS 186-4 §5.1; RSA 4096: FIPS 140-2 IG A.14 (p. 221).
475pub const FIPS1402: ProfileSpec = ProfileSpec {
476    versions: &[V::Tls13, V::Tls12],
477    cipher_suites: &[
478        C::Tls13Aes256GcmSha384,
479        C::Tls13Aes128GcmSha256,
480        C::Tls12EcdheEcdsaAes256GcmSha384,
481        C::Tls12EcdheRsaAes256GcmSha384,
482        C::Tls12EcdheEcdsaAes128GcmSha256,
483        C::Tls12EcdheRsaAes128GcmSha256,
484    ],
485    kx_groups: &[K::Secp384r1, K::Secp256r1],
486    signature_schemes: &[
487        T::EcdsaNistp384Sha384,
488        T::EcdsaNistp256Sha256,
489        T::EcdsaNistp521Sha512,
490        T::RsaPssSha384,
491        T::RsaPssSha512,
492        T::RsaPssSha256,
493        T::RsaPkcs1Sha384,
494        T::RsaPkcs1Sha512,
495        T::RsaPkcs1Sha256,
496    ],
497    key_algorithms: &[
498        S::EcdsaP384Sha384,
499        S::EcdsaP256Sha256,
500        S::EcdsaP521Sha512,
501        S::EcdsaP521Sha384,
502        S::Rsa3072Sha384,
503        S::Rsa4096Sha384,
504        S::Rsa2048Sha384,
505    ],
506};
507
508/// A profile narrowed by its options, every entry implemented by the module's backend, in the
509/// profile's preference order.
510#[derive(Debug, Clone, PartialEq, Eq)]
511pub struct Selection {
512    /// Protocol versions.
513    pub versions: Vec<V>,
514    /// Cipher suites, each of a version in `versions`.
515    pub cipher_suites: Vec<C>,
516    /// Key-exchange groups.
517    pub kx_groups: Vec<K>,
518    /// Handshake signature schemes.
519    pub signature_schemes: Vec<T>,
520    /// Key algorithms.
521    pub key_algorithms: Vec<S>,
522    /// Entries unavailable on the module line after Options, in family and preference order.
523    pub excluded: Vec<Algorithm>,
524}
525
526const fn is_tls12_only(t: T) -> bool {
527    match t {
528        T::RsaPkcs1Sha256 | T::RsaPkcs1Sha384 | T::RsaPkcs1Sha512 => true,
529        T::EcdsaNistp256Sha256
530        | T::EcdsaNistp384Sha384
531        | T::EcdsaNistp521Sha512
532        | T::Ed25519
533        | T::RsaPssSha256
534        | T::RsaPssSha384
535        | T::RsaPssSha512
536        | T::MlDsa87 => false,
537    }
538}
539
540fn keep<X: Copy>(items: &[X], mut wanted: impl FnMut(X) -> bool) -> Vec<X> {
541    items.iter().copied().filter(|x| wanted(*x)).collect()
542}
543
544/// The backend-independent half of a backend's `resolve`: `profile`'s lists, narrowed by
545/// `options`; `pq_key_exchange_required` also removes TLS 1.2, its suites and the RSA PKCS#1 v1.5
546/// handshake schemes. Records entries the module line lacks in [`Selection::excluded`], then
547/// refuses a family left empty with [`CryptoError::EmptyProfile`]. Both use versions, suites,
548/// groups, schemes and keys order, preserving preference order. Approval is a separate check.
549pub fn select(
550    profile: Profile,
551    options: Options,
552    module: Module,
553) -> Result<Selection, CryptoError> {
554    select_spec(profile, profile.spec(), options, module)
555}
556
557fn select_spec(
558    profile: Profile,
559    spec: &ProfileSpec,
560    options: Options,
561    module: Module,
562) -> Result<Selection, CryptoError> {
563    let pq = options.pq_key_exchange_required;
564    let versions = keep(spec.versions, |v| !(pq && v == V::Tls12));
565    let cipher_suites = keep(spec.cipher_suites, |c| versions.contains(&c.version()));
566    let kx_groups = keep(spec.kx_groups, |k| !pq || k.is_post_quantum());
567    let signature_schemes = keep(spec.signature_schemes, |t| !(pq && is_tls12_only(t)));
568    let key_algorithms = spec.key_algorithms.to_vec();
569    let mut excluded = Vec::new();
570    let mut available = |a| {
571        let on = capability(module, a).available;
572        if !on {
573            excluded.push(a);
574        }
575        on
576    };
577    let versions = keep(&versions, |v| available(Algorithm::Protocol(v)));
578    let cipher_suites = keep(&cipher_suites, |c| available(Algorithm::Cipher(c)));
579    let kx_groups = keep(&kx_groups, |k| available(Algorithm::Kx(k)));
580    let signature_schemes = keep(&signature_schemes, |t| available(Algorithm::Scheme(t)));
581    let key_algorithms = keep(&key_algorithms, |s| available(Algorithm::Signature(s)));
582    for (empty, category) in [
583        (versions.is_empty(), Family::Version),
584        (cipher_suites.is_empty(), Family::CipherSuite),
585        (kx_groups.is_empty(), Family::KxGroup),
586        (signature_schemes.is_empty(), Family::SignatureScheme),
587        (key_algorithms.is_empty(), Family::KeyAlgorithm),
588    ] {
589        if empty {
590            return Err(CryptoError::EmptyProfile {
591                profile,
592                options,
593                category,
594            });
595        }
596    }
597    Ok(Selection {
598        versions,
599        cipher_suites,
600        kx_groups,
601        signature_schemes,
602        key_algorithms,
603        excluded,
604    })
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610    use crate::algorithm::*;
611    use crate::capability::{Linkage, Module, ModuleLine};
612    use crate::error::{CryptoError, Family};
613
614    #[test]
615    fn every_profile_lists_its_schemes_in_the_canonical_order() {
616        assert_eq!(
617            Profile::Unrestricted.spec().signature_schemes.len(),
618            TlsSignatureScheme::ALL.len()
619        );
620        for p in Profile::ALL {
621            let s = p.spec().signature_schemes;
622            assert!(
623                s.windows(2).all(|w| w[0].preference() < w[1].preference()),
624                "{p}"
625            );
626        }
627    }
628
629    const M3S: Module = Module {
630        line: ModuleLine::AwsLcFips3,
631        linkage: Linkage::Static,
632    };
633    const M4S: Module = Module {
634        line: ModuleLine::AwsLcFips4,
635        linkage: Linkage::Static,
636    };
637    const PQ: Options = Options {
638        peer_certificates_match_profile: false,
639        pq_key_exchange_required: true,
640    };
641    const PKCS1: [TlsSignatureScheme; 3] = [
642        TlsSignatureScheme::RsaPkcs1Sha256,
643        TlsSignatureScheme::RsaPkcs1Sha384,
644        TlsSignatureScheme::RsaPkcs1Sha512,
645    ];
646
647    fn no_duplicates<X: PartialEq + std::fmt::Debug>(xs: &[X]) {
648        for (i, x) in xs.iter().enumerate() {
649            assert!(!xs[i + 1..].contains(x), "{x:?} twice");
650        }
651    }
652
653    #[test]
654    fn every_spec_is_well_formed() {
655        for p in Profile::ALL {
656            let s = p.spec();
657            no_duplicates(s.versions);
658            no_duplicates(s.cipher_suites);
659            no_duplicates(s.kx_groups);
660            no_duplicates(s.signature_schemes);
661            no_duplicates(s.key_algorithms);
662            assert!(!s.versions.is_empty() && !s.kx_groups.is_empty(), "{p}");
663            assert!(
664                !s.signature_schemes.is_empty() && !s.key_algorithms.is_empty(),
665                "{p}"
666            );
667            assert!(
668                s.cipher_suites
669                    .iter()
670                    .all(|c| s.versions.contains(&c.version())),
671                "{p}"
672            );
673            let has_pkcs1 = s.signature_schemes.iter().any(|t| PKCS1.contains(t));
674            assert!(!has_pkcs1 || s.versions.contains(&TlsVersion::Tls12), "{p}");
675        }
676    }
677
678    #[test]
679    fn preferred_excludes_what_its_definition_names() {
680        let s = Profile::Preferred.spec();
681        assert_eq!(s.versions, &[TlsVersion::Tls13]);
682        assert!(!s.kx_groups.contains(&KxGroup::X25519));
683        assert!(
684            !s.cipher_suites
685                .contains(&CipherSuite::Tls13Chacha20Poly1305Sha256)
686        );
687        assert!(!s.signature_schemes.contains(&TlsSignatureScheme::Ed25519));
688        assert!(!s.key_algorithms.contains(&SignatureAlgorithm::Ed25519));
689    }
690
691    #[test]
692    fn bsi_admits_only_ecdsa_keys() {
693        assert_eq!(
694            Profile::Bsi.spec().key_algorithms,
695            &[
696                SignatureAlgorithm::EcdsaP384Sha384,
697                SignatureAlgorithm::EcdsaP256Sha256,
698                SignatureAlgorithm::EcdsaP521Sha512,
699            ]
700        );
701    }
702
703    #[test]
704    fn select_records_line_exclusions_after_options() {
705        for module in [
706            M3S,
707            Module {
708                linkage: Linkage::Dynamic,
709                ..M3S
710            },
711        ] {
712            for p in [Profile::Unrestricted, Profile::Preferred, Profile::Fips1403] {
713                for options in [Options::default(), PQ] {
714                    let s = select(p, options, module).unwrap();
715                    assert_eq!(
716                        s.excluded,
717                        vec![
718                            Algorithm::Scheme(T::MlDsa87),
719                            Algorithm::Signature(S::MlDsa87),
720                        ]
721                    );
722                    no_duplicates(&s.excluded);
723                    assert!(!s.signature_schemes.contains(&T::MlDsa87));
724                    assert!(!s.key_algorithms.contains(&S::MlDsa87));
725                }
726            }
727            for options in [Options::default(), PQ] {
728                assert_eq!(
729                    select(Profile::Cnsa2, options, module),
730                    Err(CryptoError::EmptyProfile {
731                        profile: Profile::Cnsa2,
732                        options,
733                        category: Family::SignatureScheme,
734                    })
735                );
736            }
737            for p in [Profile::Cnsa1, Profile::Bsi, Profile::Fips1402] {
738                assert!(
739                    select(p, Options::default(), module)
740                        .unwrap()
741                        .excluded
742                        .is_empty()
743                );
744            }
745        }
746    }
747
748    #[test]
749    fn select_checks_keys_and_options_precede_line_emptiness() {
750        const KEY_ONLY: ProfileSpec = ProfileSpec {
751            signature_schemes: &[T::EcdsaNistp384Sha384],
752            ..CNSA2
753        };
754        assert_eq!(
755            select_spec(Profile::Cnsa2, &KEY_ONLY, Options::default(), M3S),
756            Err(CryptoError::EmptyProfile {
757                profile: Profile::Cnsa2,
758                options: Options::default(),
759                category: Family::KeyAlgorithm,
760            })
761        );
762        const BSI_WITH_ML_DSA: ProfileSpec = ProfileSpec {
763            signature_schemes: &[T::MlDsa87],
764            ..BSI
765        };
766        for spec in [&BSI_WITH_ML_DSA, &BSI] {
767            assert_eq!(
768                select_spec(Profile::Bsi, spec, PQ, M3S),
769                Err(CryptoError::EmptyProfile {
770                    profile: Profile::Bsi,
771                    options: PQ,
772                    category: Family::KxGroup,
773                })
774            );
775        }
776    }
777
778    #[test]
779    fn select_refuses_each_empty_family_in_order() {
780        const EMPTY: ProfileSpec = ProfileSpec {
781            versions: &[],
782            cipher_suites: &[],
783            kx_groups: &[],
784            signature_schemes: &[],
785            key_algorithms: &[],
786        };
787        let empty = |category| {
788            Err(CryptoError::EmptyProfile {
789                profile: Profile::Bsi,
790                options: Options::default(),
791                category,
792            })
793        };
794        let cases: [(ProfileSpec, Family); 5] = [
795            (EMPTY, Family::Version),
796            (
797                ProfileSpec {
798                    versions: BSI.versions,
799                    ..EMPTY
800                },
801                Family::CipherSuite,
802            ),
803            (
804                ProfileSpec {
805                    kx_groups: &[],
806                    signature_schemes: &[],
807                    key_algorithms: &[],
808                    ..BSI
809                },
810                Family::KxGroup,
811            ),
812            (
813                ProfileSpec {
814                    signature_schemes: &[],
815                    key_algorithms: &[],
816                    ..BSI
817                },
818                Family::SignatureScheme,
819            ),
820            (
821                ProfileSpec {
822                    key_algorithms: &[],
823                    ..BSI
824                },
825                Family::KeyAlgorithm,
826            ),
827        ];
828        for (spec, category) in cases {
829            assert_eq!(
830                select_spec(Profile::Bsi, &spec, Options::default(), M4S),
831                empty(category),
832                "{category:?}"
833            );
834        }
835    }
836
837    #[test]
838    fn select_without_options_is_the_spec_on_a_module_that_has_everything() {
839        for p in Profile::ALL {
840            let s = select(p, Options::default(), M4S).unwrap();
841            let spec = p.spec();
842            assert!(s.excluded.is_empty());
843            assert_eq!(s.versions, spec.versions.to_vec(), "{p}");
844            assert_eq!(s.cipher_suites, spec.cipher_suites.to_vec(), "{p}");
845            assert_eq!(s.kx_groups, spec.kx_groups.to_vec(), "{p}");
846            assert_eq!(s.signature_schemes, spec.signature_schemes.to_vec(), "{p}");
847            assert_eq!(s.key_algorithms, spec.key_algorithms.to_vec(), "{p}");
848        }
849    }
850
851    #[test]
852    fn the_option_keeps_post_quantum_groups_tls13_and_no_pkcs1_schemes() {
853        for p in Profile::ALL {
854            let refused = match p {
855                Profile::Unrestricted | Profile::Preferred | Profile::Cnsa2 | Profile::Fips1403 => {
856                    false
857                }
858                Profile::Cnsa1 | Profile::Bsi | Profile::Fips1402 => true,
859            };
860            match select(p, PQ, M4S) {
861                Ok(s) => {
862                    assert!(!refused, "{p}");
863                    let spec = p.spec();
864                    assert_eq!(s.versions, vec![TlsVersion::Tls13], "{p}");
865                    let suites: Vec<_> = spec
866                        .cipher_suites
867                        .iter()
868                        .copied()
869                        .filter(|c| c.version() == TlsVersion::Tls13)
870                        .collect();
871                    assert_eq!(s.cipher_suites, suites, "{p}");
872                    let groups: Vec<_> = spec
873                        .kx_groups
874                        .iter()
875                        .copied()
876                        .filter(|k| k.is_post_quantum())
877                        .collect();
878                    assert_eq!(s.kx_groups, groups, "{p}");
879                    let schemes: Vec<_> = spec
880                        .signature_schemes
881                        .iter()
882                        .copied()
883                        .filter(|t| !PKCS1.contains(t))
884                        .collect();
885                    assert_eq!(s.signature_schemes, schemes, "{p}");
886                    assert_eq!(s.key_algorithms, spec.key_algorithms.to_vec(), "{p}");
887                }
888                Err(e) => {
889                    assert!(refused, "{p}");
890                    assert_eq!(
891                        e,
892                        CryptoError::EmptyProfile {
893                            profile: p,
894                            options: PQ,
895                            category: Family::KxGroup
896                        }
897                    );
898                }
899            }
900        }
901    }
902
903    #[test]
904    fn the_option_removes_every_pkcs1_scheme_from_unrestricted_and_fips1403() {
905        use TlsSignatureScheme as T;
906        let expected = vec![
907            T::MlDsa87,
908            T::EcdsaNistp384Sha384,
909            T::EcdsaNistp256Sha256,
910            T::EcdsaNistp521Sha512,
911            T::Ed25519,
912            T::RsaPssSha384,
913            T::RsaPssSha512,
914            T::RsaPssSha256,
915        ];
916        for p in [Profile::Unrestricted, Profile::Fips1403] {
917            assert_eq!(
918                select(p, PQ, M4S).unwrap().signature_schemes,
919                expected,
920                "{p}"
921            );
922            assert_eq!(
923                select(p, Options::default(), M4S)
924                    .unwrap()
925                    .signature_schemes
926                    .len(),
927                expected.len() + 3,
928                "{p}"
929            );
930        }
931    }
932
933    #[test]
934    fn profile_names_are_stable_and_exact() {
935        assert_eq!(
936            Profile::ALL.map(Profile::as_str),
937            [
938                "unrestricted",
939                "preferred",
940                "cnsa2",
941                "cnsa1",
942                "bsi",
943                "fips1403",
944                "fips1402"
945            ]
946        );
947        for p in Profile::ALL {
948            assert_eq!(p.as_str().parse::<Profile>(), Ok(p));
949            assert_eq!(p.to_string(), p.as_str());
950        }
951        for bad in [
952            "",
953            "CNSA2",
954            "Cnsa2",
955            "FIPS1403",
956            "fips140-3",
957            "fips-140-3",
958            " fips1403",
959            "fips1403 ",
960            "fips1403\n",
961            " bsi",
962            "cnsa",
963            "bsi2026",
964            "preferred,",
965            "default",
966        ] {
967            assert_eq!(
968                bad.parse::<Profile>(),
969                Err(ParseProfileError(bad.to_string())),
970                "{bad:?}"
971            );
972        }
973        assert_eq!(
974            ParseProfileError("FIPS1403".to_string()).to_string(),
975            "unknown profile \"FIPS1403\""
976        );
977    }
978
979    #[test]
980    fn profile_all_lists_every_variant_in_ordinal_order() {
981        assert_eq!(
982            Profile::ALL.map(Profile::ordinal),
983            std::array::from_fn::<usize, 7, _>(|i| i)
984        );
985    }
986
987    #[test]
988    fn governing_texts_are_the_published_editions() {
989        use GoverningText::{CrateRecommendation as Own, Published};
990        let table: [(Profile, GoverningText); 7] = [
991            (Profile::Unrestricted, Own),
992            (Profile::Preferred, Own),
993            (
994                Profile::Cnsa2,
995                Published {
996                    documents: &["CNSSP 15 (December 2024), Annex B, pp. B-1 to B-2"],
997                },
998            ),
999            (
1000                Profile::Cnsa1,
1001                Published {
1002                    documents: &[
1003                        "CNSSP 15 (20 October 2016), Annex B, p. B-1",
1004                        "RFC 9151 (April 2022)",
1005                    ],
1006                },
1007            ),
1008            (
1009                Profile::Bsi,
1010                Published {
1011                    documents: &[
1012                        "BSI TR-02102-2, version 2026-01",
1013                        "BSI TR-02102-1, version 2026-01",
1014                    ],
1015                },
1016            ),
1017            (
1018                Profile::Fips1403,
1019                Published {
1020                    documents: &[
1021                        "NIST SP 800-140C r2 and SP 800-140D r2, with the CMVP lists (August 2026)",
1022                        "FIPS 140-3 Implementation Guidance (August 2026): IG C.K, D.Q, D.S",
1023                        "NIST SP 800-52r2",
1024                        "NIST SP 800-131A r2",
1025                    ],
1026                },
1027            ),
1028            (
1029                Profile::Fips1402,
1030                Published {
1031                    documents: &[
1032                        "FIPS 140-2 Annex A and Annex D (2021)",
1033                        "FIPS 186-4",
1034                        "NIST SP 800-131A r2",
1035                        "NIST SP 800-52r2",
1036                    ],
1037                },
1038            ),
1039        ];
1040        for (p, text) in table {
1041            assert_eq!(p.governing_text(), text, "{p}");
1042        }
1043    }
1044
1045    #[test]
1046    fn options_default_narrows_nothing_and_display_names_the_option() {
1047        assert_eq!(
1048            Options::default(),
1049            Options {
1050                peer_certificates_match_profile: false,
1051                pq_key_exchange_required: false
1052            }
1053        );
1054        assert_eq!(Options::default().to_string(), "no options");
1055        assert_eq!(
1056            Options {
1057                peer_certificates_match_profile: false,
1058                pq_key_exchange_required: true
1059            }
1060            .to_string(),
1061            "post-quantum key exchange required"
1062        );
1063    }
1064    #[test]
1065    fn peer_certificate_options_combinations_preserve_selection() {
1066        for (pq, peer, display) in [
1067            (false, false, "no options"),
1068            (true, false, "post-quantum key exchange required"),
1069            (false, true, "peer certificates match profile"),
1070            (
1071                true,
1072                true,
1073                "post-quantum key exchange required, peer certificates match profile",
1074            ),
1075        ] {
1076            let options = Options {
1077                pq_key_exchange_required: pq,
1078                peer_certificates_match_profile: peer,
1079            };
1080            assert_eq!(options.to_string(), display);
1081            for profile in Profile::ALL {
1082                for module in [M3S, M4S] {
1083                    let baseline = Options {
1084                        peer_certificates_match_profile: false,
1085                        ..options
1086                    };
1087                    let actual = select(profile, options, module);
1088                    let expected = select(profile, baseline, module);
1089                    match (actual, expected) {
1090                        (Ok(actual), Ok(expected)) => assert_eq!(actual, expected),
1091                        (
1092                            Err(CryptoError::EmptyProfile {
1093                                profile: p,
1094                                options: o,
1095                                category: f,
1096                            }),
1097                            Err(CryptoError::EmptyProfile {
1098                                profile: ep,
1099                                options: eo,
1100                                category: ef,
1101                            }),
1102                        ) => {
1103                            assert_eq!((p, o, f), (ep, options, ef));
1104                            assert_eq!(eo, baseline);
1105                        }
1106                        (actual, expected) => panic!("{actual:?} != {expected:?}"),
1107                    }
1108                }
1109            }
1110        }
1111    }
1112}