1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28#[non_exhaustive]
29pub enum CipherProfile {
30 Mozilla,
35 Fips1403Compliant,
43 Fips1402Compliant,
49 Fips1403Validated,
58 Cnsa1,
66 Cnsa2,
74}
75
76impl CipherProfile {
77 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 pub const FIPS_VALIDATED_AVAILABLE: bool = cfg!(feature = "fips");
89
90 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
142#[non_exhaustive]
143pub enum Crypto {
144 #[default]
146 Ring,
147 AwsLc,
151}
152
153impl Crypto {
154 pub const AWS_LC_AVAILABLE: bool = cfg!(feature = "aws-lc");
156
157 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#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
188enum Signatures {
189 None,
191 Cnsa1,
192 Fips,
193 All,
195}
196
197struct 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
277pub(crate) struct Selection {
279 pub(crate) provider: Arc<CryptoProvider>,
280 pub(crate) versions: Vec<&'static SupportedProtocolVersion>,
281 pub(crate) validated: bool,
283}
284
285struct 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
337pub(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
345pub(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
357fn known<T>(items: &[T], name: impl Fn(&T) -> String) -> String {
359 items.iter().map(name).collect::<Vec<_>>().join(", ")
360}
361
362pub(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
374pub(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 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 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
508pub(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}