Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
File diff suppressed because it is too large Load Diff
+355
View File
@@ -0,0 +1,355 @@
use alloc::vec::Vec;
// aws-lc-rs has a -- roughly -- ring-compatible API, so we just reuse all that
// glue here. The shared files should always use `super::ring_like` to access a
// ring-compatible crate, and `super::ring_shim` to bridge the gaps where they are
// small.
pub(crate) use aws_lc_rs as ring_like;
use pki_types::PrivateKeyDer;
use webpki::aws_lc_rs as webpki_algs;
use zeroize::Zeroizing;
use crate::crypto::{CryptoProvider, KeyProvider, SecureRandom, SupportedKxGroup};
use crate::enums::SignatureScheme;
use crate::rand::GetRandomFailed;
use crate::sign::SigningKey;
use crate::suites::SupportedCipherSuite;
use crate::sync::Arc;
use crate::webpki::WebPkiSupportedAlgorithms;
use crate::{Error, OtherError};
/// Hybrid public key encryption (HPKE).
pub mod hpke;
/// Post-quantum secure algorithms.
pub(crate) mod pq;
/// Using software keys for authentication.
pub mod sign;
#[path = "../ring/hash.rs"]
pub(crate) mod hash;
#[path = "../ring/hmac.rs"]
pub(crate) mod hmac;
#[path = "../ring/kx.rs"]
pub(crate) mod kx;
#[path = "../ring/quic.rs"]
pub(crate) mod quic;
#[cfg(feature = "std")]
pub(crate) mod ticketer;
#[cfg(feature = "tls12")]
pub(crate) mod tls12;
pub(crate) mod tls13;
/// A `CryptoProvider` backed by aws-lc-rs.
pub fn default_provider() -> CryptoProvider {
CryptoProvider {
cipher_suites: DEFAULT_CIPHER_SUITES.to_vec(),
kx_groups: default_kx_groups(),
signature_verification_algorithms: SUPPORTED_SIG_ALGS,
secure_random: &AwsLcRs,
key_provider: &AwsLcRs,
}
}
fn default_kx_groups() -> Vec<&'static dyn SupportedKxGroup> {
#[cfg(feature = "fips")]
{
DEFAULT_KX_GROUPS
.iter()
.filter(|cs| cs.fips())
.copied()
.collect()
}
#[cfg(not(feature = "fips"))]
{
DEFAULT_KX_GROUPS.to_vec()
}
}
#[derive(Debug)]
struct AwsLcRs;
impl SecureRandom for AwsLcRs {
fn fill(&self, buf: &mut [u8]) -> Result<(), GetRandomFailed> {
use ring_like::rand::SecureRandom;
ring_like::rand::SystemRandom::new()
.fill(buf)
.map_err(|_| GetRandomFailed)
}
fn fips(&self) -> bool {
fips()
}
}
impl KeyProvider for AwsLcRs {
fn load_private_key(
&self,
key_der: PrivateKeyDer<'static>,
) -> Result<Arc<dyn SigningKey>, Error> {
sign::any_supported_type(&Zeroizing::new(key_der))
}
fn fips(&self) -> bool {
fips()
}
}
/// The cipher suite configuration that an application should use by default.
///
/// This will be [`ALL_CIPHER_SUITES`] sans any supported cipher suites that
/// shouldn't be enabled by most applications.
pub static DEFAULT_CIPHER_SUITES: &[SupportedCipherSuite] = &[
// TLS1.3 suites
tls13::TLS13_AES_256_GCM_SHA384,
tls13::TLS13_AES_128_GCM_SHA256,
#[cfg(not(feature = "fips"))]
tls13::TLS13_CHACHA20_POLY1305_SHA256,
// TLS1.2 suites
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
#[cfg(all(feature = "tls12", not(feature = "fips")))]
tls12::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
#[cfg(all(feature = "tls12", not(feature = "fips")))]
tls12::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
];
/// A list of all the cipher suites supported by the rustls aws-lc-rs provider.
pub static ALL_CIPHER_SUITES: &[SupportedCipherSuite] = &[
// TLS1.3 suites
tls13::TLS13_AES_256_GCM_SHA384,
tls13::TLS13_AES_128_GCM_SHA256,
tls13::TLS13_CHACHA20_POLY1305_SHA256,
// TLS1.2 suites
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
];
/// All defined cipher suites supported by aws-lc-rs appear in this module.
pub mod cipher_suite {
#[cfg(feature = "tls12")]
pub use super::tls12::{
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
};
pub use super::tls13::{
TLS13_AES_128_GCM_SHA256, TLS13_AES_256_GCM_SHA384, TLS13_CHACHA20_POLY1305_SHA256,
};
}
/// A `WebPkiSupportedAlgorithms` value that reflects webpki's capabilities when
/// compiled against aws-lc-rs.
static SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms {
all: &[
webpki_algs::ECDSA_P256_SHA256,
webpki_algs::ECDSA_P256_SHA384,
webpki_algs::ECDSA_P256_SHA512,
webpki_algs::ECDSA_P384_SHA256,
webpki_algs::ECDSA_P384_SHA384,
webpki_algs::ECDSA_P384_SHA512,
webpki_algs::ECDSA_P521_SHA256,
webpki_algs::ECDSA_P521_SHA384,
webpki_algs::ECDSA_P521_SHA512,
webpki_algs::ED25519,
webpki_algs::RSA_PSS_2048_8192_SHA256_LEGACY_KEY,
webpki_algs::RSA_PSS_2048_8192_SHA384_LEGACY_KEY,
webpki_algs::RSA_PSS_2048_8192_SHA512_LEGACY_KEY,
webpki_algs::RSA_PKCS1_2048_8192_SHA256,
webpki_algs::RSA_PKCS1_2048_8192_SHA384,
webpki_algs::RSA_PKCS1_2048_8192_SHA512,
webpki_algs::RSA_PKCS1_2048_8192_SHA256_ABSENT_PARAMS,
webpki_algs::RSA_PKCS1_2048_8192_SHA384_ABSENT_PARAMS,
webpki_algs::RSA_PKCS1_2048_8192_SHA512_ABSENT_PARAMS,
webpki_algs::ML_DSA_44,
webpki_algs::ML_DSA_65,
webpki_algs::ML_DSA_87,
],
mapping: &[
// Note: for TLS1.2 the curve is not fixed by SignatureScheme. For TLS1.3 it is.
(
SignatureScheme::ECDSA_NISTP384_SHA384,
&[
webpki_algs::ECDSA_P384_SHA384,
webpki_algs::ECDSA_P256_SHA384,
webpki_algs::ECDSA_P521_SHA384,
],
),
(
SignatureScheme::ECDSA_NISTP256_SHA256,
&[
webpki_algs::ECDSA_P256_SHA256,
webpki_algs::ECDSA_P384_SHA256,
webpki_algs::ECDSA_P521_SHA256,
],
),
(
SignatureScheme::ECDSA_NISTP521_SHA512,
&[
webpki_algs::ECDSA_P521_SHA512,
webpki_algs::ECDSA_P384_SHA512,
webpki_algs::ECDSA_P256_SHA512,
],
),
(SignatureScheme::ED25519, &[webpki_algs::ED25519]),
(
SignatureScheme::RSA_PSS_SHA512,
&[webpki_algs::RSA_PSS_2048_8192_SHA512_LEGACY_KEY],
),
(
SignatureScheme::RSA_PSS_SHA384,
&[webpki_algs::RSA_PSS_2048_8192_SHA384_LEGACY_KEY],
),
(
SignatureScheme::RSA_PSS_SHA256,
&[webpki_algs::RSA_PSS_2048_8192_SHA256_LEGACY_KEY],
),
(
SignatureScheme::RSA_PKCS1_SHA512,
&[webpki_algs::RSA_PKCS1_2048_8192_SHA512],
),
(
SignatureScheme::RSA_PKCS1_SHA384,
&[webpki_algs::RSA_PKCS1_2048_8192_SHA384],
),
(
SignatureScheme::RSA_PKCS1_SHA256,
&[webpki_algs::RSA_PKCS1_2048_8192_SHA256],
),
(SignatureScheme::ML_DSA_44, &[webpki_algs::ML_DSA_44]),
(SignatureScheme::ML_DSA_65, &[webpki_algs::ML_DSA_65]),
(SignatureScheme::ML_DSA_87, &[webpki_algs::ML_DSA_87]),
],
};
/// All defined key exchange groups supported by aws-lc-rs appear in this module.
///
/// [`ALL_KX_GROUPS`] is provided as an array of all of these values.
/// [`DEFAULT_KX_GROUPS`] is provided as an array of this provider's defaults.
pub mod kx_group {
pub use super::kx::{SECP256R1, SECP384R1, X25519};
pub use super::pq::{MLKEM768, MLKEM1024, SECP256R1MLKEM768, X25519MLKEM768};
}
/// A list of the default key exchange groups supported by this provider.
///
/// This does not contain MLKEM768; by default MLKEM768 is only offered
/// in hybrid with X25519.
pub static DEFAULT_KX_GROUPS: &[&dyn SupportedKxGroup] = &[
#[cfg(feature = "prefer-post-quantum")]
kx_group::X25519MLKEM768,
kx_group::X25519,
kx_group::SECP256R1,
kx_group::SECP384R1,
#[cfg(not(feature = "prefer-post-quantum"))]
kx_group::X25519MLKEM768,
];
/// A list of all the key exchange groups supported by this provider.
pub static ALL_KX_GROUPS: &[&dyn SupportedKxGroup] = &[
#[cfg(feature = "prefer-post-quantum")]
kx_group::X25519MLKEM768,
#[cfg(feature = "prefer-post-quantum")]
kx_group::SECP256R1MLKEM768,
kx_group::X25519,
kx_group::SECP256R1,
kx_group::SECP384R1,
#[cfg(not(feature = "prefer-post-quantum"))]
kx_group::X25519MLKEM768,
#[cfg(not(feature = "prefer-post-quantum"))]
kx_group::SECP256R1MLKEM768,
kx_group::MLKEM768,
kx_group::MLKEM1024,
];
#[cfg(feature = "std")]
pub use ticketer::Ticketer;
/// Compatibility shims between ring 0.16.x and 0.17.x API
mod ring_shim {
use super::ring_like;
use crate::crypto::SharedSecret;
pub(super) fn agree_ephemeral(
priv_key: ring_like::agreement::EphemeralPrivateKey,
peer_key: &ring_like::agreement::UnparsedPublicKey<&[u8]>,
) -> Result<SharedSecret, ()> {
ring_like::agreement::agree_ephemeral(priv_key, peer_key, (), |secret| {
Ok(SharedSecret::from(secret))
})
}
}
/// Are we in FIPS mode?
pub(super) fn fips() -> bool {
aws_lc_rs::try_fips_mode().is_ok()
}
pub(super) fn unspecified_err(_e: aws_lc_rs::error::Unspecified) -> Error {
#[cfg(feature = "std")]
{
Error::Other(OtherError(Arc::new(_e)))
}
#[cfg(not(feature = "std"))]
{
Error::Other(OtherError())
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
#[cfg(feature = "fips")]
#[test]
fn default_suites_are_fips() {
assert!(
super::DEFAULT_CIPHER_SUITES
.iter()
.all(|scs| scs.fips())
);
}
#[cfg(not(feature = "fips"))]
#[test]
fn default_suites() {
assert_eq!(super::DEFAULT_CIPHER_SUITES, super::ALL_CIPHER_SUITES);
}
#[test]
fn certificate_sig_algs() {
// `all` should not contain duplicates (not incorrect, but a waste of time)
assert_eq!(
super::SUPPORTED_SIG_ALGS
.all
.iter()
.map(|alg| {
(
alg.public_key_alg_id()
.as_ref()
.to_vec(),
alg.signature_alg_id().as_ref().to_vec(),
)
})
.collect::<HashSet<_>>()
.len(),
super::SUPPORTED_SIG_ALGS.all.len(),
);
}
}
+205
View File
@@ -0,0 +1,205 @@
use alloc::boxed::Box;
use alloc::vec::Vec;
use super::INVALID_KEY_SHARE;
use crate::crypto::{ActiveKeyExchange, CompletedKeyExchange, SharedSecret, SupportedKxGroup};
use crate::ffdhe_groups::FfdheGroup;
use crate::{Error, NamedGroup, ProtocolVersion};
/// A generalization of hybrid key exchange.
#[derive(Debug)]
pub(crate) struct Hybrid {
pub(crate) classical: &'static dyn SupportedKxGroup,
pub(crate) post_quantum: &'static dyn SupportedKxGroup,
pub(crate) name: NamedGroup,
pub(crate) layout: Layout,
}
impl SupportedKxGroup for Hybrid {
fn start(&self) -> Result<Box<dyn ActiveKeyExchange>, Error> {
let classical = self.classical.start()?;
let post_quantum = self.post_quantum.start()?;
let combined_pub_key = self
.layout
.concat(post_quantum.pub_key(), classical.pub_key());
Ok(Box::new(ActiveHybrid {
classical,
post_quantum,
name: self.name,
layout: self.layout,
combined_pub_key,
}))
}
fn start_and_complete(&self, client_share: &[u8]) -> Result<CompletedKeyExchange, Error> {
let (post_quantum_share, classical_share) = self
.layout
.split_received_client_share(client_share)
.ok_or(INVALID_KEY_SHARE)?;
let cl = self
.classical
.start_and_complete(classical_share)?;
let pq = self
.post_quantum
.start_and_complete(post_quantum_share)?;
let combined_pub_key = self
.layout
.concat(&pq.pub_key, &cl.pub_key);
let secret = self
.layout
.concat(pq.secret.secret_bytes(), cl.secret.secret_bytes());
Ok(CompletedKeyExchange {
group: self.name,
pub_key: combined_pub_key,
secret: SharedSecret::from(secret),
})
}
fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
None
}
fn name(&self) -> NamedGroup {
self.name
}
fn fips(&self) -> bool {
// Behold! The Night Mare: SP800-56C rev 2:
//
// "In addition to the currently approved techniques for the generation of the
// shared secret Z as specified in SP 800-56A and SP 800-56B, this Recommendation
// permits the use of a "hybrid" shared secret of the form Z′ = Z || T, a
// concatenation consisting of a "standard" shared secret Z that was generated
// during the execution of a key-establishment scheme (as currently specified in
// [SP 800-56A] or [SP 800-56B])"
//
// NIST plan to adjust this and allow both orders: see
// <https://csrc.nist.gov/pubs/sp/800/227/ipd> (Jan 2025) lines 1070-1080.
//
// But, for now, we follow the SP800-56C logic: the element appearing first is the
// one that controls approval.
match self.layout.post_quantum_first {
true => self.post_quantum.fips(),
false => self.classical.fips(),
}
}
fn usable_for_version(&self, version: ProtocolVersion) -> bool {
version == ProtocolVersion::TLSv1_3
}
}
struct ActiveHybrid {
classical: Box<dyn ActiveKeyExchange>,
post_quantum: Box<dyn ActiveKeyExchange>,
name: NamedGroup,
layout: Layout,
combined_pub_key: Vec<u8>,
}
impl ActiveKeyExchange for ActiveHybrid {
fn complete(self: Box<Self>, peer_pub_key: &[u8]) -> Result<SharedSecret, Error> {
let (post_quantum_share, classical_share) = self
.layout
.split_received_server_share(peer_pub_key)
.ok_or(INVALID_KEY_SHARE)?;
let cl = self
.classical
.complete(classical_share)?;
let pq = self
.post_quantum
.complete(post_quantum_share)?;
let secret = self
.layout
.concat(pq.secret_bytes(), cl.secret_bytes());
Ok(SharedSecret::from(secret))
}
/// Allow the classical computation to be offered and selected separately.
fn hybrid_component(&self) -> Option<(NamedGroup, &[u8])> {
Some((self.classical.group(), self.classical.pub_key()))
}
fn complete_hybrid_component(
self: Box<Self>,
peer_pub_key: &[u8],
) -> Result<SharedSecret, Error> {
self.classical.complete(peer_pub_key)
}
fn pub_key(&self) -> &[u8] {
&self.combined_pub_key
}
fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
None
}
fn group(&self) -> NamedGroup {
self.name
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Layout {
/// Length of classical key share.
pub(crate) classical_share_len: usize,
/// Length of post-quantum key share sent by client
pub(crate) post_quantum_client_share_len: usize,
/// Length of post-quantum key share sent by server
pub(crate) post_quantum_server_share_len: usize,
/// Whether the post-quantum element comes first in shares and secrets.
///
/// For dismal and unprincipled reasons, SECP256R1MLKEM768 has the
/// classical element first, while X25519MLKEM768 has it second.
pub(crate) post_quantum_first: bool,
}
impl Layout {
fn split_received_client_share<'a>(&self, share: &'a [u8]) -> Option<(&'a [u8], &'a [u8])> {
self.split(share, self.post_quantum_client_share_len)
}
fn split_received_server_share<'a>(&self, share: &'a [u8]) -> Option<(&'a [u8], &'a [u8])> {
self.split(share, self.post_quantum_server_share_len)
}
/// Return the PQ and classical component of a key share.
fn split<'a>(
&self,
share: &'a [u8],
post_quantum_share_len: usize,
) -> Option<(&'a [u8], &'a [u8])> {
if share.len() != self.classical_share_len + post_quantum_share_len {
return None;
}
Some(match self.post_quantum_first {
true => {
let (first_share, second_share) = share.split_at(post_quantum_share_len);
(first_share, second_share)
}
false => {
let (first_share, second_share) = share.split_at(self.classical_share_len);
(second_share, first_share)
}
})
}
fn concat(&self, post_quantum: &[u8], classical: &[u8]) -> Vec<u8> {
match self.post_quantum_first {
true => [post_quantum, classical].concat(),
false => [classical, post_quantum].concat(),
}
}
}
+108
View File
@@ -0,0 +1,108 @@
use alloc::boxed::Box;
use alloc::vec::Vec;
use aws_lc_rs::kem;
use super::INVALID_KEY_SHARE;
use crate::crypto::{ActiveKeyExchange, CompletedKeyExchange, SharedSecret, SupportedKxGroup};
use crate::ffdhe_groups::FfdheGroup;
use crate::{Error, NamedGroup, ProtocolVersion};
#[derive(Debug)]
pub(crate) struct MlKem {
pub(crate) alg: &'static kem::Algorithm<kem::AlgorithmId>,
pub(crate) group: NamedGroup,
}
impl SupportedKxGroup for MlKem {
fn start(&self) -> Result<Box<dyn ActiveKeyExchange>, Error> {
let decaps_key = kem::DecapsulationKey::generate(self.alg)
.map_err(|_| Error::General("key generation failed".into()))?;
let pub_key_bytes = decaps_key
.encapsulation_key()
.and_then(|encaps_key| encaps_key.key_bytes())
.map_err(|_| Error::General("encaps failed".into()))?;
Ok(Box::new(Active {
decaps_key: Box::new(decaps_key),
encaps_key_bytes: Vec::from(pub_key_bytes.as_ref()),
group: self.group,
}))
}
fn start_and_complete(&self, client_share: &[u8]) -> Result<CompletedKeyExchange, Error> {
let encaps_key =
kem::EncapsulationKey::new(self.alg, client_share).map_err(|_| INVALID_KEY_SHARE)?;
let (ciphertext, shared_secret) = encaps_key
.encapsulate()
.map_err(|_| INVALID_KEY_SHARE)?;
Ok(CompletedKeyExchange {
group: self.name(),
pub_key: Vec::from(ciphertext.as_ref()),
secret: SharedSecret::from(shared_secret.as_ref()),
})
}
fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
None
}
fn name(&self) -> NamedGroup {
self.group
}
fn fips(&self) -> bool {
// AUDITORS:
// At the time of writing, the ML-KEM implementation in AWS-LC-FIPS module 3.0
// is FIPS-pending. Some regulatory regimes (eg, FedRAMP rev 5 SC-13) allow
// use of implementations in this state, as if they are already approved.
//
// We follow this liberal interpretation, and say MlKem768 is FIPS-compliant
// if the underlying library is in FIPS mode.
//
// TODO: adjust the `fips()` function return type to allow more policies to
// be expressed, perhaps following something like
// <https://github.com/golang/go/issues/70200#issuecomment-2490017956> --
// see <https://github.com/rustls/rustls/issues/2309>
super::super::fips()
}
fn usable_for_version(&self, version: ProtocolVersion) -> bool {
version == ProtocolVersion::TLSv1_3
}
}
struct Active {
decaps_key: Box<kem::DecapsulationKey<kem::AlgorithmId>>,
encaps_key_bytes: Vec<u8>,
group: NamedGroup,
}
impl ActiveKeyExchange for Active {
// The received 'peer_pub_key' is actually the ML-KEM ciphertext,
// which when decapsulated with our `decaps_key` produces the shared
// secret.
fn complete(self: Box<Self>, peer_pub_key: &[u8]) -> Result<SharedSecret, Error> {
let shared_secret = self
.decaps_key
.decapsulate(peer_pub_key.into())
.map_err(|_| INVALID_KEY_SHARE)?;
Ok(SharedSecret::from(shared_secret.as_ref()))
}
fn pub_key(&self) -> &[u8] {
&self.encaps_key_bytes
}
fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
None
}
fn group(&self) -> NamedGroup {
self.group
}
}
+62
View File
@@ -0,0 +1,62 @@
use aws_lc_rs::kem;
use crate::crypto::SupportedKxGroup;
use crate::crypto::aws_lc_rs::kx_group;
use crate::crypto::aws_lc_rs::pq::mlkem::MlKem;
use crate::{Error, NamedGroup, PeerMisbehaved};
mod hybrid;
mod mlkem;
/// This is the [X25519MLKEM768] key exchange.
///
/// [X25519MLKEM768]: <https://datatracker.ietf.org/doc/draft-ietf-tls-ecdhe-mlkem/>
pub static X25519MLKEM768: &dyn SupportedKxGroup = &hybrid::Hybrid {
classical: kx_group::X25519,
post_quantum: MLKEM768,
name: NamedGroup::X25519MLKEM768,
layout: hybrid::Layout {
classical_share_len: X25519_LEN,
post_quantum_client_share_len: MLKEM768_ENCAP_LEN,
post_quantum_server_share_len: MLKEM768_CIPHERTEXT_LEN,
post_quantum_first: true,
},
};
/// This is the [SECP256R1MLKEM768] key exchange.
///
/// [SECP256R1MLKEM768]: <https://datatracker.ietf.org/doc/draft-ietf-tls-ecdhe-mlkem/>
pub static SECP256R1MLKEM768: &dyn SupportedKxGroup = &hybrid::Hybrid {
classical: kx_group::SECP256R1,
post_quantum: MLKEM768,
name: NamedGroup::secp256r1MLKEM768,
layout: hybrid::Layout {
classical_share_len: SECP256R1_LEN,
post_quantum_client_share_len: MLKEM768_ENCAP_LEN,
post_quantum_server_share_len: MLKEM768_CIPHERTEXT_LEN,
post_quantum_first: false,
},
};
/// This is the [MLKEM] key encapsulation mechanism in NIST with security category 3.
///
/// [MLKEM]: https://datatracker.ietf.org/doc/draft-ietf-tls-mlkem
pub static MLKEM768: &dyn SupportedKxGroup = &MlKem {
alg: &kem::ML_KEM_768,
group: NamedGroup::MLKEM768,
};
/// This is the [MLKEM] key encapsulation mechanism in NIST with security category 5.
///
/// [MLKEM]: https://datatracker.ietf.org/doc/draft-ietf-tls-mlkem
pub static MLKEM1024: &dyn SupportedKxGroup = &MlKem {
alg: &kem::ML_KEM_1024,
group: NamedGroup::MLKEM1024,
};
const INVALID_KEY_SHARE: Error = Error::PeerMisbehaved(PeerMisbehaved::InvalidKeyShare);
const X25519_LEN: usize = 32;
const SECP256R1_LEN: usize = 65;
const MLKEM768_CIPHERTEXT_LEN: usize = 1088;
const MLKEM768_ENCAP_LEN: usize = 1184;
File diff suppressed because it is too large Load Diff
+411
View File
@@ -0,0 +1,411 @@
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt;
use core::fmt::{Debug, Formatter};
use core::sync::atomic::{AtomicUsize, Ordering};
use aws_lc_rs::cipher::{
AES_256, AES_256_KEY_LEN, AES_CBC_IV_LEN, DecryptionContext, PaddedBlockDecryptingKey,
PaddedBlockEncryptingKey, UnboundCipherKey,
};
use aws_lc_rs::{hmac, iv};
use super::ring_like::rand::{SecureRandom, SystemRandom};
use super::unspecified_err;
use crate::error::Error;
#[cfg(debug_assertions)]
use crate::log::debug;
use crate::polyfill::try_split_at;
use crate::rand::GetRandomFailed;
use crate::server::ProducesTickets;
use crate::sync::Arc;
/// A concrete, safe ticket creation mechanism.
pub struct Ticketer {}
impl Ticketer {
/// Make the recommended `Ticketer`. This produces tickets
/// with a 12 hour life and randomly generated keys.
///
/// The `Ticketer` uses the [RFC 5077 §4] "Recommended Ticket Construction",
/// using AES 256 for encryption and HMAC-SHA256 for ciphertext authentication.
///
/// [RFC 5077 §4]: https://www.rfc-editor.org/rfc/rfc5077#section-4
#[cfg(feature = "std")]
pub fn new() -> Result<Arc<dyn ProducesTickets>, Error> {
Ok(Arc::new(crate::ticketer::TicketRotator::new(
6 * 60 * 60,
make_ticket_generator,
)?))
}
}
fn make_ticket_generator() -> Result<Box<dyn ProducesTickets>, GetRandomFailed> {
// NOTE(XXX): Unconditionally mapping errors to `GetRandomFailed` here is slightly
// misleading in some cases (e.g. failure to construct a padded block cipher encrypting key).
// However, we can't change the return type expected from a `TicketSwitcher` `generator`
// without breaking semver.
// Tracking in https://github.com/rustls/rustls/issues/2074
Ok(Box::new(
Rfc5077Ticketer::new().map_err(|_| GetRandomFailed)?,
))
}
/// An RFC 5077 "Recommended Ticket Construction" implementation of a [`Ticketer`].
struct Rfc5077Ticketer {
aes_encrypt_key: PaddedBlockEncryptingKey,
aes_decrypt_key: PaddedBlockDecryptingKey,
hmac_key: hmac::Key,
key_name: [u8; 16],
lifetime: u32,
maximum_ciphertext_len: AtomicUsize,
}
impl Rfc5077Ticketer {
fn new() -> Result<Self, Error> {
let rand = SystemRandom::new();
// Generate a random AES 256 key to use for AES CBC encryption.
let mut aes_key = [0u8; AES_256_KEY_LEN];
rand.fill(&mut aes_key)
.map_err(|_| GetRandomFailed)?;
// Convert the raw AES 256 key bytes into encrypting and decrypting keys using CBC mode and
// PKCS#7 padding. We don't want to store just the raw key bytes as constructing the
// cipher keys has some setup overhead. We can't store just the `UnboundCipherKey` since
// constructing the padded encrypt/decrypt specific types consume the `UnboundCipherKey`.
let aes_encrypt_key =
UnboundCipherKey::new(&AES_256, &aes_key[..]).map_err(unspecified_err)?;
let aes_encrypt_key =
PaddedBlockEncryptingKey::cbc_pkcs7(aes_encrypt_key).map_err(unspecified_err)?;
// Convert the raw AES 256 key bytes into a decrypting key using CBC PKCS#7 padding.
let aes_decrypt_key =
UnboundCipherKey::new(&AES_256, &aes_key[..]).map_err(unspecified_err)?;
let aes_decrypt_key =
PaddedBlockDecryptingKey::cbc_pkcs7(aes_decrypt_key).map_err(unspecified_err)?;
// Generate a random HMAC SHA256 key to use for HMAC authentication.
let hmac_key = hmac::Key::generate(hmac::HMAC_SHA256, &rand).map_err(unspecified_err)?;
// Generate a random key name.
let mut key_name = [0u8; 16];
rand.fill(&mut key_name)
.map_err(|_| GetRandomFailed)?;
Ok(Self {
aes_encrypt_key,
aes_decrypt_key,
hmac_key,
key_name,
lifetime: 60 * 60 * 12,
maximum_ciphertext_len: AtomicUsize::new(0),
})
}
}
impl ProducesTickets for Rfc5077Ticketer {
fn enabled(&self) -> bool {
true
}
fn lifetime(&self) -> u32 {
self.lifetime
}
/// Encrypt `message` and return the ciphertext.
fn encrypt(&self, message: &[u8]) -> Option<Vec<u8>> {
// Encrypt the ticket state - the cipher module handles generating a random IV of
// appropriate size, returning it in the `DecryptionContext`.
let mut encrypted_state = Vec::from(message);
let dec_ctx = self
.aes_encrypt_key
.encrypt(&mut encrypted_state)
.ok()?;
let iv: &[u8] = (&dec_ctx).try_into().ok()?;
// Produce the MAC tag over the relevant context & encrypted state.
// Quoting RFC 5077:
// "The Message Authentication Code (MAC) is calculated using HMAC-SHA-256 over
// key_name (16 octets) and IV (16 octets), followed by the length of
// the encrypted_state field (2 octets) and its contents (variable
// length)."
let mut hmac_data =
Vec::with_capacity(self.key_name.len() + iv.len() + 2 + encrypted_state.len());
hmac_data.extend(&self.key_name);
hmac_data.extend(iv);
hmac_data.extend(
u16::try_from(encrypted_state.len())
.ok()?
.to_be_bytes(),
);
hmac_data.extend(&encrypted_state);
let tag = hmac::sign(&self.hmac_key, &hmac_data);
let tag = tag.as_ref();
// Combine the context, the encrypted state, and the tag to produce the final ciphertext.
// Ciphertext structure is:
// key_name: [u8; 16]
// iv: [u8; 16]
// encrypted_state: [u8, _]
// mac tag: [u8; 32]
let mut ciphertext =
Vec::with_capacity(self.key_name.len() + iv.len() + encrypted_state.len() + tag.len());
ciphertext.extend(self.key_name);
ciphertext.extend(iv);
ciphertext.extend(encrypted_state);
ciphertext.extend(tag);
self.maximum_ciphertext_len
.fetch_max(ciphertext.len(), Ordering::SeqCst);
Some(ciphertext)
}
fn decrypt(&self, ciphertext: &[u8]) -> Option<Vec<u8>> {
if ciphertext.len()
> self
.maximum_ciphertext_len
.load(Ordering::SeqCst)
{
#[cfg(debug_assertions)]
debug!("rejected over-length ticket");
return None;
}
// Split off the key name from the remaining ciphertext.
let (alleged_key_name, ciphertext) = try_split_at(ciphertext, self.key_name.len())?;
// Split off the IV from the remaining ciphertext.
let (iv, ciphertext) = try_split_at(ciphertext, AES_CBC_IV_LEN)?;
// And finally, split the encrypted state from the tag.
let tag_len = self
.hmac_key
.algorithm()
.digest_algorithm()
.output_len();
let (enc_state, mac) = try_split_at(ciphertext, ciphertext.len().checked_sub(tag_len)?)?;
// Reconstitute the HMAC data to verify the tag.
let mut hmac_data =
Vec::with_capacity(alleged_key_name.len() + iv.len() + 2 + enc_state.len());
hmac_data.extend(alleged_key_name);
hmac_data.extend(iv);
hmac_data.extend(
u16::try_from(enc_state.len())
.ok()?
.to_be_bytes(),
);
hmac_data.extend(enc_state);
hmac::verify(&self.hmac_key, &hmac_data, mac).ok()?;
// Convert the raw IV back into an appropriate decryption context.
let iv = iv::FixedLength::try_from(iv).ok()?;
let dec_context = DecryptionContext::Iv128(iv);
// And finally, decrypt the encrypted state.
let mut out = Vec::from(enc_state);
let plaintext = self
.aes_decrypt_key
.decrypt(&mut out, dec_context)
.ok()?;
Some(plaintext.into())
}
}
impl Debug for Rfc5077Ticketer {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
// Note: we deliberately omit keys from the debug output.
f.debug_struct("Rfc5077Ticketer")
.field("lifetime", &self.lifetime)
.finish()
}
}
#[cfg(test)]
mod tests {
use core::time::Duration;
use pki_types::UnixTime;
use super::*;
#[test]
fn basic_pairwise_test() {
let t = Ticketer::new().unwrap();
assert!(t.enabled());
let cipher = t.encrypt(b"hello world").unwrap();
let plain = t.decrypt(&cipher).unwrap();
assert_eq!(plain, b"hello world");
}
#[test]
fn refuses_decrypt_before_encrypt() {
let t = Ticketer::new().unwrap();
assert_eq!(t.decrypt(b"hello"), None);
}
#[test]
fn refuses_decrypt_larger_than_largest_encryption() {
let t = Ticketer::new().unwrap();
let mut cipher = t.encrypt(b"hello world").unwrap();
assert_eq!(t.decrypt(&cipher), Some(b"hello world".to_vec()));
// obviously this would never work anyway, but this
// and `cannot_decrypt_before_encrypt` exercise the
// first branch in `decrypt()`
cipher.push(0);
assert_eq!(t.decrypt(&cipher), None);
}
#[test]
fn ticketrotator_switching_test() {
let t = Arc::new(crate::ticketer::TicketRotator::new(1, make_ticket_generator).unwrap());
let now = UnixTime::now();
let cipher1 = t.encrypt(b"ticket 1").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
{
// Trigger new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 10,
)));
}
let cipher2 = t.encrypt(b"ticket 2").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
{
// Trigger new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 20,
)));
}
let cipher3 = t.encrypt(b"ticket 3").unwrap();
assert!(t.decrypt(&cipher1).is_none());
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
}
#[test]
fn ticketrotator_remains_usable_over_temporary_ticketer_creation_failure() {
let mut t = crate::ticketer::TicketRotator::new(1, make_ticket_generator).unwrap();
let now = UnixTime::now();
let cipher1 = t.encrypt(b"ticket 1").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
t.generator = fail_generator;
{
// Failed new ticketer; this means we still need to
// rotate.
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 10,
)));
}
// check post-failure encryption/decryption still works
let cipher2 = t.encrypt(b"ticket 2").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
// do the rotation for real
t.generator = make_ticket_generator;
{
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 20,
)));
}
let cipher3 = t.encrypt(b"ticket 3").unwrap();
assert!(t.decrypt(&cipher1).is_some());
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
}
#[test]
fn ticketswitcher_switching_test() {
#[expect(deprecated)]
let t = Arc::new(crate::ticketer::TicketSwitcher::new(1, make_ticket_generator).unwrap());
let now = UnixTime::now();
let cipher1 = t.encrypt(b"ticket 1").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
{
// Trigger new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 10,
)));
}
let cipher2 = t.encrypt(b"ticket 2").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
{
// Trigger new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 20,
)));
}
let cipher3 = t.encrypt(b"ticket 3").unwrap();
assert!(t.decrypt(&cipher1).is_none());
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
}
#[test]
fn ticketswitcher_recover_test() {
#[expect(deprecated)]
let mut t = crate::ticketer::TicketSwitcher::new(1, make_ticket_generator).unwrap();
let now = UnixTime::now();
let cipher1 = t.encrypt(b"ticket 1").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
t.generator = fail_generator;
{
// Failed new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 10,
)));
}
t.generator = make_ticket_generator;
let cipher2 = t.encrypt(b"ticket 2").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
{
// recover
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 20,
)));
}
let cipher3 = t.encrypt(b"ticket 3").unwrap();
assert!(t.decrypt(&cipher1).is_none());
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
}
#[test]
fn refuses_decrypt_truncated_ciphertext() {
let t = make_ticket_generator().unwrap();
let cipher = t.encrypt(b"hello world").unwrap();
assert_eq!(t.decrypt(&cipher), Some(b"hello world".to_vec()));
// a truncation is rejected at any length; lengths that leave fewer
// bytes than the trailing tag after the key_name and iv prefix
// exercise the final split.
for len in 0..cipher.len() {
assert_eq!(t.decrypt(&cipher[..len]), None);
}
}
#[test]
fn rfc5077ticketer_is_debug_and_producestickets() {
use alloc::format;
use super::*;
let t = make_ticket_generator().unwrap();
assert_eq!(format!("{t:?}"), "Rfc5077Ticketer { lifetime: 43200 }");
assert!(t.enabled());
assert_eq!(t.lifetime(), 43200);
}
fn fail_generator() -> Result<Box<dyn ProducesTickets>, GetRandomFailed> {
Err(GetRandomFailed)
}
}
+465
View File
@@ -0,0 +1,465 @@
use alloc::boxed::Box;
use aws_lc_rs::{aead, tls_prf};
use crate::crypto::cipher::{
AeadKey, InboundOpaqueMessage, Iv, KeyBlockShape, MessageDecrypter, MessageEncrypter,
NONCE_LEN, Nonce, Tls12AeadAlgorithm, UnsupportedOperationError, make_tls12_aad,
};
use crate::crypto::tls12::Prf;
use crate::crypto::{ActiveKeyExchange, KeyExchangeAlgorithm};
use crate::enums::{CipherSuite, SignatureScheme};
use crate::error::Error;
use crate::msgs::fragmenter::MAX_FRAGMENT_LEN;
use crate::msgs::message::{
InboundPlainMessage, OutboundOpaqueMessage, OutboundPlainMessage, PrefixedPayload,
};
use crate::suites::{CipherSuiteCommon, ConnectionTrafficSecrets, SupportedCipherSuite};
use crate::tls12::Tls12CipherSuite;
use crate::version::TLS12;
/// The TLS1.2 ciphersuite TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256.
pub static TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: u64::MAX,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_ECDSA_SCHEMES,
aead_alg: &ChaCha20Poly1305,
prf_provider: &Tls12Prf(&tls_prf::P_SHA256),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
pub static TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: u64::MAX,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_RSA_SCHEMES,
aead_alg: &ChaCha20Poly1305,
prf_provider: &Tls12Prf(&tls_prf::P_SHA256),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
pub static TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: 1 << 24,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_RSA_SCHEMES,
aead_alg: &AES128_GCM,
prf_provider: &Tls12Prf(&tls_prf::P_SHA256),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
pub static TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
hash_provider: &super::hash::SHA384,
confidentiality_limit: 1 << 24,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_RSA_SCHEMES,
aead_alg: &AES256_GCM,
prf_provider: &Tls12Prf(&tls_prf::P_SHA384),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
pub static TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: 1 << 24,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_ECDSA_SCHEMES,
aead_alg: &AES128_GCM,
prf_provider: &Tls12Prf(&tls_prf::P_SHA256),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
pub static TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
hash_provider: &super::hash::SHA384,
confidentiality_limit: 1 << 24,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_ECDSA_SCHEMES,
aead_alg: &AES256_GCM,
prf_provider: &Tls12Prf(&tls_prf::P_SHA384),
});
static TLS12_ECDSA_SCHEMES: &[SignatureScheme] = &[
SignatureScheme::ED25519,
SignatureScheme::ECDSA_NISTP521_SHA512,
SignatureScheme::ECDSA_NISTP384_SHA384,
SignatureScheme::ECDSA_NISTP256_SHA256,
];
static TLS12_RSA_SCHEMES: &[SignatureScheme] = &[
SignatureScheme::RSA_PSS_SHA512,
SignatureScheme::RSA_PSS_SHA384,
SignatureScheme::RSA_PSS_SHA256,
SignatureScheme::RSA_PKCS1_SHA512,
SignatureScheme::RSA_PKCS1_SHA384,
SignatureScheme::RSA_PKCS1_SHA256,
];
pub(crate) static AES128_GCM: GcmAlgorithm = GcmAlgorithm(&aead::AES_128_GCM);
pub(crate) static AES256_GCM: GcmAlgorithm = GcmAlgorithm(&aead::AES_256_GCM);
pub(crate) struct GcmAlgorithm(&'static aead::Algorithm);
impl Tls12AeadAlgorithm for GcmAlgorithm {
fn decrypter(&self, dec_key: AeadKey, dec_iv: &[u8]) -> Box<dyn MessageDecrypter> {
// safety: see `encrypter()`.
let dec_key =
aead::TlsRecordOpeningKey::new(self.0, aead::TlsProtocolId::TLS12, dec_key.as_ref())
.unwrap();
let mut ret = GcmMessageDecrypter {
dec_key,
dec_salt: [0u8; 4],
};
debug_assert_eq!(dec_iv.len(), 4);
ret.dec_salt.copy_from_slice(dec_iv);
Box::new(ret)
}
fn encrypter(
&self,
enc_key: AeadKey,
write_iv: &[u8],
explicit: &[u8],
) -> Box<dyn MessageEncrypter> {
// safety: `TlsRecordSealingKey::new` fails if
// - `enc_key`'s length is wrong for `algorithm`. But the length is defined by
// `algorithm.key_len()` in `key_block_shape()`, below.
// - `algorithm` is not supported: but `AES_128_GCM` and `AES_256_GCM` is.
// thus, this `unwrap()` is unreachable.
//
// `TlsProtocolId::TLS13` is deliberate: we reuse the nonce construction from
// RFC7905 and TLS13: a random starting point, XOR'd with the sequence number. This means
// `TlsProtocolId::TLS12` (which wants to see a plain sequence number) is unsuitable.
//
// The most important property is that nonce is unique per key, which is satisfied by
// this construction, even if the nonce is not monotonically increasing.
let enc_key =
aead::TlsRecordSealingKey::new(self.0, aead::TlsProtocolId::TLS13, enc_key.as_ref())
.unwrap();
let iv = gcm_iv(write_iv, explicit);
Box::new(GcmMessageEncrypter { enc_key, iv })
}
fn key_block_shape(&self) -> KeyBlockShape {
KeyBlockShape {
enc_key_len: self.0.key_len(),
fixed_iv_len: 4,
explicit_nonce_len: 8,
}
}
fn extract_keys(
&self,
key: AeadKey,
write_iv: &[u8],
explicit: &[u8],
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
let iv = gcm_iv(write_iv, explicit);
Ok(match self.0.key_len() {
16 => ConnectionTrafficSecrets::Aes128Gcm { key, iv },
32 => ConnectionTrafficSecrets::Aes256Gcm { key, iv },
_ => unreachable!(),
})
}
fn fips(&self) -> bool {
super::fips()
}
}
pub(crate) struct ChaCha20Poly1305;
impl Tls12AeadAlgorithm for ChaCha20Poly1305 {
fn decrypter(&self, dec_key: AeadKey, iv: &[u8]) -> Box<dyn MessageDecrypter> {
let dec_key = aead::LessSafeKey::new(
aead::UnboundKey::new(&aead::CHACHA20_POLY1305, dec_key.as_ref()).unwrap(),
);
Box::new(ChaCha20Poly1305MessageDecrypter {
dec_key,
dec_offset: Iv::copy(iv),
})
}
fn encrypter(&self, enc_key: AeadKey, enc_iv: &[u8], _: &[u8]) -> Box<dyn MessageEncrypter> {
let enc_key = aead::LessSafeKey::new(
aead::UnboundKey::new(&aead::CHACHA20_POLY1305, enc_key.as_ref()).unwrap(),
);
Box::new(ChaCha20Poly1305MessageEncrypter {
enc_key,
enc_offset: Iv::copy(enc_iv),
})
}
fn key_block_shape(&self) -> KeyBlockShape {
KeyBlockShape {
enc_key_len: 32,
fixed_iv_len: 12,
explicit_nonce_len: 0,
}
}
fn extract_keys(
&self,
key: AeadKey,
iv: &[u8],
_explicit: &[u8],
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
// This should always be true because KeyBlockShape and the Iv nonce len are in agreement.
debug_assert_eq!(aead::NONCE_LEN, iv.len());
Ok(ConnectionTrafficSecrets::Chacha20Poly1305 {
key,
iv: Iv::new(iv[..].try_into().unwrap()),
})
}
fn fips(&self) -> bool {
false // not FIPS approved
}
}
/// A `MessageEncrypter` for AES-GCM AEAD ciphersuites. TLS 1.2 only.
struct GcmMessageEncrypter {
enc_key: aead::TlsRecordSealingKey,
iv: Iv,
}
/// A `MessageDecrypter` for AES-GCM AEAD ciphersuites. TLS1.2 only.
struct GcmMessageDecrypter {
dec_key: aead::TlsRecordOpeningKey,
dec_salt: [u8; 4],
}
const GCM_EXPLICIT_NONCE_LEN: usize = 8;
const GCM_OVERHEAD: usize = GCM_EXPLICIT_NONCE_LEN + 16;
impl MessageDecrypter for GcmMessageDecrypter {
fn decrypt<'a>(
&mut self,
mut msg: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, Error> {
let payload = &msg.payload;
if payload.len() < GCM_OVERHEAD {
return Err(Error::DecryptError);
}
let nonce = {
let mut nonce = [0u8; 12];
nonce[..4].copy_from_slice(&self.dec_salt);
nonce[4..].copy_from_slice(&payload[..8]);
aead::Nonce::assume_unique_for_key(nonce)
};
let aad = aead::Aad::from(make_tls12_aad(
seq,
msg.typ,
msg.version,
payload.len() - GCM_OVERHEAD,
));
let payload = &mut msg.payload;
let plain_len = self
.dec_key
.open_in_place(nonce, aad, &mut payload[GCM_EXPLICIT_NONCE_LEN..])
.map_err(|_| Error::DecryptError)?
.len();
if plain_len > MAX_FRAGMENT_LEN {
return Err(Error::PeerSentOversizedRecord);
}
Ok(
msg.into_plain_message_range(
GCM_EXPLICIT_NONCE_LEN..GCM_EXPLICIT_NONCE_LEN + plain_len,
),
)
}
}
impl MessageEncrypter for GcmMessageEncrypter {
fn encrypt(
&mut self,
msg: OutboundPlainMessage<'_>,
seq: u64,
) -> Result<OutboundOpaqueMessage, Error> {
let total_len = self.encrypted_payload_len(msg.payload.len());
let mut payload = PrefixedPayload::with_capacity(total_len);
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, seq).0);
let aad = aead::Aad::from(make_tls12_aad(seq, msg.typ, msg.version, msg.payload.len()));
payload.extend_from_slice(&nonce.as_ref()[4..]);
payload.extend_from_chunks(&msg.payload);
self.enc_key
.seal_in_place_separate_tag(nonce, aad, &mut payload.as_mut()[GCM_EXPLICIT_NONCE_LEN..])
.map(|tag| payload.extend_from_slice(tag.as_ref()))
.map_err(|_| Error::EncryptError)?;
Ok(OutboundOpaqueMessage::new(msg.typ, msg.version, payload))
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len + GCM_EXPLICIT_NONCE_LEN + self.enc_key.algorithm().tag_len()
}
}
/// The RFC7905/RFC7539 ChaCha20Poly1305 construction.
/// This implementation does the AAD construction required in TLS1.2.
/// TLS1.3 uses `TLS13MessageEncrypter`.
struct ChaCha20Poly1305MessageEncrypter {
enc_key: aead::LessSafeKey,
enc_offset: Iv,
}
/// The RFC7905/RFC7539 ChaCha20Poly1305 construction.
/// This implementation does the AAD construction required in TLS1.2.
/// TLS1.3 uses `TLS13MessageDecrypter`.
struct ChaCha20Poly1305MessageDecrypter {
dec_key: aead::LessSafeKey,
dec_offset: Iv,
}
const CHACHAPOLY1305_OVERHEAD: usize = 16;
impl MessageDecrypter for ChaCha20Poly1305MessageDecrypter {
fn decrypt<'a>(
&mut self,
mut msg: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, Error> {
let payload = &msg.payload;
if payload.len() < CHACHAPOLY1305_OVERHEAD {
return Err(Error::DecryptError);
}
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.dec_offset, seq).0);
let aad = aead::Aad::from(make_tls12_aad(
seq,
msg.typ,
msg.version,
payload.len() - CHACHAPOLY1305_OVERHEAD,
));
let payload = &mut msg.payload;
let plain_len = self
.dec_key
.open_in_place(nonce, aad, payload)
.map_err(|_| Error::DecryptError)?
.len();
if plain_len > MAX_FRAGMENT_LEN {
return Err(Error::PeerSentOversizedRecord);
}
payload.truncate(plain_len);
Ok(msg.into_plain_message())
}
}
impl MessageEncrypter for ChaCha20Poly1305MessageEncrypter {
fn encrypt(
&mut self,
msg: OutboundPlainMessage<'_>,
seq: u64,
) -> Result<OutboundOpaqueMessage, Error> {
let total_len = self.encrypted_payload_len(msg.payload.len());
let mut payload = PrefixedPayload::with_capacity(total_len);
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.enc_offset, seq).0);
let aad = aead::Aad::from(make_tls12_aad(seq, msg.typ, msg.version, msg.payload.len()));
payload.extend_from_chunks(&msg.payload);
self.enc_key
.seal_in_place_append_tag(nonce, aad, &mut payload)
.map_err(|_| Error::EncryptError)?;
Ok(OutboundOpaqueMessage::new(msg.typ, msg.version, payload))
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len + self.enc_key.algorithm().tag_len()
}
}
fn gcm_iv(write_iv: &[u8], explicit: &[u8]) -> Iv {
debug_assert_eq!(write_iv.len(), 4);
debug_assert_eq!(explicit.len(), 8);
// The GCM nonce is constructed from a 32-bit 'salt' derived
// from the master-secret, and a 64-bit explicit part,
// with no specified construction. Thanks for that.
//
// We use the same construction as TLS1.3/ChaCha20Poly1305:
// a starting point extracted from the key block, xored with
// the sequence number.
let mut iv = [0; NONCE_LEN];
iv[..4].copy_from_slice(write_iv);
iv[4..].copy_from_slice(explicit);
Iv::new(iv)
}
struct Tls12Prf(&'static tls_prf::Algorithm);
impl Prf for Tls12Prf {
fn for_secret(&self, output: &mut [u8], secret: &[u8], label: &[u8], seed: &[u8]) {
// safety:
// - [1] is safe because our caller guarantees `secret` is non-empty; this is
// the only documented error case.
// - [2] is safe in practice because the only failure from `derive()` is due
// to zero `output.len()`; this is outlawed at higher levels
let derived = tls_prf::Secret::new(self.0, secret)
.unwrap() // [1]
.derive(label, seed, output.len())
.unwrap(); // [2]
output.copy_from_slice(derived.as_ref());
}
fn for_key_exchange(
&self,
output: &mut [u8; 48],
kx: Box<dyn ActiveKeyExchange>,
peer_pub_key: &[u8],
label: &[u8],
seed: &[u8],
) -> Result<(), Error> {
self.for_secret(
output,
kx.complete_for_tls_version(peer_pub_key, &TLS12)?
.secret_bytes(),
label,
seed,
);
Ok(())
}
fn fips(&self) -> bool {
super::fips()
}
}
+425
View File
@@ -0,0 +1,425 @@
use alloc::boxed::Box;
use aws_lc_rs::hkdf::KeyType;
use aws_lc_rs::{aead, hkdf, hmac};
use crate::crypto;
use crate::crypto::cipher::{
AeadKey, InboundOpaqueMessage, Iv, MessageDecrypter, MessageEncrypter, Nonce,
Tls13AeadAlgorithm, UnsupportedOperationError, make_tls13_aad,
};
use crate::crypto::tls13::{Hkdf, HkdfExpander, OkmBlock, OutputLengthError};
use crate::enums::{CipherSuite, ContentType, ProtocolVersion};
use crate::error::Error;
use crate::msgs::message::{
InboundPlainMessage, OutboundOpaqueMessage, OutboundPlainMessage, PrefixedPayload,
};
use crate::suites::{CipherSuiteCommon, ConnectionTrafficSecrets, SupportedCipherSuite};
use crate::tls13::Tls13CipherSuite;
/// The TLS1.3 ciphersuite TLS_CHACHA20_POLY1305_SHA256
pub static TLS13_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls13(TLS13_CHACHA20_POLY1305_SHA256_INTERNAL);
pub(crate) static TLS13_CHACHA20_POLY1305_SHA256_INTERNAL: &Tls13CipherSuite = &Tls13CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS13_CHACHA20_POLY1305_SHA256,
hash_provider: &super::hash::SHA256,
// ref: <https://www.ietf.org/archive/id/draft-irtf-cfrg-aead-limits-08.html#section-5.2.1>
confidentiality_limit: u64::MAX,
},
hkdf_provider: &AwsLcHkdf(hkdf::HKDF_SHA256, hmac::HMAC_SHA256),
aead_alg: &Chacha20Poly1305Aead(AeadAlgorithm(&aead::CHACHA20_POLY1305)),
quic: Some(&super::quic::KeyBuilder {
packet_alg: &aead::CHACHA20_POLY1305,
header_alg: &aead::quic::CHACHA20,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-6.6>
confidentiality_limit: u64::MAX,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-6.6>
integrity_limit: 1 << 36,
}),
};
/// The TLS1.3 ciphersuite TLS_AES_256_GCM_SHA384
pub static TLS13_AES_256_GCM_SHA384: SupportedCipherSuite =
SupportedCipherSuite::Tls13(&Tls13CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS13_AES_256_GCM_SHA384,
hash_provider: &super::hash::SHA384,
confidentiality_limit: 1 << 24,
},
hkdf_provider: &AwsLcHkdf(hkdf::HKDF_SHA384, hmac::HMAC_SHA384),
aead_alg: &Aes256GcmAead(AeadAlgorithm(&aead::AES_256_GCM)),
quic: Some(&super::quic::KeyBuilder {
packet_alg: &aead::AES_256_GCM,
header_alg: &aead::quic::AES_256,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-b.1.1>
confidentiality_limit: 1 << 23,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-b.1.2>
integrity_limit: 1 << 52,
}),
});
/// The TLS1.3 ciphersuite TLS_AES_128_GCM_SHA256
pub static TLS13_AES_128_GCM_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls13(TLS13_AES_128_GCM_SHA256_INTERNAL);
pub(crate) static TLS13_AES_128_GCM_SHA256_INTERNAL: &Tls13CipherSuite = &Tls13CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS13_AES_128_GCM_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: 1 << 24,
},
hkdf_provider: &AwsLcHkdf(hkdf::HKDF_SHA256, hmac::HMAC_SHA256),
aead_alg: &Aes128GcmAead(AeadAlgorithm(&aead::AES_128_GCM)),
quic: Some(&super::quic::KeyBuilder {
packet_alg: &aead::AES_128_GCM,
header_alg: &aead::quic::AES_128,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-b.1.1>
confidentiality_limit: 1 << 23,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-b.1.2>
integrity_limit: 1 << 52,
}),
};
struct Chacha20Poly1305Aead(AeadAlgorithm);
impl Tls13AeadAlgorithm for Chacha20Poly1305Aead {
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter> {
// safety: the caller arranges that `key` is `key_len()` in bytes, so this unwrap is safe.
Box::new(AeadMessageEncrypter {
enc_key: aead::LessSafeKey::new(aead::UnboundKey::new(self.0.0, key.as_ref()).unwrap()),
iv,
})
}
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter> {
// safety: the caller arranges that `key` is `key_len()` in bytes, so this unwrap is safe.
Box::new(AeadMessageDecrypter {
dec_key: aead::LessSafeKey::new(aead::UnboundKey::new(self.0.0, key.as_ref()).unwrap()),
iv,
})
}
fn key_len(&self) -> usize {
self.0.key_len()
}
fn extract_keys(
&self,
key: AeadKey,
iv: Iv,
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
Ok(ConnectionTrafficSecrets::Chacha20Poly1305 { key, iv })
}
fn fips(&self) -> bool {
false // not FIPS approved
}
}
struct Aes256GcmAead(AeadAlgorithm);
impl Tls13AeadAlgorithm for Aes256GcmAead {
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter> {
self.0.encrypter(key, iv)
}
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter> {
self.0.decrypter(key, iv)
}
fn key_len(&self) -> usize {
self.0.key_len()
}
fn extract_keys(
&self,
key: AeadKey,
iv: Iv,
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
Ok(ConnectionTrafficSecrets::Aes256Gcm { key, iv })
}
fn fips(&self) -> bool {
super::fips()
}
}
struct Aes128GcmAead(AeadAlgorithm);
impl Tls13AeadAlgorithm for Aes128GcmAead {
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter> {
self.0.encrypter(key, iv)
}
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter> {
self.0.decrypter(key, iv)
}
fn key_len(&self) -> usize {
self.0.key_len()
}
fn extract_keys(
&self,
key: AeadKey,
iv: Iv,
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
Ok(ConnectionTrafficSecrets::Aes128Gcm { key, iv })
}
fn fips(&self) -> bool {
super::fips()
}
}
// common encrypter/decrypter/key_len items for above Tls13AeadAlgorithm impls
struct AeadAlgorithm(&'static aead::Algorithm);
impl AeadAlgorithm {
// using aead::TlsRecordSealingKey
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter> {
// safety:
// - the caller arranges that `key` is `key_len()` in bytes, so this unwrap is safe.
// - this function should only be used for `Algorithm::AES_128_GCM` or `Algorithm::AES_256_GCM`
Box::new(GcmMessageEncrypter {
enc_key: aead::TlsRecordSealingKey::new(
self.0,
aead::TlsProtocolId::TLS13,
key.as_ref(),
)
.unwrap(),
iv,
})
}
// using aead::TlsRecordOpeningKey
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter> {
// safety:
// - the caller arranges that `key` is `key_len()` in bytes, so this unwrap is safe.
// - this function should only be used for `Algorithm::AES_128_GCM` or `Algorithm::AES_256_GCM`
Box::new(GcmMessageDecrypter {
dec_key: aead::TlsRecordOpeningKey::new(
self.0,
aead::TlsProtocolId::TLS13,
key.as_ref(),
)
.unwrap(),
iv,
})
}
fn key_len(&self) -> usize {
self.0.key_len()
}
}
struct AeadMessageEncrypter {
enc_key: aead::LessSafeKey,
iv: Iv,
}
struct AeadMessageDecrypter {
dec_key: aead::LessSafeKey,
iv: Iv,
}
impl MessageEncrypter for AeadMessageEncrypter {
fn encrypt(
&mut self,
msg: OutboundPlainMessage<'_>,
seq: u64,
) -> Result<OutboundOpaqueMessage, Error> {
let total_len = self.encrypted_payload_len(msg.payload.len());
let mut payload = PrefixedPayload::with_capacity(total_len);
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, seq).0);
let aad = aead::Aad::from(make_tls13_aad(total_len));
payload.extend_from_chunks(&msg.payload);
payload.extend_from_slice(&msg.typ.to_array());
self.enc_key
.seal_in_place_append_tag(nonce, aad, &mut payload)
.map_err(|_| Error::EncryptError)?;
Ok(OutboundOpaqueMessage::new(
ContentType::ApplicationData,
// Note: all TLS 1.3 application data records use TLSv1_2 (0x0303) as the legacy record
// protocol version, see https://www.rfc-editor.org/rfc/rfc8446#section-5.1
ProtocolVersion::TLSv1_2,
payload,
))
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len + 1 + self.enc_key.algorithm().tag_len()
}
}
impl MessageDecrypter for AeadMessageDecrypter {
fn decrypt<'a>(
&mut self,
mut msg: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, Error> {
let payload = &mut msg.payload;
if payload.len() < self.dec_key.algorithm().tag_len() {
return Err(Error::DecryptError);
}
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, seq).0);
let aad = aead::Aad::from(make_tls13_aad(payload.len()));
let plain_len = self
.dec_key
.open_in_place(nonce, aad, payload)
.map_err(|_| Error::DecryptError)?
.len();
payload.truncate(plain_len);
msg.into_tls13_unpadded_message()
}
}
struct GcmMessageEncrypter {
enc_key: aead::TlsRecordSealingKey,
iv: Iv,
}
impl MessageEncrypter for GcmMessageEncrypter {
fn encrypt(
&mut self,
msg: OutboundPlainMessage<'_>,
seq: u64,
) -> Result<OutboundOpaqueMessage, Error> {
let total_len = self.encrypted_payload_len(msg.payload.len());
let mut payload = PrefixedPayload::with_capacity(total_len);
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, seq).0);
let aad = aead::Aad::from(make_tls13_aad(total_len));
payload.extend_from_chunks(&msg.payload);
payload.extend_from_slice(&msg.typ.to_array());
self.enc_key
.seal_in_place_append_tag(nonce, aad, &mut payload)
.map_err(|_| Error::EncryptError)?;
Ok(OutboundOpaqueMessage::new(
ContentType::ApplicationData,
ProtocolVersion::TLSv1_2,
payload,
))
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len + 1 + self.enc_key.algorithm().tag_len()
}
}
struct GcmMessageDecrypter {
dec_key: aead::TlsRecordOpeningKey,
iv: Iv,
}
impl MessageDecrypter for GcmMessageDecrypter {
fn decrypt<'a>(
&mut self,
mut msg: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, Error> {
let payload = &mut msg.payload;
if payload.len() < self.dec_key.algorithm().tag_len() {
return Err(Error::DecryptError);
}
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, seq).0);
let aad = aead::Aad::from(make_tls13_aad(payload.len()));
let plain_len = self
.dec_key
.open_in_place(nonce, aad, payload)
.map_err(|_| Error::DecryptError)?
.len();
payload.truncate(plain_len);
msg.into_tls13_unpadded_message()
}
}
struct AwsLcHkdf(hkdf::Algorithm, hmac::Algorithm);
impl Hkdf for AwsLcHkdf {
fn extract_from_zero_ikm(&self, salt: Option<&[u8]>) -> Box<dyn HkdfExpander> {
let zeroes = [0u8; OkmBlock::MAX_LEN];
let salt = match salt {
Some(salt) => salt,
None => &zeroes[..self.0.len()],
};
Box::new(AwsLcHkdfExpander {
alg: self.0,
prk: hkdf::Salt::new(self.0, salt).extract(&zeroes[..self.0.len()]),
})
}
fn extract_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Box<dyn HkdfExpander> {
let zeroes = [0u8; OkmBlock::MAX_LEN];
let salt = match salt {
Some(salt) => salt,
None => &zeroes[..self.0.len()],
};
Box::new(AwsLcHkdfExpander {
alg: self.0,
prk: hkdf::Salt::new(self.0, salt).extract(secret),
})
}
fn expander_for_okm(&self, okm: &OkmBlock) -> Box<dyn HkdfExpander> {
Box::new(AwsLcHkdfExpander {
alg: self.0,
prk: hkdf::Prk::new_less_safe(self.0, okm.as_ref()),
})
}
fn hmac_sign(&self, key: &OkmBlock, message: &[u8]) -> crypto::hmac::Tag {
crypto::hmac::Tag::new(hmac::sign(&hmac::Key::new(self.1, key.as_ref()), message).as_ref())
}
fn fips(&self) -> bool {
super::fips()
}
}
struct AwsLcHkdfExpander {
alg: hkdf::Algorithm,
prk: hkdf::Prk,
}
impl HkdfExpander for AwsLcHkdfExpander {
fn expand_slice(&self, info: &[&[u8]], output: &mut [u8]) -> Result<(), OutputLengthError> {
self.prk
.expand(info, Len(output.len()))
.and_then(|okm| okm.fill(output))
.map_err(|_| OutputLengthError)
}
fn expand_block(&self, info: &[&[u8]]) -> OkmBlock {
let mut buf = [0u8; OkmBlock::MAX_LEN];
let output = &mut buf[..self.hash_len()];
self.prk
.expand(info, Len(output.len()))
.and_then(|okm| okm.fill(output))
.unwrap();
OkmBlock::new(output)
}
fn hash_len(&self) -> usize {
self.alg.len()
}
}
struct Len(usize);
impl KeyType for Len {
fn len(&self) -> usize {
self.0
}
}
+364
View File
@@ -0,0 +1,364 @@
use alloc::boxed::Box;
use alloc::string::ToString;
use core::fmt;
use zeroize::Zeroize;
use crate::enums::{ContentType, ProtocolVersion};
use crate::error::Error;
use crate::msgs::codec;
pub use crate::msgs::message::{
BorrowedPayload, InboundOpaqueMessage, InboundPlainMessage, OutboundChunks,
OutboundOpaqueMessage, OutboundPlainMessage, PlainMessage, PrefixedPayload,
};
use crate::suites::ConnectionTrafficSecrets;
/// Factory trait for building `MessageEncrypter` and `MessageDecrypter` for a TLS1.3 cipher suite.
pub trait Tls13AeadAlgorithm: Send + Sync {
/// Build a `MessageEncrypter` for the given key/iv.
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter>;
/// Build a `MessageDecrypter` for the given key/iv.
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter>;
/// The length of key in bytes required by `encrypter()` and `decrypter()`.
fn key_len(&self) -> usize;
/// Convert the key material from `key`/`iv`, into a `ConnectionTrafficSecrets` item.
///
/// May return [`UnsupportedOperationError`] if the AEAD algorithm is not a supported
/// variant of `ConnectionTrafficSecrets`.
fn extract_keys(
&self,
key: AeadKey,
iv: Iv,
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError>;
/// Return `true` if this is backed by a FIPS-approved implementation.
fn fips(&self) -> bool {
false
}
}
/// Factory trait for building `MessageEncrypter` and `MessageDecrypter` for a TLS1.2 cipher suite.
pub trait Tls12AeadAlgorithm: Send + Sync + 'static {
/// Build a `MessageEncrypter` for the given key/iv and extra key block (which can be used for
/// improving explicit nonce size security, if needed).
///
/// The length of `key` is set by [`KeyBlockShape::enc_key_len`].
///
/// The length of `iv` is set by [`KeyBlockShape::fixed_iv_len`].
///
/// The length of `extra` is set by [`KeyBlockShape::explicit_nonce_len`].
fn encrypter(&self, key: AeadKey, iv: &[u8], extra: &[u8]) -> Box<dyn MessageEncrypter>;
/// Build a `MessageDecrypter` for the given key/iv.
///
/// The length of `key` is set by [`KeyBlockShape::enc_key_len`].
///
/// The length of `iv` is set by [`KeyBlockShape::fixed_iv_len`].
fn decrypter(&self, key: AeadKey, iv: &[u8]) -> Box<dyn MessageDecrypter>;
/// Return a `KeyBlockShape` that defines how large the `key_block` is and how it
/// is split up prior to calling `encrypter()`, `decrypter()` and/or `extract_keys()`.
fn key_block_shape(&self) -> KeyBlockShape;
/// Convert the key material from `key`/`iv`, into a `ConnectionTrafficSecrets` item.
///
/// The length of `key` is set by [`KeyBlockShape::enc_key_len`].
///
/// The length of `iv` is set by [`KeyBlockShape::fixed_iv_len`].
///
/// The length of `extra` is set by [`KeyBlockShape::explicit_nonce_len`].
///
/// May return [`UnsupportedOperationError`] if the AEAD algorithm is not a supported
/// variant of `ConnectionTrafficSecrets`.
fn extract_keys(
&self,
key: AeadKey,
iv: &[u8],
explicit: &[u8],
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError>;
/// Return `true` if this is backed by a FIPS-approved implementation.
fn fips(&self) -> bool {
false
}
}
/// An error indicating that the AEAD algorithm does not support the requested operation.
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub struct UnsupportedOperationError;
impl From<UnsupportedOperationError> for Error {
fn from(value: UnsupportedOperationError) -> Self {
Self::General(value.to_string())
}
}
impl fmt::Display for UnsupportedOperationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "operation not supported")
}
}
#[cfg(feature = "std")]
impl std::error::Error for UnsupportedOperationError {}
/// How a TLS1.2 `key_block` is partitioned.
///
/// Note: ciphersuites with non-zero `mac_key_length` are not currently supported.
pub struct KeyBlockShape {
/// How long keys are.
///
/// `enc_key_length` terminology is from the standard ([RFC5246 A.6]).
///
/// [RFC5246 A.6]: <https://www.rfc-editor.org/rfc/rfc5246#appendix-A.6>
pub enc_key_len: usize,
/// How long the fixed part of the 'IV' is.
///
/// `fixed_iv_length` terminology is from the standard ([RFC5246 A.6]).
///
/// This isn't usually an IV, but we continue the
/// terminology misuse to match the standard.
///
/// [RFC5246 A.6]: <https://www.rfc-editor.org/rfc/rfc5246#appendix-A.6>
pub fixed_iv_len: usize,
/// This is a non-standard extension which extends the
/// key block to provide an initial explicit nonce offset,
/// in a deterministic and safe way. GCM needs this,
/// chacha20poly1305 works this way by design.
pub explicit_nonce_len: usize,
}
/// Objects with this trait can decrypt TLS messages.
pub trait MessageDecrypter: Send + Sync {
/// Decrypt the given TLS message `msg`, using the sequence number
/// `seq` which can be used to derive a unique [`Nonce`].
fn decrypt<'a>(
&mut self,
msg: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, Error>;
}
/// Objects with this trait can encrypt TLS messages.
pub trait MessageEncrypter: Send + Sync {
/// Encrypt the given TLS message `msg`, using the sequence number
/// `seq` which can be used to derive a unique [`Nonce`].
fn encrypt(
&mut self,
msg: OutboundPlainMessage<'_>,
seq: u64,
) -> Result<OutboundOpaqueMessage, Error>;
/// Return the length of the ciphertext that results from encrypting plaintext of
/// length `payload_len`
fn encrypted_payload_len(&self, payload_len: usize) -> usize;
}
impl dyn MessageEncrypter {
pub(crate) fn invalid() -> Box<dyn MessageEncrypter> {
Box::new(InvalidMessageEncrypter {})
}
}
impl dyn MessageDecrypter {
pub(crate) fn invalid() -> Box<dyn MessageDecrypter> {
Box::new(InvalidMessageDecrypter {})
}
}
/// A write or read IV.
#[derive(Default)]
pub struct Iv([u8; NONCE_LEN]);
impl Iv {
/// Create a new `Iv` from a byte array, of precisely `NONCE_LEN` bytes.
#[cfg(feature = "tls12")]
pub fn new(value: [u8; NONCE_LEN]) -> Self {
Self(value)
}
/// Create a new `Iv` from a byte slice, of precisely `NONCE_LEN` bytes.
#[cfg(feature = "tls12")]
pub fn copy(value: &[u8]) -> Self {
debug_assert_eq!(value.len(), NONCE_LEN);
let mut iv = Self::new(Default::default());
iv.0.copy_from_slice(value);
iv
}
}
impl From<[u8; NONCE_LEN]> for Iv {
fn from(bytes: [u8; NONCE_LEN]) -> Self {
Self(bytes)
}
}
impl AsRef<[u8]> for Iv {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
/// A nonce. This is unique for all messages on a connection.
pub struct Nonce(pub [u8; NONCE_LEN]);
impl Nonce {
/// Combine an `Iv` and sequence number to produce a unique nonce.
///
/// This is `iv ^ seq` where `seq` is encoded as a 96-bit big-endian integer.
#[inline]
pub fn new(iv: &Iv, seq: u64) -> Self {
let mut seq_bytes = [0u8; NONCE_LEN];
codec::put_u64(seq, &mut seq_bytes[4..]);
Self::new_from_seq(iv, seq_bytes)
}
/// Creates a unique nonce based on the `iv`, the packet number `pn` and multipath `path_id`.
///
/// The nonce is computed as the XOR between the `iv` and the 96-bit big-ending integer formed
/// by concatenating `path_id` and `pn`.
pub fn for_path(path_id: u32, iv: &Iv, pn: u64) -> Self {
let mut seq_bytes = [0u8; NONCE_LEN];
seq_bytes[0..4].copy_from_slice(&path_id.to_be_bytes());
codec::put_u64(pn, &mut seq_bytes[4..]);
Self::new_from_seq(iv, seq_bytes)
}
/// Creates a unique nonce based on the `iv` and sequence number `seq`.
#[inline]
fn new_from_seq(iv: &Iv, mut seq: [u8; NONCE_LEN]) -> Self {
seq.iter_mut()
.zip(iv.0.iter())
.for_each(|(s, iv)| {
*s ^= *iv;
});
Self(seq)
}
}
/// Size of TLS nonces (incorrectly termed "IV" in standard) for all supported ciphersuites
/// (AES-GCM, Chacha20Poly1305)
pub const NONCE_LEN: usize = 12;
/// Returns a TLS1.3 `additional_data` encoding.
///
/// See RFC8446 s5.2 for the `additional_data` definition.
#[inline]
pub fn make_tls13_aad(payload_len: usize) -> [u8; 5] {
let version = ProtocolVersion::TLSv1_2.to_array();
[
ContentType::ApplicationData.into(),
// Note: this is `legacy_record_version`, i.e. TLS1.2 even for TLS1.3.
version[0],
version[1],
(payload_len >> 8) as u8,
(payload_len & 0xff) as u8,
]
}
/// Returns a TLS1.2 `additional_data` encoding.
///
/// See RFC5246 s6.2.3.3 for the `additional_data` definition.
#[inline]
pub fn make_tls12_aad(
seq: u64,
typ: ContentType,
vers: ProtocolVersion,
len: usize,
) -> [u8; TLS12_AAD_SIZE] {
let mut out = [0; TLS12_AAD_SIZE];
codec::put_u64(seq, &mut out[0..]);
out[8] = typ.into();
codec::put_u16(vers.into(), &mut out[9..]);
codec::put_u16(len as u16, &mut out[11..]);
out
}
const TLS12_AAD_SIZE: usize = 8 + 1 + 2 + 2;
/// A key for an AEAD algorithm.
///
/// This is a value type for a byte string up to `AeadKey::MAX_LEN` bytes in length.
pub struct AeadKey {
buf: [u8; Self::MAX_LEN],
used: usize,
}
impl AeadKey {
#[cfg(feature = "tls12")]
pub(crate) fn new(buf: &[u8]) -> Self {
debug_assert!(buf.len() <= Self::MAX_LEN);
let mut key = Self::from([0u8; Self::MAX_LEN]);
key.buf[..buf.len()].copy_from_slice(buf);
key.used = buf.len();
key
}
pub(crate) fn with_length(self, len: usize) -> Self {
assert!(len <= self.used);
Self {
buf: self.buf,
used: len,
}
}
/// Largest possible AEAD key in the ciphersuites we support.
pub(crate) const MAX_LEN: usize = 32;
}
impl Drop for AeadKey {
fn drop(&mut self) {
self.buf.zeroize();
}
}
impl AsRef<[u8]> for AeadKey {
fn as_ref(&self) -> &[u8] {
&self.buf[..self.used]
}
}
impl From<[u8; Self::MAX_LEN]> for AeadKey {
fn from(bytes: [u8; Self::MAX_LEN]) -> Self {
Self {
buf: bytes,
used: Self::MAX_LEN,
}
}
}
/// A `MessageEncrypter` which doesn't work.
struct InvalidMessageEncrypter {}
impl MessageEncrypter for InvalidMessageEncrypter {
fn encrypt(
&mut self,
_m: OutboundPlainMessage<'_>,
_seq: u64,
) -> Result<OutboundOpaqueMessage, Error> {
Err(Error::EncryptError)
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len
}
}
/// A `MessageDecrypter` which doesn't work.
struct InvalidMessageDecrypter {}
impl MessageDecrypter for InvalidMessageDecrypter {
fn decrypt<'a>(
&mut self,
_m: InboundOpaqueMessage<'a>,
_seq: u64,
) -> Result<InboundPlainMessage<'a>, Error> {
Err(Error::DecryptError)
}
}
+81
View File
@@ -0,0 +1,81 @@
use alloc::boxed::Box;
pub use crate::msgs::enums::HashAlgorithm;
/// Describes a single cryptographic hash function.
///
/// This interface can do both one-shot and incremental hashing, using
/// [`Hash::hash()`] and [`Hash::start()`] respectively.
pub trait Hash: Send + Sync {
/// Start an incremental hash computation.
fn start(&self) -> Box<dyn Context>;
/// Return the output of this hash function with input `data`.
fn hash(&self, data: &[u8]) -> Output;
/// The length in bytes of this hash function's output.
fn output_len(&self) -> usize;
/// Which hash function this is, eg, `HashAlgorithm::SHA256`.
fn algorithm(&self) -> HashAlgorithm;
/// Return `true` if this is backed by a FIPS-approved implementation.
fn fips(&self) -> bool {
false
}
}
/// A hash output, stored as a value.
pub struct Output {
buf: [u8; Self::MAX_LEN],
used: usize,
}
impl Output {
/// Build a `hash::Output` from a slice of no more than `Output::MAX_LEN` bytes.
pub fn new(bytes: &[u8]) -> Self {
let mut output = Self {
buf: [0u8; Self::MAX_LEN],
used: bytes.len(),
};
debug_assert!(bytes.len() <= Self::MAX_LEN);
output.buf[..bytes.len()].copy_from_slice(bytes);
output
}
/// Maximum supported hash output size: supports up to SHA512.
pub const MAX_LEN: usize = 64;
}
impl AsRef<[u8]> for Output {
fn as_ref(&self) -> &[u8] {
&self.buf[..self.used]
}
}
/// How to incrementally compute a hash.
pub trait Context: Send + Sync {
/// Finish the computation, returning the resulting output.
///
/// The computation remains valid, and more data can be added later with
/// [`Context::update()`].
///
/// Compare with [`Context::finish()`] which consumes the computation
/// and prevents any further data being added. This can be more efficient
/// because it avoids a hash context copy to apply Merkle-Damgård padding
/// (if required).
fn fork_finish(&self) -> Output;
/// Fork the computation, producing another context that has the
/// same prefix as this one.
fn fork(&self) -> Box<dyn Context>;
/// Terminate and finish the computation, returning the resulting output.
///
/// Further data cannot be added after this, because the context is consumed.
/// Compare [`Context::fork_finish()`].
fn finish(self: Box<Self>) -> Output;
/// Add `data` to computation.
fn update(&mut self, data: &[u8]);
}
+73
View File
@@ -0,0 +1,73 @@
use alloc::boxed::Box;
use zeroize::Zeroize;
/// A concrete HMAC implementation, for a single cryptographic hash function.
///
/// You should have one object that implements this trait for HMAC-SHA256, another
/// for HMAC-SHA384, etc.
pub trait Hmac: Send + Sync {
/// Prepare to use `key` as a HMAC key.
fn with_key(&self, key: &[u8]) -> Box<dyn Key>;
/// Give the length of the underlying hash function. In RFC2104 terminology this is `L`.
fn hash_output_len(&self) -> usize;
/// Return `true` if this is backed by a FIPS-approved implementation.
fn fips(&self) -> bool {
false
}
}
/// A HMAC tag, stored as a value.
#[derive(Clone)]
pub struct Tag {
buf: [u8; Self::MAX_LEN],
used: usize,
}
impl Tag {
/// Build a tag by copying a byte slice.
///
/// The slice can be up to [`Tag::MAX_LEN`] bytes in length.
pub fn new(bytes: &[u8]) -> Self {
let mut tag = Self {
buf: [0u8; Self::MAX_LEN],
used: bytes.len(),
};
tag.buf[..bytes.len()].copy_from_slice(bytes);
tag
}
/// Maximum supported HMAC tag size: supports up to SHA512.
pub const MAX_LEN: usize = 64;
}
impl Drop for Tag {
fn drop(&mut self) {
self.buf.zeroize();
}
}
impl AsRef<[u8]> for Tag {
fn as_ref(&self) -> &[u8] {
&self.buf[..self.used]
}
}
/// A HMAC key that is ready for use.
///
/// The algorithm used is implicit in the `Hmac` object that produced the key.
pub trait Key: Send + Sync {
/// Calculates a tag over `data` -- a slice of byte slices.
fn sign(&self, data: &[&[u8]]) -> Tag {
self.sign_concat(&[], data, &[])
}
/// Calculates a tag over the concatenation of `first`, the items in `middle`, and `last`.
fn sign_concat(&self, first: &[u8], middle: &[&[u8]], last: &[u8]) -> Tag;
/// Returns the length of the tag returned by a computation using
/// this key.
fn tag_len(&self) -> usize;
}
+145
View File
@@ -0,0 +1,145 @@
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt::Debug;
use zeroize::Zeroize;
use crate::Error;
use crate::msgs::enums::HpkeKem;
use crate::msgs::handshake::HpkeSymmetricCipherSuite;
/// An HPKE suite, specifying a key encapsulation mechanism and a symmetric cipher suite.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HpkeSuite {
/// The choice of HPKE key encapsulation mechanism.
pub kem: HpkeKem,
/// The choice of HPKE symmetric cipher suite.
///
/// This combines a choice of authenticated encryption with additional data (AEAD) algorithm
/// and a key derivation function (KDF).
pub sym: HpkeSymmetricCipherSuite,
}
/// An HPKE instance that can be used for base-mode single-shot encryption and decryption.
pub trait Hpke: Debug + Send + Sync {
/// Seal the provided `plaintext` to the recipient public key `pub_key` with application supplied
/// `info`, and additional data `aad`.
///
/// Returns ciphertext that can be used with [Self::open] by the recipient to recover plaintext
/// using the same `info` and `aad` and the private key corresponding to `pub_key`. RFC 9180
/// refers to `pub_key` as `pkR`.
fn seal(
&self,
info: &[u8],
aad: &[u8],
plaintext: &[u8],
pub_key: &HpkePublicKey,
) -> Result<(EncapsulatedSecret, Vec<u8>), Error>;
/// Set up a sealer context for the receiver public key `pub_key` with application supplied `info`.
///
/// Returns both an encapsulated ciphertext and a sealer context that can be used to seal
/// messages to the recipient. RFC 9180 refers to `pub_key` as `pkR`.
fn setup_sealer(
&self,
info: &[u8],
pub_key: &HpkePublicKey,
) -> Result<(EncapsulatedSecret, Box<dyn HpkeSealer + 'static>), Error>;
/// Open the provided `ciphertext` using the encapsulated secret `enc`, with application
/// supplied `info`, and additional data `aad`.
///
/// Returns plaintext if the `info` and `aad` match those used with [Self::seal], and
/// decryption with `secret_key` succeeds. RFC 9180 refers to `secret_key` as `skR`.
fn open(
&self,
enc: &EncapsulatedSecret,
info: &[u8],
aad: &[u8],
ciphertext: &[u8],
secret_key: &HpkePrivateKey,
) -> Result<Vec<u8>, Error>;
/// Set up an opener context for the secret key `secret_key` with application supplied `info`.
///
/// Returns an opener context that can be used to open sealed messages encrypted to the
/// public key corresponding to `secret_key`. RFC 9180 refers to `secret_key` as `skR`.
fn setup_opener(
&self,
enc: &EncapsulatedSecret,
info: &[u8],
secret_key: &HpkePrivateKey,
) -> Result<Box<dyn HpkeOpener + 'static>, Error>;
/// Generate a new public key and private key pair compatible with this HPKE instance.
///
/// Key pairs should be encoded as raw big endian fixed length integers sized based
/// on the suite's DH KEM algorithm.
fn generate_key_pair(&self) -> Result<(HpkePublicKey, HpkePrivateKey), Error>;
/// Return whether the HPKE instance is FIPS compatible.
fn fips(&self) -> bool {
false
}
/// Return the [HpkeSuite] that this HPKE instance supports.
fn suite(&self) -> HpkeSuite;
}
/// An HPKE sealer context.
///
/// This is a stateful object that can be used to seal messages for receipt by
/// a receiver.
pub trait HpkeSealer: Debug + Send + Sync + 'static {
/// Seal the provided `plaintext` with additional data `aad`, returning
/// ciphertext.
fn seal(&mut self, aad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, Error>;
}
/// An HPKE opener context.
///
/// This is a stateful object that can be used to open sealed messages sealed
/// by a sender.
pub trait HpkeOpener: Debug + Send + Sync + 'static {
/// Open the provided `ciphertext` with additional data `aad`, returning plaintext.
fn open(&mut self, aad: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, Error>;
}
/// An HPKE public key.
#[derive(Clone, Debug)]
pub struct HpkePublicKey(pub Vec<u8>);
/// An HPKE private key.
pub struct HpkePrivateKey(Vec<u8>);
impl HpkePrivateKey {
/// Return the private key bytes.
pub fn secret_bytes(&self) -> &[u8] {
self.0.as_slice()
}
}
impl From<Vec<u8>> for HpkePrivateKey {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
impl Drop for HpkePrivateKey {
fn drop(&mut self) {
self.0.zeroize();
}
}
/// An HPKE key pair, made of a matching public and private key.
pub struct HpkeKeyPair {
/// A HPKE public key.
pub public_key: HpkePublicKey,
/// A HPKE private key.
pub private_key: HpkePrivateKey,
}
/// An encapsulated secret returned from setting up a sender or receiver context.
#[derive(Debug)]
pub struct EncapsulatedSecret(pub Vec<u8>);
+760
View File
@@ -0,0 +1,760 @@
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt::Debug;
use pki_types::PrivateKeyDer;
use zeroize::Zeroize;
#[cfg(all(doc, feature = "tls12"))]
use crate::Tls12CipherSuite;
use crate::msgs::ffdhe_groups::FfdheGroup;
use crate::sign::SigningKey;
use crate::sync::Arc;
pub use crate::webpki::{
WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature,
verify_tls13_signature_with_raw_key,
};
#[cfg(doc)]
use crate::{
ClientConfig, ConfigBuilder, ServerConfig, SupportedCipherSuite, Tls13CipherSuite, client,
crypto, server, sign,
};
use crate::{Error, NamedGroup, ProtocolVersion, SupportedProtocolVersion, suites};
/// *ring* based CryptoProvider.
#[cfg(feature = "ring")]
pub mod ring;
/// aws-lc-rs-based CryptoProvider.
#[cfg(feature = "aws_lc_rs")]
pub mod aws_lc_rs;
/// TLS message encryption/decryption interfaces.
pub mod cipher;
/// Hashing interfaces.
pub mod hash;
/// HMAC interfaces.
pub mod hmac;
#[cfg(feature = "tls12")]
/// Cryptography specific to TLS1.2.
pub mod tls12;
/// Cryptography specific to TLS1.3.
pub mod tls13;
/// Hybrid public key encryption (RFC 9180).
pub mod hpke;
// Message signing interfaces. Re-exported under rustls::sign. Kept crate-internal here to
// avoid having two import paths to the same types.
pub(crate) mod signer;
pub use crate::msgs::handshake::KeyExchangeAlgorithm;
pub use crate::rand::GetRandomFailed;
pub use crate::suites::CipherSuiteCommon;
/// Controls core cryptography used by rustls.
///
/// This crate comes with two built-in options, provided as
/// `CryptoProvider` structures:
///
/// - [`crypto::aws_lc_rs::default_provider`]: (behind the `aws_lc_rs` crate feature,
/// which is enabled by default). This provider uses the [aws-lc-rs](https://github.com/aws/aws-lc-rs)
/// crate. The `fips` crate feature makes this option use FIPS140-3-approved cryptography.
/// - [`crypto::ring::default_provider`]: (behind the `ring` crate feature, which
/// is optional). This provider uses the [*ring*](https://github.com/briansmith/ring)
/// crate.
///
/// This structure provides defaults. Everything in it can be overridden at
/// runtime by replacing field values as needed.
///
/// # Using the per-process default `CryptoProvider`
///
/// There is the concept of an implicit default provider, configured at run-time once in
/// a given process.
///
/// It is used for functions like [`ClientConfig::builder()`] and [`ServerConfig::builder()`].
///
/// The intention is that an application can specify the [`CryptoProvider`] they wish to use
/// once, and have that apply to the variety of places where their application does TLS
/// (which may be wrapped inside other libraries).
/// They should do this by calling [`CryptoProvider::install_default()`] early on.
///
/// To achieve this goal:
///
/// - _libraries_ should use [`ClientConfig::builder()`]/[`ServerConfig::builder()`]
/// or otherwise rely on the [`CryptoProvider::get_default()`] provider.
/// - _applications_ should call [`CryptoProvider::install_default()`] early
/// in their `fn main()`. If _applications_ uses a custom provider based on the one built-in,
/// they can activate the `custom-provider` feature to ensure its usage.
///
/// # Using a specific `CryptoProvider`
///
/// Supply the provider when constructing your [`ClientConfig`] or [`ServerConfig`]:
///
/// - [`ClientConfig::builder_with_provider()`]
/// - [`ServerConfig::builder_with_provider()`]
///
/// When creating and configuring a webpki-backed client or server certificate verifier, a choice of
/// provider is also needed to start the configuration process:
///
/// - [`client::WebPkiServerVerifier::builder_with_provider()`]
/// - [`server::WebPkiClientVerifier::builder_with_provider()`]
///
/// If you install a custom provider and want to avoid any accidental use of a built-in provider, the feature
/// `custom-provider` can be activated to ensure your custom provider is used everywhere
/// and not a built-in one. This will disable any implicit use of a built-in provider.
///
/// # Making a custom `CryptoProvider`
///
/// Your goal will be to populate an instance of this `CryptoProvider` struct.
///
/// ## Which elements are required?
///
/// There is no requirement that the individual elements ([`SupportedCipherSuite`], [`SupportedKxGroup`],
/// [`SigningKey`], etc.) come from the same crate. It is allowed and expected that uninteresting
/// elements would be delegated back to one of the default providers (statically) or a parent
/// provider (dynamically).
///
/// For example, if we want to make a provider that just overrides key loading in the config builder
/// API (with [`ConfigBuilder::with_single_cert`], etc.), it might look like this:
///
/// ```
/// # #[cfg(feature = "aws_lc_rs")] {
/// # use std::sync::Arc;
/// # mod fictious_hsm_api { pub fn load_private_key(key_der: pki_types::PrivateKeyDer<'static>) -> ! { unreachable!(); } }
/// use rustls::crypto::aws_lc_rs;
///
/// pub fn provider() -> rustls::crypto::CryptoProvider {
/// rustls::crypto::CryptoProvider{
/// key_provider: &HsmKeyLoader,
/// ..aws_lc_rs::default_provider()
/// }
/// }
///
/// #[derive(Debug)]
/// struct HsmKeyLoader;
///
/// impl rustls::crypto::KeyProvider for HsmKeyLoader {
/// fn load_private_key(&self, key_der: pki_types::PrivateKeyDer<'static>) -> Result<Arc<dyn rustls::sign::SigningKey>, rustls::Error> {
/// fictious_hsm_api::load_private_key(key_der)
/// }
/// }
/// # }
/// ```
///
/// ## References to the individual elements
///
/// The elements are documented separately:
///
/// - **Random** - see [`crypto::SecureRandom::fill()`].
/// - **Cipher suites** - see [`SupportedCipherSuite`], [`Tls12CipherSuite`], and
/// [`Tls13CipherSuite`].
/// - **Key exchange groups** - see [`crypto::SupportedKxGroup`].
/// - **Signature verification algorithms** - see [`crypto::WebPkiSupportedAlgorithms`].
/// - **Authentication key loading** - see [`crypto::KeyProvider::load_private_key()`] and
/// [`sign::SigningKey`].
///
/// # Example code
///
/// See custom [`provider-example/`] for a full client and server example that uses
/// cryptography from the [`RustCrypto`] and [`dalek-cryptography`] projects.
///
/// ```shell
/// $ cargo run --example client | head -3
/// Current ciphersuite: TLS13_CHACHA20_POLY1305_SHA256
/// HTTP/1.1 200 OK
/// Content-Type: text/html; charset=utf-8
/// Content-Length: 19899
/// ```
///
/// [`provider-example/`]: https://github.com/rustls/rustls/tree/main/provider-example/
/// [`RustCrypto`]: https://github.com/RustCrypto
/// [`dalek-cryptography`]: https://github.com/dalek-cryptography
///
/// # FIPS-approved cryptography
/// The `fips` crate feature enables use of the `aws-lc-rs` crate in FIPS mode.
///
/// You can verify the configuration at runtime by checking
/// [`ServerConfig::fips()`]/[`ClientConfig::fips()`] return `true`.
#[derive(Debug, Clone)]
pub struct CryptoProvider {
/// List of supported ciphersuites, in preference order -- the first element
/// is the highest priority.
///
/// The `SupportedCipherSuite` type carries both configuration and implementation.
///
/// A valid `CryptoProvider` must ensure that all cipher suites are accompanied by at least
/// one matching key exchange group in [`CryptoProvider::kx_groups`].
pub cipher_suites: Vec<suites::SupportedCipherSuite>,
/// List of supported key exchange groups, in preference order -- the
/// first element is the highest priority.
///
/// The first element in this list is the _default key share algorithm_,
/// and in TLS1.3 a key share for it is sent in the client hello.
///
/// The `SupportedKxGroup` type carries both configuration and implementation.
pub kx_groups: Vec<&'static dyn SupportedKxGroup>,
/// List of signature verification algorithms for use with webpki.
///
/// These are used for both certificate chain verification and handshake signature verification.
///
/// This is called by [`ConfigBuilder::with_root_certificates()`],
/// [`server::WebPkiClientVerifier::builder_with_provider()`] and
/// [`client::WebPkiServerVerifier::builder_with_provider()`].
pub signature_verification_algorithms: WebPkiSupportedAlgorithms,
/// Source of cryptographically secure random numbers.
pub secure_random: &'static dyn SecureRandom,
/// Provider for loading private [`SigningKey`]s from [`PrivateKeyDer`].
pub key_provider: &'static dyn KeyProvider,
}
impl CryptoProvider {
/// Sets this `CryptoProvider` as the default for this process.
///
/// This can be called successfully at most once in any process execution.
///
/// Call this early in your process to configure which provider is used for
/// the provider. The configuration should happen before any use of
/// [`ClientConfig::builder()`] or [`ServerConfig::builder()`].
pub fn install_default(self) -> Result<(), Arc<Self>> {
static_default::install_default(self)
}
/// Returns the default `CryptoProvider` for this process.
///
/// This will be `None` if no default has been set yet.
pub fn get_default() -> Option<&'static Arc<Self>> {
static_default::get_default()
}
/// An internal function that:
///
/// - gets the pre-installed default, or
/// - installs one `from_crate_features()`, or else
/// - panics about the need to call [`CryptoProvider::install_default()`]
pub(crate) fn get_default_or_install_from_crate_features() -> &'static Arc<Self> {
if let Some(provider) = Self::get_default() {
return provider;
}
let provider = Self::from_crate_features()
.expect(r###"
Could not automatically determine the process-level CryptoProvider from Rustls crate features.
Call CryptoProvider::install_default() before this point to select a provider manually, or make sure exactly one of the 'aws-lc-rs' and 'ring' features is enabled.
See the documentation of the CryptoProvider type for more information.
"###);
// Ignore the error resulting from us losing a race, and accept the outcome.
let _ = provider.install_default();
Self::get_default().unwrap()
}
/// Returns a provider named unambiguously by rustls crate features.
///
/// This function returns `None` if the crate features are ambiguous (ie, specify two
/// providers), or specify no providers, or the feature `custom-provider` is activated.
/// In all cases the application should explicitly specify the provider to use
/// with [`CryptoProvider::install_default`].
fn from_crate_features() -> Option<Self> {
#[cfg(all(
feature = "ring",
not(feature = "aws_lc_rs"),
not(feature = "custom-provider")
))]
{
return Some(ring::default_provider());
}
#[cfg(all(
feature = "aws_lc_rs",
not(feature = "ring"),
not(feature = "custom-provider")
))]
{
return Some(aws_lc_rs::default_provider());
}
#[allow(unreachable_code)]
None
}
/// Returns `true` if this `CryptoProvider` is operating in FIPS mode.
///
/// This covers only the cryptographic parts of FIPS approval. There are
/// also TLS protocol-level recommendations made by NIST. You should
/// prefer to call [`ClientConfig::fips()`] or [`ServerConfig::fips()`]
/// which take these into account.
pub fn fips(&self) -> bool {
let Self {
cipher_suites,
kx_groups,
signature_verification_algorithms,
secure_random,
key_provider,
} = self;
cipher_suites.iter().all(|cs| cs.fips())
&& kx_groups.iter().all(|kx| kx.fips())
&& signature_verification_algorithms.fips()
&& secure_random.fips()
&& key_provider.fips()
}
}
/// A source of cryptographically secure randomness.
pub trait SecureRandom: Send + Sync + Debug {
/// Fill the given buffer with random bytes.
///
/// The bytes must be sourced from a cryptographically secure random number
/// generator seeded with good quality, secret entropy.
///
/// This is used for all randomness required by rustls, but not necessarily
/// randomness required by the underlying cryptography library. For example:
/// [`SupportedKxGroup::start()`] requires random material to generate
/// an ephemeral key exchange key, but this is not included in the interface with
/// rustls: it is assumed that the cryptography library provides for this itself.
fn fill(&self, buf: &mut [u8]) -> Result<(), GetRandomFailed>;
/// Return `true` if this is backed by a FIPS-approved implementation.
fn fips(&self) -> bool {
false
}
}
/// A mechanism for loading private [`SigningKey`]s from [`PrivateKeyDer`].
///
/// This trait is intended to be used with private key material that is sourced from DER,
/// such as a private-key that may be present on-disk. It is not intended to be used with
/// keys held in hardware security modules (HSMs) or physical tokens. For these use-cases
/// see the Rustls manual section on [customizing private key usage].
///
/// [customizing private key usage]: <https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#customising-private-key-usage>
pub trait KeyProvider: Send + Sync + Debug {
/// Decode and validate a private signing key from `key_der`.
///
/// This is used by [`ConfigBuilder::with_client_auth_cert()`], [`ConfigBuilder::with_single_cert()`],
/// and [`ConfigBuilder::with_single_cert_with_ocsp()`]. The key types and formats supported by this
/// function directly defines the key types and formats supported in those APIs.
///
/// Return an error if the key type encoding is not supported, or if the key fails validation.
fn load_private_key(
&self,
key_der: PrivateKeyDer<'static>,
) -> Result<Arc<dyn SigningKey>, Error>;
/// Return `true` if this is backed by a FIPS-approved implementation.
///
/// If this returns `true`, that must be the case for all possible key types
/// supported by [`KeyProvider::load_private_key()`].
fn fips(&self) -> bool {
false
}
}
/// A supported key exchange group.
///
/// This type carries both configuration and implementation. Specifically,
/// it has a TLS-level name expressed using the [`NamedGroup`] enum, and
/// a function which produces a [`ActiveKeyExchange`].
///
/// Compare with [`NamedGroup`], which carries solely a protocol identifier.
pub trait SupportedKxGroup: Send + Sync + Debug {
/// Start a key exchange.
///
/// This will prepare an ephemeral secret key in the supported group, and a corresponding
/// public key. The key exchange can be completed by calling [ActiveKeyExchange#complete]
/// or discarded.
///
/// # Errors
///
/// This can fail if the random source fails during ephemeral key generation.
fn start(&self) -> Result<Box<dyn ActiveKeyExchange>, Error>;
/// Start and complete a key exchange, in one operation.
///
/// The default implementation for this calls `start()` and then calls
/// `complete()` on the result. This is suitable for Diffie-Hellman-like
/// key exchange algorithms, where there is not a data dependency between
/// our key share (named "pub_key" in this API) and the peer's (`peer_pub_key`).
///
/// If there is such a data dependency (like key encapsulation mechanisms), this
/// function should be implemented.
fn start_and_complete(&self, peer_pub_key: &[u8]) -> Result<CompletedKeyExchange, Error> {
let kx = self.start()?;
Ok(CompletedKeyExchange {
group: kx.group(),
pub_key: kx.pub_key().to_vec(),
secret: kx.complete(peer_pub_key)?,
})
}
/// FFDHE group the `SupportedKxGroup` operates in.
///
/// Return `None` if this group is not a FFDHE one.
///
/// The default implementation calls `FfdheGroup::from_named_group`: this function
/// is extremely linker-unfriendly so it is recommended all key exchange implementers
/// provide this function.
///
/// `rustls::ffdhe_groups` contains suitable values to return from this,
/// for example [`rustls::ffdhe_groups::FFDHE2048`][crate::ffdhe_groups::FFDHE2048].
fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
#[allow(deprecated)]
FfdheGroup::from_named_group(self.name())
}
/// Named group the SupportedKxGroup operates in.
///
/// If the `NamedGroup` enum does not have a name for the algorithm you are implementing,
/// you can use [`NamedGroup::Unknown`].
fn name(&self) -> NamedGroup;
/// Return `true` if this is backed by a FIPS-approved implementation.
fn fips(&self) -> bool {
false
}
/// Return `true` if this should be offered/selected with the given version.
///
/// The default implementation returns true for all versions.
fn usable_for_version(&self, _version: ProtocolVersion) -> bool {
true
}
}
/// An in-progress key exchange originating from a [`SupportedKxGroup`].
pub trait ActiveKeyExchange: Send + Sync {
/// Completes the key exchange, given the peer's public key.
///
/// This method must return an error if `peer_pub_key` is invalid: either
/// mis-encoded, or an invalid public key (such as, but not limited to, being
/// in a small order subgroup).
///
/// If the key exchange algorithm is FFDHE, the result must be left-padded with zeros,
/// as required by [RFC 8446](https://www.rfc-editor.org/rfc/rfc8446#section-7.4.1)
/// (see [`complete_for_tls_version()`](Self::complete_for_tls_version) for more details).
///
/// The shared secret is returned as a [`SharedSecret`] which can be constructed
/// from a `&[u8]`.
///
/// This consumes and so terminates the [`ActiveKeyExchange`].
fn complete(self: Box<Self>, peer_pub_key: &[u8]) -> Result<SharedSecret, Error>;
/// Completes the key exchange for the given TLS version, given the peer's public key.
///
/// Note that finite-field Diffie–Hellman key exchange has different requirements for the derived
/// shared secret in TLS 1.2 and TLS 1.3 (ECDHE key exchange is the same in TLS 1.2 and TLS 1.3):
///
/// In TLS 1.2, the calculated secret is required to be stripped of leading zeros
/// [(RFC 5246)](https://www.rfc-editor.org/rfc/rfc5246#section-8.1.2).
///
/// In TLS 1.3, the calculated secret is required to be padded with leading zeros to be the same
/// byte-length as the group modulus [(RFC 8446)](https://www.rfc-editor.org/rfc/rfc8446#section-7.4.1).
///
/// The default implementation of this method delegates to [`complete()`](Self::complete) assuming it is
/// implemented for TLS 1.3 (i.e., for FFDHE KX, removes padding as needed). Implementers of this trait
/// are encouraged to just implement [`complete()`](Self::complete) assuming TLS 1.3, and let the default
/// implementation of this method handle TLS 1.2-specific requirements.
///
/// This method must return an error if `peer_pub_key` is invalid: either
/// mis-encoded, or an invalid public key (such as, but not limited to, being
/// in a small order subgroup).
///
/// The shared secret is returned as a [`SharedSecret`] which can be constructed
/// from a `&[u8]`.
///
/// This consumes and so terminates the [`ActiveKeyExchange`].
fn complete_for_tls_version(
self: Box<Self>,
peer_pub_key: &[u8],
tls_version: &SupportedProtocolVersion,
) -> Result<SharedSecret, Error> {
if tls_version.version != ProtocolVersion::TLSv1_2 {
return self.complete(peer_pub_key);
}
let group = self.group();
let mut complete_res = self.complete(peer_pub_key)?;
if group.key_exchange_algorithm() == KeyExchangeAlgorithm::DHE {
complete_res.strip_leading_zeros();
}
Ok(complete_res)
}
/// For hybrid key exchanges, returns the [`NamedGroup`] and key share
/// for the classical half of this key exchange.
///
/// There is no requirement for a hybrid scheme (or any other!) to implement
/// `hybrid_component()`. It only enables an optimization; described below.
///
/// "Hybrid" means a key exchange algorithm which is constructed from two
/// (or more) independent component algorithms. Usually one is post-quantum-secure,
/// and the other is "classical". See
/// <https://datatracker.ietf.org/doc/draft-ietf-tls-hybrid-design/11/>
///
/// # Background
/// Rustls always sends a presumptive key share in its `ClientHello`, using
/// (absent any other information) the first item in [`CryptoProvider::kx_groups`].
/// If the server accepts the client's selection, it can complete the handshake
/// using that key share. If not, the server sends a `HelloRetryRequest` instructing
/// the client to send a different key share instead.
///
/// This request costs an extra round trip, and wastes the key exchange computation
/// (in [`SupportedKxGroup::start()`]) the client already did. We would
/// like to avoid those wastes if possible.
///
/// It is early days for post-quantum-secure hybrid key exchange deployment.
/// This means (commonly) continuing to offer both the hybrid and classical
/// key exchanges, so the handshake can be completed without a `HelloRetryRequest`
/// for servers that support the offered hybrid or classical schemes.
///
/// Implementing `hybrid_component()` enables two optimizations:
///
/// 1. Sending both the hybrid and classical key shares in the `ClientHello`.
///
/// 2. Performing the classical key exchange setup only once. This is important
/// because the classical key exchange setup is relatively expensive.
/// This optimization is permitted and described in
/// <https://www.ietf.org/archive/id/draft-ietf-tls-hybrid-design-11.html#section-3.2>
///
/// Both of these only happen if the classical algorithm appears separately in
/// the client's [`CryptoProvider::kx_groups`], and if the hybrid algorithm appears
/// first in that list.
///
/// # How it works
/// This function is only called by rustls for clients. It is called when
/// constructing the initial `ClientHello`. rustls follows these steps:
///
/// 1. If the return value is `None`, nothing further happens.
/// 2. If the given [`NamedGroup`] does not appear in
/// [`CryptoProvider::kx_groups`], nothing further happens.
/// 3. The given key share is added to the `ClientHello`, after the hybrid entry.
///
/// Then, one of three things may happen when the server replies to the `ClientHello`:
///
/// 1. The server sends a `HelloRetryRequest`. Everything is thrown away and
/// we start again.
/// 2. The server agrees to our hybrid key exchange: rustls calls
/// [`ActiveKeyExchange::complete()`] consuming `self`.
/// 3. The server agrees to our classical key exchange: rustls calls
/// [`ActiveKeyExchange::complete_hybrid_component()`] which
/// discards the hybrid key data, and completes just the classical key exchange.
fn hybrid_component(&self) -> Option<(NamedGroup, &[u8])> {
None
}
/// Completes the classical component of the key exchange, given the peer's public key.
///
/// This is only called if `hybrid_component` returns `Some(_)`.
///
/// This method must return an error if `peer_pub_key` is invalid: either
/// mis-encoded, or an invalid public key (such as, but not limited to, being
/// in a small order subgroup).
///
/// The shared secret is returned as a [`SharedSecret`] which can be constructed
/// from a `&[u8]`.
///
/// See the documentation on [`Self::hybrid_component()`] for explanation.
fn complete_hybrid_component(
self: Box<Self>,
_peer_pub_key: &[u8],
) -> Result<SharedSecret, Error> {
unreachable!("only called if `hybrid_component()` implemented")
}
/// Return the public key being used.
///
/// For ECDHE, the encoding required is defined in
/// [RFC8446 section 4.2.8.2](https://www.rfc-editor.org/rfc/rfc8446#section-4.2.8.2).
///
/// For FFDHE, the encoding required is defined in
/// [RFC8446 section 4.2.8.1](https://www.rfc-editor.org/rfc/rfc8446#section-4.2.8.1).
fn pub_key(&self) -> &[u8];
/// FFDHE group the `ActiveKeyExchange` is operating in.
///
/// Return `None` if this group is not a FFDHE one.
///
/// The default implementation calls `FfdheGroup::from_named_group`: this function
/// is extremely linker-unfriendly so it is recommended all key exchange implementers
/// provide this function.
///
/// `rustls::ffdhe_groups` contains suitable values to return from this,
/// for example [`rustls::ffdhe_groups::FFDHE2048`][crate::ffdhe_groups::FFDHE2048].
fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
#[allow(deprecated)]
FfdheGroup::from_named_group(self.group())
}
/// Return the group being used.
fn group(&self) -> NamedGroup;
}
/// The result from [`SupportedKxGroup::start_and_complete()`].
pub struct CompletedKeyExchange {
/// Which group was used.
pub group: NamedGroup,
/// Our key share (sometimes a public key).
pub pub_key: Vec<u8>,
/// The computed shared secret.
pub secret: SharedSecret,
}
/// The result from [`ActiveKeyExchange::complete`] or [`ActiveKeyExchange::complete_hybrid_component`].
pub struct SharedSecret {
buf: Vec<u8>,
offset: usize,
}
impl SharedSecret {
/// Returns the shared secret as a slice of bytes.
pub fn secret_bytes(&self) -> &[u8] {
&self.buf[self.offset..]
}
/// Removes leading zeros from `secret_bytes()` by adjusting the `offset`.
///
/// This function does not re-allocate.
fn strip_leading_zeros(&mut self) {
let start = self
.secret_bytes()
.iter()
.enumerate()
.find(|(_i, x)| **x != 0)
.map(|(i, _x)| i)
.unwrap_or(self.secret_bytes().len());
self.offset += start;
}
}
impl Drop for SharedSecret {
fn drop(&mut self) {
self.buf.zeroize();
}
}
impl From<&[u8]> for SharedSecret {
fn from(source: &[u8]) -> Self {
Self {
buf: source.to_vec(),
offset: 0,
}
}
}
impl From<Vec<u8>> for SharedSecret {
fn from(buf: Vec<u8>) -> Self {
Self { buf, offset: 0 }
}
}
/// This function returns a [`CryptoProvider`] that uses
/// FIPS140-3-approved cryptography.
///
/// Using this function expresses in your code that you require
/// FIPS-approved cryptography, and will not compile if you make
/// a mistake with cargo features.
///
/// See our [FIPS documentation](crate::manual::_06_fips) for
/// more detail.
///
/// Install this as the process-default provider, like:
///
/// ```rust
/// # #[cfg(feature = "fips")] {
/// rustls::crypto::default_fips_provider().install_default()
/// .expect("default provider already set elsewhere");
/// # }
/// ```
///
/// You can also use this explicitly, like:
///
/// ```rust
/// # #[cfg(feature = "fips")] {
/// # let root_store = rustls::RootCertStore::empty();
/// let config = rustls::ClientConfig::builder_with_provider(
/// rustls::crypto::default_fips_provider().into()
/// )
/// .with_safe_default_protocol_versions()
/// .unwrap()
/// .with_root_certificates(root_store)
/// .with_no_client_auth();
/// # }
/// ```
#[cfg(all(feature = "aws_lc_rs", any(feature = "fips", rustls_docsrs)))]
#[cfg_attr(rustls_docsrs, doc(cfg(feature = "fips")))]
pub fn default_fips_provider() -> CryptoProvider {
aws_lc_rs::default_provider()
}
mod static_default {
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
#[cfg(feature = "std")]
use std::sync::OnceLock;
#[cfg(not(feature = "std"))]
use once_cell::race::OnceBox;
use super::CryptoProvider;
use crate::sync::Arc;
#[cfg(feature = "std")]
pub(crate) fn install_default(
default_provider: CryptoProvider,
) -> Result<(), Arc<CryptoProvider>> {
PROCESS_DEFAULT_PROVIDER.set(Arc::new(default_provider))
}
#[cfg(not(feature = "std"))]
pub(crate) fn install_default(
default_provider: CryptoProvider,
) -> Result<(), Arc<CryptoProvider>> {
PROCESS_DEFAULT_PROVIDER
.set(Box::new(Arc::new(default_provider)))
.map_err(|e| *e)
}
pub(crate) fn get_default() -> Option<&'static Arc<CryptoProvider>> {
PROCESS_DEFAULT_PROVIDER.get()
}
#[cfg(feature = "std")]
static PROCESS_DEFAULT_PROVIDER: OnceLock<Arc<CryptoProvider>> = OnceLock::new();
#[cfg(not(feature = "std"))]
static PROCESS_DEFAULT_PROVIDER: OnceBox<Arc<CryptoProvider>> = OnceBox::new();
}
#[cfg(test)]
mod tests {
use std::vec;
use super::SharedSecret;
#[test]
fn test_shared_secret_strip_leading_zeros() {
let test_cases = [
(vec![0, 1], vec![1]),
(vec![1], vec![1]),
(vec![1, 0, 2], vec![1, 0, 2]),
(vec![0, 0, 1, 2], vec![1, 2]),
(vec![0, 0, 0], vec![]),
(vec![], vec![]),
];
for (buf, expected) in test_cases {
let mut secret = SharedSecret::from(&buf[..]);
assert_eq!(secret.secret_bytes(), buf);
secret.strip_leading_zeros();
assert_eq!(secret.secret_bytes(), expected);
}
}
}
+60
View File
@@ -0,0 +1,60 @@
#![allow(clippy::duplicate_mod)]
use alloc::boxed::Box;
use super::ring_like::digest;
use crate::crypto;
use crate::msgs::enums::HashAlgorithm;
pub(crate) static SHA256: Hash = Hash(&digest::SHA256, HashAlgorithm::SHA256);
pub(crate) static SHA384: Hash = Hash(&digest::SHA384, HashAlgorithm::SHA384);
pub(crate) struct Hash(&'static digest::Algorithm, HashAlgorithm);
impl crypto::hash::Hash for Hash {
fn start(&self) -> Box<dyn crypto::hash::Context> {
Box::new(Context(digest::Context::new(self.0)))
}
fn hash(&self, bytes: &[u8]) -> crypto::hash::Output {
let mut ctx = digest::Context::new(self.0);
ctx.update(bytes);
convert(ctx.finish())
}
fn output_len(&self) -> usize {
self.0.output_len()
}
fn algorithm(&self) -> HashAlgorithm {
self.1
}
fn fips(&self) -> bool {
super::fips()
}
}
struct Context(digest::Context);
impl crypto::hash::Context for Context {
fn fork_finish(&self) -> crypto::hash::Output {
convert(self.0.clone().finish())
}
fn fork(&self) -> Box<dyn crypto::hash::Context> {
Box::new(Self(self.0.clone()))
}
fn finish(self: Box<Self>) -> crypto::hash::Output {
convert(self.0.finish())
}
fn update(&mut self, data: &[u8]) {
self.0.update(data);
}
}
fn convert(val: digest::Digest) -> crypto::hash::Output {
crypto::hash::Output::new(val.as_ref())
}
+48
View File
@@ -0,0 +1,48 @@
#![allow(clippy::duplicate_mod)]
use alloc::boxed::Box;
use super::ring_like;
use crate::crypto;
pub(crate) static HMAC_SHA256: Hmac = Hmac(&ring_like::hmac::HMAC_SHA256);
pub(crate) static HMAC_SHA384: Hmac = Hmac(&ring_like::hmac::HMAC_SHA384);
#[allow(dead_code)] // Only used for TLS 1.2 prf test, and aws-lc-rs HPKE suites.
pub(crate) static HMAC_SHA512: Hmac = Hmac(&ring_like::hmac::HMAC_SHA512);
pub(crate) struct Hmac(&'static ring_like::hmac::Algorithm);
impl crypto::hmac::Hmac for Hmac {
fn with_key(&self, key: &[u8]) -> Box<dyn crypto::hmac::Key> {
Box::new(Key(ring_like::hmac::Key::new(*self.0, key)))
}
fn hash_output_len(&self) -> usize {
self.0.digest_algorithm().output_len()
}
fn fips(&self) -> bool {
super::fips()
}
}
struct Key(ring_like::hmac::Key);
impl crypto::hmac::Key for Key {
fn sign_concat(&self, first: &[u8], middle: &[&[u8]], last: &[u8]) -> crypto::hmac::Tag {
let mut ctx = ring_like::hmac::Context::with_key(&self.0);
ctx.update(first);
for d in middle {
ctx.update(d);
}
ctx.update(last);
crypto::hmac::Tag::new(ctx.sign().as_ref())
}
fn tag_len(&self) -> usize {
self.0
.algorithm()
.digest_algorithm()
.output_len()
}
}
+188
View File
@@ -0,0 +1,188 @@
#![allow(clippy::duplicate_mod)]
use alloc::boxed::Box;
use core::fmt;
use super::ring_like::agreement;
use super::ring_like::rand::SystemRandom;
use crate::crypto::{ActiveKeyExchange, FfdheGroup, SharedSecret, SupportedKxGroup};
use crate::error::{Error, PeerMisbehaved};
use crate::msgs::enums::NamedGroup;
use crate::rand::GetRandomFailed;
/// A key-exchange group supported by *ring*.
struct KxGroup {
/// The IANA "TLS Supported Groups" name of the group
name: NamedGroup,
/// The corresponding ring agreement::Algorithm
agreement_algorithm: &'static agreement::Algorithm,
/// Whether the algorithm is allowed by FIPS
///
/// `SupportedKxGroup::fips()` is true if and only if the algorithm is allowed,
/// _and_ the implementation is FIPS-validated.
fips_allowed: bool,
/// aws-lc-rs 1.9 and later accepts more formats of public keys than
/// just uncompressed.
///
/// That is not compatible with TLS:
/// - TLS1.3 outlaws other encodings,
/// - TLS1.2 negotiates other encodings (we only offer uncompressed), and
/// defaults to uncompressed if negotiation is not done.
///
/// This function should return `true` if the basic shape of its argument
/// is consistent with an uncompressed point encoding. It does not need
/// to verify that the point is on the curve (if the curve requires that
/// for security); aws-lc-rs/ring must do that.
pub_key_validator: fn(&[u8]) -> bool,
}
impl SupportedKxGroup for KxGroup {
fn start(&self) -> Result<Box<dyn ActiveKeyExchange>, Error> {
let rng = SystemRandom::new();
let priv_key = agreement::EphemeralPrivateKey::generate(self.agreement_algorithm, &rng)
.map_err(|_| GetRandomFailed)?;
let pub_key = priv_key
.compute_public_key()
.map_err(|_| GetRandomFailed)?;
Ok(Box::new(KeyExchange {
name: self.name,
agreement_algorithm: self.agreement_algorithm,
priv_key,
pub_key,
pub_key_validator: self.pub_key_validator,
}))
}
fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
None
}
fn name(&self) -> NamedGroup {
self.name
}
fn fips(&self) -> bool {
self.fips_allowed && super::fips()
}
}
impl fmt::Debug for KxGroup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.name.fmt(f)
}
}
/// Ephemeral ECDH on curve25519 (see RFC7748)
pub static X25519: &dyn SupportedKxGroup = &KxGroup {
name: NamedGroup::X25519,
agreement_algorithm: &agreement::X25519,
// "Curves that are included in SP 800-186 but not included in SP 800-56Arev3 are
// not approved for key agreement. E.g., the ECDH X25519 and X448 key agreement
// schemes (defined in RFC 7748) that use Curve25519 and Curve448, respectively,
// are not compliant to SP 800-56Arev3."
// -- <https://csrc.nist.gov/csrc/media/Projects/cryptographic-module-validation-program/documents/fips%20140-3/FIPS%20140-3%20IG.pdf>
fips_allowed: false,
pub_key_validator: |point: &[u8]| point.len() == 32,
};
/// Ephemeral ECDH on secp256r1 (aka NIST-P256)
pub static SECP256R1: &dyn SupportedKxGroup = &KxGroup {
name: NamedGroup::secp256r1,
agreement_algorithm: &agreement::ECDH_P256,
fips_allowed: true,
pub_key_validator: uncompressed_point,
};
/// Ephemeral ECDH on secp384r1 (aka NIST-P384)
pub static SECP384R1: &dyn SupportedKxGroup = &KxGroup {
name: NamedGroup::secp384r1,
agreement_algorithm: &agreement::ECDH_P384,
fips_allowed: true,
pub_key_validator: uncompressed_point,
};
fn uncompressed_point(point: &[u8]) -> bool {
// See `UncompressedPointRepresentation`, which is a retelling of
// SEC1 section 2.3.3 "Elliptic-Curve-Point-to-Octet-String Conversion"
// <https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.8.2>
matches!(point.first(), Some(0x04))
}
/// An in-progress key exchange. This has the algorithm,
/// our private key, and our public key.
struct KeyExchange {
name: NamedGroup,
agreement_algorithm: &'static agreement::Algorithm,
priv_key: agreement::EphemeralPrivateKey,
pub_key: agreement::PublicKey,
pub_key_validator: fn(&[u8]) -> bool,
}
impl ActiveKeyExchange for KeyExchange {
/// Completes the key exchange, given the peer's public key.
fn complete(self: Box<Self>, peer: &[u8]) -> Result<SharedSecret, Error> {
if !(self.pub_key_validator)(peer) {
return Err(PeerMisbehaved::InvalidKeyShare.into());
}
let peer_key = agreement::UnparsedPublicKey::new(self.agreement_algorithm, peer);
super::ring_shim::agree_ephemeral(self.priv_key, &peer_key)
.map_err(|_| PeerMisbehaved::InvalidKeyShare.into())
}
fn ffdhe_group(&self) -> Option<FfdheGroup<'static>> {
None
}
/// Return the group being used.
fn group(&self) -> NamedGroup {
self.name
}
/// Return the public key being used.
fn pub_key(&self) -> &[u8] {
self.pub_key.as_ref()
}
}
#[cfg(test)]
mod tests {
use std::format;
#[test]
fn kxgroup_fmt_yields_name() {
assert_eq!("X25519", format!("{:?}", super::X25519));
}
}
#[cfg(bench)]
mod benchmarks {
#[bench]
fn bench_x25519(b: &mut test::Bencher) {
bench_any(b, super::X25519);
}
#[bench]
fn bench_ecdh_p256(b: &mut test::Bencher) {
bench_any(b, super::SECP256R1);
}
#[bench]
fn bench_ecdh_p384(b: &mut test::Bencher) {
bench_any(b, super::SECP384R1);
}
fn bench_any(b: &mut test::Bencher, kxg: &dyn super::SupportedKxGroup) {
b.iter(|| {
let akx = kxg.start().unwrap();
let pub_key = akx.pub_key().to_vec();
test::black_box(akx.complete(&pub_key).unwrap());
});
}
}
+204
View File
@@ -0,0 +1,204 @@
use pki_types::PrivateKeyDer;
pub(crate) use ring as ring_like;
use webpki::ring as webpki_algs;
use zeroize::Zeroizing;
use crate::Error;
use crate::crypto::{CryptoProvider, KeyProvider, SecureRandom, SupportedKxGroup};
use crate::enums::SignatureScheme;
use crate::rand::GetRandomFailed;
use crate::sign::SigningKey;
use crate::suites::SupportedCipherSuite;
use crate::sync::Arc;
use crate::webpki::WebPkiSupportedAlgorithms;
/// Using software keys for authentication.
pub mod sign;
pub(crate) mod hash;
#[cfg(any(test, feature = "tls12"))]
pub(crate) mod hmac;
pub(crate) mod kx;
pub(crate) mod quic;
#[cfg(feature = "std")]
pub(crate) mod ticketer;
#[cfg(feature = "tls12")]
pub(crate) mod tls12;
pub(crate) mod tls13;
/// A `CryptoProvider` backed by the [*ring*] crate.
///
/// [*ring*]: https://github.com/briansmith/ring
pub fn default_provider() -> CryptoProvider {
CryptoProvider {
cipher_suites: DEFAULT_CIPHER_SUITES.to_vec(),
kx_groups: DEFAULT_KX_GROUPS.to_vec(),
signature_verification_algorithms: SUPPORTED_SIG_ALGS,
secure_random: &Ring,
key_provider: &Ring,
}
}
/// Default crypto provider.
#[derive(Debug)]
struct Ring;
impl SecureRandom for Ring {
fn fill(&self, buf: &mut [u8]) -> Result<(), GetRandomFailed> {
use ring_like::rand::SecureRandom;
ring_like::rand::SystemRandom::new()
.fill(buf)
.map_err(|_| GetRandomFailed)
}
}
impl KeyProvider for Ring {
fn load_private_key(
&self,
key_der: PrivateKeyDer<'static>,
) -> Result<Arc<dyn SigningKey>, Error> {
sign::any_supported_type(&Zeroizing::new(key_der))
}
}
/// The cipher suite configuration that an application should use by default.
///
/// This will be [`ALL_CIPHER_SUITES`] sans any supported cipher suites that
/// shouldn't be enabled by most applications.
pub static DEFAULT_CIPHER_SUITES: &[SupportedCipherSuite] = ALL_CIPHER_SUITES;
/// A list of all the cipher suites supported by the rustls *ring* provider.
pub static ALL_CIPHER_SUITES: &[SupportedCipherSuite] = &[
// TLS1.3 suites
tls13::TLS13_AES_256_GCM_SHA384,
tls13::TLS13_AES_128_GCM_SHA256,
tls13::TLS13_CHACHA20_POLY1305_SHA256,
// TLS1.2 suites
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
#[cfg(feature = "tls12")]
tls12::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
];
/// All defined cipher suites supported by *ring* appear in this module.
pub mod cipher_suite {
#[cfg(feature = "tls12")]
pub use super::tls12::{
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
};
pub use super::tls13::{
TLS13_AES_128_GCM_SHA256, TLS13_AES_256_GCM_SHA384, TLS13_CHACHA20_POLY1305_SHA256,
};
}
/// A `WebPkiSupportedAlgorithms` value that reflects webpki's capabilities when
/// compiled against *ring*.
static SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms {
all: &[
webpki_algs::ECDSA_P256_SHA256,
webpki_algs::ECDSA_P256_SHA384,
webpki_algs::ECDSA_P384_SHA256,
webpki_algs::ECDSA_P384_SHA384,
webpki_algs::ED25519,
webpki_algs::RSA_PSS_2048_8192_SHA256_LEGACY_KEY,
webpki_algs::RSA_PSS_2048_8192_SHA384_LEGACY_KEY,
webpki_algs::RSA_PSS_2048_8192_SHA512_LEGACY_KEY,
webpki_algs::RSA_PKCS1_2048_8192_SHA256,
webpki_algs::RSA_PKCS1_2048_8192_SHA384,
webpki_algs::RSA_PKCS1_2048_8192_SHA512,
webpki_algs::RSA_PKCS1_2048_8192_SHA256_ABSENT_PARAMS,
webpki_algs::RSA_PKCS1_2048_8192_SHA384_ABSENT_PARAMS,
webpki_algs::RSA_PKCS1_2048_8192_SHA512_ABSENT_PARAMS,
],
mapping: &[
// Note: for TLS1.2 the curve is not fixed by SignatureScheme. For TLS1.3 it is.
(
SignatureScheme::ECDSA_NISTP384_SHA384,
&[
webpki_algs::ECDSA_P384_SHA384,
webpki_algs::ECDSA_P256_SHA384,
],
),
(
SignatureScheme::ECDSA_NISTP256_SHA256,
&[
webpki_algs::ECDSA_P256_SHA256,
webpki_algs::ECDSA_P384_SHA256,
],
),
(SignatureScheme::ED25519, &[webpki_algs::ED25519]),
(
SignatureScheme::RSA_PSS_SHA512,
&[webpki_algs::RSA_PSS_2048_8192_SHA512_LEGACY_KEY],
),
(
SignatureScheme::RSA_PSS_SHA384,
&[webpki_algs::RSA_PSS_2048_8192_SHA384_LEGACY_KEY],
),
(
SignatureScheme::RSA_PSS_SHA256,
&[webpki_algs::RSA_PSS_2048_8192_SHA256_LEGACY_KEY],
),
(
SignatureScheme::RSA_PKCS1_SHA512,
&[webpki_algs::RSA_PKCS1_2048_8192_SHA512],
),
(
SignatureScheme::RSA_PKCS1_SHA384,
&[webpki_algs::RSA_PKCS1_2048_8192_SHA384],
),
(
SignatureScheme::RSA_PKCS1_SHA256,
&[webpki_algs::RSA_PKCS1_2048_8192_SHA256],
),
],
};
/// All defined key exchange groups supported by *ring* appear in this module.
///
/// [`ALL_KX_GROUPS`] is provided as an array of all of these values.
/// [`DEFAULT_KX_GROUPS`] is provided as an array of this provider's defaults.
pub mod kx_group {
pub use super::kx::{SECP256R1, SECP384R1, X25519};
}
/// A list of the default key exchange groups supported by this provider.
pub static DEFAULT_KX_GROUPS: &[&dyn SupportedKxGroup] = ALL_KX_GROUPS;
/// A list of all the key exchange groups supported by this provider.
pub static ALL_KX_GROUPS: &[&dyn SupportedKxGroup] =
&[kx_group::X25519, kx_group::SECP256R1, kx_group::SECP384R1];
#[cfg(feature = "std")]
pub use ticketer::Ticketer;
/// Compatibility shims between ring 0.16.x and 0.17.x API
mod ring_shim {
use super::ring_like;
use crate::crypto::SharedSecret;
pub(super) fn agree_ephemeral(
priv_key: ring_like::agreement::EphemeralPrivateKey,
peer_key: &ring_like::agreement::UnparsedPublicKey<&[u8]>,
) -> Result<SharedSecret, ()> {
ring_like::agreement::agree_ephemeral(priv_key, peer_key, |secret| {
SharedSecret::from(secret)
})
.map_err(|_| ())
}
}
pub(super) fn fips() -> bool {
false
}
+533
View File
@@ -0,0 +1,533 @@
#![allow(clippy::duplicate_mod)]
use alloc::boxed::Box;
use super::ring_like::aead;
use crate::crypto::cipher::{AeadKey, Iv, Nonce};
use crate::error::Error;
use crate::quic;
pub(crate) struct HeaderProtectionKey(aead::quic::HeaderProtectionKey);
impl HeaderProtectionKey {
pub(crate) fn new(key: AeadKey, alg: &'static aead::quic::Algorithm) -> Self {
Self(aead::quic::HeaderProtectionKey::new(alg, key.as_ref()).unwrap())
}
fn xor_in_place(
&self,
sample: &[u8],
first: &mut u8,
packet_number: &mut [u8],
masked: bool,
) -> Result<(), Error> {
// This implements "Header Protection Application" almost verbatim.
// <https://datatracker.ietf.org/doc/html/rfc9001#section-5.4.1>
let mask = self
.0
.new_mask(sample)
.map_err(|_| Error::General("sample of invalid length".into()))?;
// The `unwrap()` will not panic because `new_mask` returns a
// non-empty result.
let (first_mask, pn_mask) = mask.split_first().unwrap();
// It is OK for the `mask` to be longer than `packet_number`,
// but a valid `packet_number` will never be longer than `mask`.
if packet_number.len() > pn_mask.len() {
return Err(Error::General("packet number too long".into()));
}
// Infallible from this point on. Before this point, `first` and
// `packet_number` are unchanged.
const LONG_HEADER_FORM: u8 = 0x80;
let bits = match *first & LONG_HEADER_FORM == LONG_HEADER_FORM {
true => 0x0f, // Long header: 4 bits masked
false => 0x1f, // Short header: 5 bits masked
};
let first_plain = match masked {
// When unmasking, use the packet length bits after unmasking
true => *first ^ (first_mask & bits),
// When masking, use the packet length bits before masking
false => *first,
};
let pn_len = (first_plain & 0x03) as usize + 1;
*first ^= first_mask & bits;
for (dst, m) in packet_number
.iter_mut()
.zip(pn_mask)
.take(pn_len)
{
*dst ^= m;
}
Ok(())
}
}
impl quic::HeaderProtectionKey for HeaderProtectionKey {
fn encrypt_in_place(
&self,
sample: &[u8],
first: &mut u8,
packet_number: &mut [u8],
) -> Result<(), Error> {
self.xor_in_place(sample, first, packet_number, false)
}
fn decrypt_in_place(
&self,
sample: &[u8],
first: &mut u8,
packet_number: &mut [u8],
) -> Result<(), Error> {
self.xor_in_place(sample, first, packet_number, true)
}
#[inline]
fn sample_len(&self) -> usize {
self.0.algorithm().sample_len()
}
}
pub(crate) struct PacketKey {
/// Encrypts or decrypts a packet's payload
key: aead::LessSafeKey,
/// Computes unique nonces for each packet
iv: Iv,
/// Confidentiality limit (see [`quic::PacketKey::confidentiality_limit`])
confidentiality_limit: u64,
/// Integrity limit (see [`quic::PacketKey::integrity_limit`])
integrity_limit: u64,
}
impl PacketKey {
pub(crate) fn new(
key: AeadKey,
iv: Iv,
confidentiality_limit: u64,
integrity_limit: u64,
aead_algorithm: &'static aead::Algorithm,
) -> Self {
Self {
key: aead::LessSafeKey::new(
aead::UnboundKey::new(aead_algorithm, key.as_ref()).unwrap(),
),
iv,
confidentiality_limit,
integrity_limit,
}
}
}
impl quic::PacketKey for PacketKey {
fn encrypt_in_place(
&self,
packet_number: u64,
header: &[u8],
payload: &mut [u8],
) -> Result<quic::Tag, Error> {
let aad = aead::Aad::from(header);
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, packet_number).0);
let tag = self
.key
.seal_in_place_separate_tag(nonce, aad, payload)
.map_err(|_| Error::EncryptError)?;
Ok(quic::Tag::from(tag.as_ref()))
}
fn encrypt_in_place_for_path(
&self,
path_id: u32,
packet_number: u64,
header: &[u8],
payload: &mut [u8],
) -> Result<quic::Tag, Error> {
let aad = aead::Aad::from(header);
let nonce =
aead::Nonce::assume_unique_for_key(Nonce::for_path(path_id, &self.iv, packet_number).0);
let tag = self
.key
.seal_in_place_separate_tag(nonce, aad, payload)
.map_err(|_| Error::EncryptError)?;
Ok(quic::Tag::from(tag.as_ref()))
}
/// Decrypt a QUIC packet
///
/// Takes the packet `header`, which is used as the additional authenticated data, and the
/// `payload`, which includes the authentication tag.
///
/// If the return value is `Ok`, the decrypted payload can be found in `payload`, up to the
/// length found in the return value.
fn decrypt_in_place<'a>(
&self,
packet_number: u64,
header: &[u8],
payload: &'a mut [u8],
) -> Result<&'a [u8], Error> {
let payload_len = payload.len();
let aad = aead::Aad::from(header);
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, packet_number).0);
self.key
.open_in_place(nonce, aad, payload)
.map_err(|_| Error::DecryptError)?;
let plain_len = payload_len - self.key.algorithm().tag_len();
Ok(&payload[..plain_len])
}
fn decrypt_in_place_for_path<'a>(
&self,
path_id: u32,
packet_number: u64,
header: &[u8],
payload: &'a mut [u8],
) -> Result<&'a [u8], Error> {
let payload_len = payload.len();
let aad = aead::Aad::from(header);
let nonce =
aead::Nonce::assume_unique_for_key(Nonce::for_path(path_id, &self.iv, packet_number).0);
self.key
.open_in_place(nonce, aad, payload)
.map_err(|_| Error::DecryptError)?;
let plain_len = payload_len - self.key.algorithm().tag_len();
Ok(&payload[..plain_len])
}
/// Tag length for the underlying AEAD algorithm
#[inline]
fn tag_len(&self) -> usize {
self.key.algorithm().tag_len()
}
/// Confidentiality limit (see [`quic::PacketKey::confidentiality_limit`])
fn confidentiality_limit(&self) -> u64 {
self.confidentiality_limit
}
/// Integrity limit (see [`quic::PacketKey::integrity_limit`])
fn integrity_limit(&self) -> u64 {
self.integrity_limit
}
}
pub(crate) struct KeyBuilder {
pub(crate) packet_alg: &'static aead::Algorithm,
pub(crate) header_alg: &'static aead::quic::Algorithm,
pub(crate) confidentiality_limit: u64,
pub(crate) integrity_limit: u64,
}
impl quic::Algorithm for KeyBuilder {
fn packet_key(&self, key: AeadKey, iv: Iv) -> Box<dyn quic::PacketKey> {
Box::new(PacketKey::new(
key,
iv,
self.confidentiality_limit,
self.integrity_limit,
self.packet_alg,
))
}
fn header_protection_key(&self, key: AeadKey) -> Box<dyn quic::HeaderProtectionKey> {
Box::new(HeaderProtectionKey::new(key, self.header_alg))
}
fn aead_key_len(&self) -> usize {
self.packet_alg.key_len()
}
fn fips(&self) -> bool {
super::fips()
}
}
#[cfg(test)]
#[macro_rules_attribute::apply(test_for_each_provider)]
mod tests {
use std::dbg;
use super::provider::tls13::{
TLS13_AES_128_GCM_SHA256_INTERNAL, TLS13_CHACHA20_POLY1305_SHA256_INTERNAL,
};
use crate::common_state::Side;
use crate::crypto::tls13::OkmBlock;
use crate::quic::*;
fn test_short_packet(version: Version, expected: &[u8]) {
const PN: u64 = 654360564;
const SECRET: &[u8] = &[
0x9a, 0xc3, 0x12, 0xa7, 0xf8, 0x77, 0x46, 0x8e, 0xbe, 0x69, 0x42, 0x27, 0x48, 0xad,
0x00, 0xa1, 0x54, 0x43, 0xf1, 0x82, 0x03, 0xa0, 0x7d, 0x60, 0x60, 0xf6, 0x88, 0xf3,
0x0f, 0x21, 0x63, 0x2b,
];
let secret = OkmBlock::new(SECRET);
let builder = KeyBuilder::new(
&secret,
version,
TLS13_CHACHA20_POLY1305_SHA256_INTERNAL
.quic
.unwrap(),
TLS13_CHACHA20_POLY1305_SHA256_INTERNAL.hkdf_provider,
);
let packet = builder.packet_key();
let hpk = builder.header_protection_key();
const PLAIN: &[u8] = &[0x42, 0x00, 0xbf, 0xf4, 0x01];
let mut buf = PLAIN.to_vec();
let (header, payload) = buf.split_at_mut(4);
let tag = packet
.encrypt_in_place(PN, header, payload)
.unwrap();
buf.extend(tag.as_ref());
let pn_offset = 1;
let (header, sample) = buf.split_at_mut(pn_offset + 4);
let (first, rest) = header.split_at_mut(1);
let sample = &sample[..hpk.sample_len()];
hpk.encrypt_in_place(sample, &mut first[0], dbg!(rest))
.unwrap();
assert_eq!(&buf, expected);
let (header, sample) = buf.split_at_mut(pn_offset + 4);
let (first, rest) = header.split_at_mut(1);
let sample = &sample[..hpk.sample_len()];
hpk.decrypt_in_place(sample, &mut first[0], rest)
.unwrap();
let (header, payload_tag) = buf.split_at_mut(4);
let plain = packet
.decrypt_in_place(PN, header, payload_tag)
.unwrap();
assert_eq!(plain, &PLAIN[4..]);
}
#[test]
fn short_packet_header_protection() {
// https://www.rfc-editor.org/rfc/rfc9001.html#name-chacha20-poly1305-short-hea
test_short_packet(
Version::V1,
&[
0x4c, 0xfe, 0x41, 0x89, 0x65, 0x5e, 0x5c, 0xd5, 0x5c, 0x41, 0xf6, 0x90, 0x80, 0x57,
0x5d, 0x79, 0x99, 0xc2, 0x5a, 0x5b, 0xfb,
],
);
}
#[test]
fn key_update_test_vector() {
fn equal_okm(x: &OkmBlock, y: &OkmBlock) -> bool {
x.as_ref() == y.as_ref()
}
let mut secrets = Secrets::new(
// Constant dummy values for reproducibility
OkmBlock::new(
&[
0xb8, 0x76, 0x77, 0x08, 0xf8, 0x77, 0x23, 0x58, 0xa6, 0xea, 0x9f, 0xc4, 0x3e,
0x4a, 0xdd, 0x2c, 0x96, 0x1b, 0x3f, 0x52, 0x87, 0xa6, 0xd1, 0x46, 0x7e, 0xe0,
0xae, 0xab, 0x33, 0x72, 0x4d, 0xbf,
][..],
),
OkmBlock::new(
&[
0x42, 0xdc, 0x97, 0x21, 0x40, 0xe0, 0xf2, 0xe3, 0x98, 0x45, 0xb7, 0x67, 0x61,
0x34, 0x39, 0xdc, 0x67, 0x58, 0xca, 0x43, 0x25, 0x9b, 0x87, 0x85, 0x06, 0x82,
0x4e, 0xb1, 0xe4, 0x38, 0xd8, 0x55,
][..],
),
TLS13_AES_128_GCM_SHA256_INTERNAL,
TLS13_AES_128_GCM_SHA256_INTERNAL
.quic
.unwrap(),
Side::Client,
Version::V1,
);
secrets.update();
assert!(equal_okm(
&secrets.client,
&OkmBlock::new(
&[
0x42, 0xca, 0xc8, 0xc9, 0x1c, 0xd5, 0xeb, 0x40, 0x68, 0x2e, 0x43, 0x2e, 0xdf,
0x2d, 0x2b, 0xe9, 0xf4, 0x1a, 0x52, 0xca, 0x6b, 0x22, 0xd8, 0xe6, 0xcd, 0xb1,
0xe8, 0xac, 0xa9, 0x6, 0x1f, 0xce
][..]
)
));
assert!(equal_okm(
&secrets.server,
&OkmBlock::new(
&[
0xeb, 0x7f, 0x5e, 0x2a, 0x12, 0x3f, 0x40, 0x7d, 0xb4, 0x99, 0xe3, 0x61, 0xca,
0xe5, 0x90, 0xd4, 0xd9, 0x92, 0xe1, 0x4b, 0x7a, 0xce, 0x3, 0xc2, 0x44, 0xe0,
0x42, 0x21, 0x15, 0xb6, 0xd3, 0x8a
][..]
)
));
}
#[test]
fn short_packet_header_protection_v2() {
// https://www.ietf.org/archive/id/draft-ietf-quic-v2-10.html#name-chacha20-poly1305-short-head
test_short_packet(
Version::V2,
&[
0x55, 0x58, 0xb1, 0xc6, 0x0a, 0xe7, 0xb6, 0xb9, 0x32, 0xbc, 0x27, 0xd7, 0x86, 0xf4,
0xbc, 0x2b, 0xb2, 0x0f, 0x21, 0x62, 0xba,
],
);
}
#[test]
fn initial_test_vector_v2() {
// https://www.ietf.org/archive/id/draft-ietf-quic-v2-10.html#name-sample-packet-protection-2
let icid = [0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08];
let server = Keys::initial(
Version::V2,
TLS13_AES_128_GCM_SHA256_INTERNAL,
TLS13_AES_128_GCM_SHA256_INTERNAL
.quic
.unwrap(),
&icid,
Side::Server,
);
let mut server_payload = [
0x02, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x40, 0x5a, 0x02, 0x00, 0x00, 0x56, 0x03,
0x03, 0xee, 0xfc, 0xe7, 0xf7, 0xb3, 0x7b, 0xa1, 0xd1, 0x63, 0x2e, 0x96, 0x67, 0x78,
0x25, 0xdd, 0xf7, 0x39, 0x88, 0xcf, 0xc7, 0x98, 0x25, 0xdf, 0x56, 0x6d, 0xc5, 0x43,
0x0b, 0x9a, 0x04, 0x5a, 0x12, 0x00, 0x13, 0x01, 0x00, 0x00, 0x2e, 0x00, 0x33, 0x00,
0x24, 0x00, 0x1d, 0x00, 0x20, 0x9d, 0x3c, 0x94, 0x0d, 0x89, 0x69, 0x0b, 0x84, 0xd0,
0x8a, 0x60, 0x99, 0x3c, 0x14, 0x4e, 0xca, 0x68, 0x4d, 0x10, 0x81, 0x28, 0x7c, 0x83,
0x4d, 0x53, 0x11, 0xbc, 0xf3, 0x2b, 0xb9, 0xda, 0x1a, 0x00, 0x2b, 0x00, 0x02, 0x03,
0x04,
];
let mut server_header = [
0xd1, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62,
0xb5, 0x00, 0x40, 0x75, 0x00, 0x01,
];
let tag = server
.local
.packet
.encrypt_in_place(1, &server_header, &mut server_payload)
.unwrap();
let (first, rest) = server_header.split_at_mut(1);
let rest_len = rest.len();
server
.local
.header
.encrypt_in_place(
&server_payload[2..18],
&mut first[0],
&mut rest[rest_len - 2..],
)
.unwrap();
let mut server_packet = server_header.to_vec();
server_packet.extend(server_payload);
server_packet.extend(tag.as_ref());
let expected_server_packet = [
0xdc, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62,
0xb5, 0x00, 0x40, 0x75, 0xd9, 0x2f, 0xaa, 0xf1, 0x6f, 0x05, 0xd8, 0xa4, 0x39, 0x8c,
0x47, 0x08, 0x96, 0x98, 0xba, 0xee, 0xa2, 0x6b, 0x91, 0xeb, 0x76, 0x1d, 0x9b, 0x89,
0x23, 0x7b, 0xbf, 0x87, 0x26, 0x30, 0x17, 0x91, 0x53, 0x58, 0x23, 0x00, 0x35, 0xf7,
0xfd, 0x39, 0x45, 0xd8, 0x89, 0x65, 0xcf, 0x17, 0xf9, 0xaf, 0x6e, 0x16, 0x88, 0x6c,
0x61, 0xbf, 0xc7, 0x03, 0x10, 0x6f, 0xba, 0xf3, 0xcb, 0x4c, 0xfa, 0x52, 0x38, 0x2d,
0xd1, 0x6a, 0x39, 0x3e, 0x42, 0x75, 0x75, 0x07, 0x69, 0x80, 0x75, 0xb2, 0xc9, 0x84,
0xc7, 0x07, 0xf0, 0xa0, 0x81, 0x2d, 0x8c, 0xd5, 0xa6, 0x88, 0x1e, 0xaf, 0x21, 0xce,
0xda, 0x98, 0xf4, 0xbd, 0x23, 0xf6, 0xfe, 0x1a, 0x3e, 0x2c, 0x43, 0xed, 0xd9, 0xce,
0x7c, 0xa8, 0x4b, 0xed, 0x85, 0x21, 0xe2, 0xe1, 0x40,
];
assert_eq!(server_packet[..], expected_server_packet[..]);
}
// This test is based on picoquic's output for `multipath_aead_test` in
// `picoquictest/multipath_test.c`.
//
// See <https://github.com/private-octopus/picoquic/blob/be0d99e6d4f8759cb7920425351c06a1c6f4a958/picoquictest/multipath_test.c#L1537-L1606>
#[test]
fn test_multipath_aead_basic() {
const SECRET: &[u8; 32] = &[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 35, 26, 27, 28, 29, 30, 31,
];
const PN: u64 = 12345;
const PATH_ID: u32 = 2;
const PAYLOAD: &[u8] = b"The quick brown fox jumps over the lazy dog";
const HEADER: &[u8] = b"This is a test";
const EXPECTED: &[u8] = &[
123, 139, 232, 52, 136, 25, 201, 143, 250, 89, 87, 39, 37, 63, 0, 210, 220, 227, 186,
140, 183, 251, 13, 203, 6, 116, 204, 100, 166, 64, 43, 185, 174, 85, 212, 163, 242,
141, 24, 166, 62, 228, 187, 137, 248, 31, 152, 126, 240, 151, 79, 51, 253, 130, 43,
114, 173, 234, 254,
];
let secret = OkmBlock::new(SECRET);
let builder = KeyBuilder::new(
&secret,
Version::V1,
TLS13_AES_128_GCM_SHA256_INTERNAL
.quic
.unwrap(),
TLS13_AES_128_GCM_SHA256_INTERNAL.hkdf_provider,
);
let packet = builder.packet_key();
let mut buf = PAYLOAD.to_vec();
let tag = packet
.encrypt_in_place_for_path(PATH_ID, PN, HEADER, &mut buf)
.unwrap();
buf.extend_from_slice(tag.as_ref());
assert_eq!(buf.as_slice(), EXPECTED);
}
// This test is based on `multipath_aead_test` in `picoquictest/multipath_test.c`
//
// See <https://github.com/private-octopus/picoquic/blob/be0d99e6d4f8759cb7920425351c06a1c6f4a958/picoquictest/multipath_test.c#L1537-L1606>
#[test]
fn test_multipath_aead_roundtrip() {
const SECRET: &[u8; 32] = &[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 35, 26, 27, 28, 29, 30, 31,
];
const PAYLOAD: &[u8] = b"The quick brown fox jumps over the lazy dog";
const HEADER: &[u8] = b"This is a test";
const PN: u64 = 12345;
const TEST_PATH_IDS: &[u32] = &[0, 1, 2, 0xaead];
let secret = OkmBlock::new(SECRET);
let builder = KeyBuilder::new(
&secret,
Version::V1,
TLS13_AES_128_GCM_SHA256_INTERNAL
.quic
.unwrap(),
TLS13_AES_128_GCM_SHA256_INTERNAL.hkdf_provider,
);
let packet = builder.packet_key();
for &path_id in TEST_PATH_IDS {
let mut buf = PAYLOAD.to_vec();
let tag = packet
.encrypt_in_place_for_path(path_id, PN, HEADER, &mut buf)
.unwrap();
buf.extend_from_slice(tag.as_ref());
let decrypted = packet
.decrypt_in_place_for_path(path_id, PN, HEADER, &mut buf)
.unwrap();
assert_eq!(decrypted, PAYLOAD);
}
}
}
+826
View File
@@ -0,0 +1,826 @@
#![allow(clippy::duplicate_mod)]
use alloc::boxed::Box;
use alloc::string::ToString;
use alloc::vec::Vec;
use alloc::{format, vec};
use core::fmt::{self, Debug, Formatter};
use pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer, SubjectPublicKeyInfoDer, alg_id};
use super::ring_like::rand::{SecureRandom, SystemRandom};
use super::ring_like::signature::{self, EcdsaKeyPair, Ed25519KeyPair, KeyPair, RsaKeyPair};
use crate::crypto::signer::{Signer, SigningKey, public_key_to_spki};
use crate::enums::{SignatureAlgorithm, SignatureScheme};
use crate::error::Error;
use crate::sync::Arc;
use crate::x509::{wrap_concat_in_sequence, wrap_in_octet_string};
/// Parse `der` as any supported key encoding/type, returning
/// the first which works.
pub fn any_supported_type(der: &PrivateKeyDer<'_>) -> Result<Arc<dyn SigningKey>, Error> {
if let Ok(rsa) = RsaSigningKey::new(der) {
return Ok(Arc::new(rsa));
}
if let Ok(ecdsa) = any_ecdsa_type(der) {
return Ok(ecdsa);
}
if let PrivateKeyDer::Pkcs8(pkcs8) = der {
if let Ok(eddsa) = any_eddsa_type(pkcs8) {
return Ok(eddsa);
}
}
Err(Error::General(
"failed to parse private key as RSA, ECDSA, or EdDSA".into(),
))
}
/// Parse `der` as any ECDSA key type, returning the first which works.
///
/// Both SEC1 (PEM section starting with 'BEGIN EC PRIVATE KEY') and PKCS8
/// (PEM section starting with 'BEGIN PRIVATE KEY') encodings are supported.
pub fn any_ecdsa_type(der: &PrivateKeyDer<'_>) -> Result<Arc<dyn SigningKey>, Error> {
if let Ok(ecdsa_p256) = EcdsaSigningKey::new(
der,
SignatureScheme::ECDSA_NISTP256_SHA256,
&signature::ECDSA_P256_SHA256_ASN1_SIGNING,
) {
return Ok(Arc::new(ecdsa_p256));
}
if let Ok(ecdsa_p384) = EcdsaSigningKey::new(
der,
SignatureScheme::ECDSA_NISTP384_SHA384,
&signature::ECDSA_P384_SHA384_ASN1_SIGNING,
) {
return Ok(Arc::new(ecdsa_p384));
}
Err(Error::General(
"failed to parse ECDSA private key as PKCS#8 or SEC1".into(),
))
}
/// Parse `der` as any EdDSA key type, returning the first which works.
///
/// Note that, at the time of writing, Ed25519 does not have wide support
/// in browsers. It is also not supported by the WebPKI, because the
/// CA/Browser Forum Baseline Requirements do not support it for publicly
/// trusted certificates.
pub fn any_eddsa_type(der: &PrivatePkcs8KeyDer<'_>) -> Result<Arc<dyn SigningKey>, Error> {
// TODO: Add support for Ed448
Ok(Arc::new(Ed25519SigningKey::new(
der,
SignatureScheme::ED25519,
)?))
}
/// A `SigningKey` for RSA-PKCS1 or RSA-PSS.
///
/// This is used by the test suite, so it must be `pub`, but it isn't part of
/// the public, stable, API.
#[doc(hidden)]
pub struct RsaSigningKey {
key: Arc<RsaKeyPair>,
}
static ALL_RSA_SCHEMES: &[SignatureScheme] = &[
SignatureScheme::RSA_PSS_SHA512,
SignatureScheme::RSA_PSS_SHA384,
SignatureScheme::RSA_PSS_SHA256,
SignatureScheme::RSA_PKCS1_SHA512,
SignatureScheme::RSA_PKCS1_SHA384,
SignatureScheme::RSA_PKCS1_SHA256,
];
impl RsaSigningKey {
/// Make a new `RsaSigningKey` from a DER encoding, in either
/// PKCS#1 or PKCS#8 format.
pub fn new(der: &PrivateKeyDer<'_>) -> Result<Self, Error> {
let key_pair = match der {
PrivateKeyDer::Pkcs1(pkcs1) => RsaKeyPair::from_der(pkcs1.secret_pkcs1_der()),
PrivateKeyDer::Pkcs8(pkcs8) => RsaKeyPair::from_pkcs8(pkcs8.secret_pkcs8_der()),
_ => {
return Err(Error::General(
"failed to parse RSA private key as either PKCS#1 or PKCS#8".into(),
));
}
}
.map_err(|key_rejected| {
Error::General(format!("failed to parse RSA private key: {key_rejected}"))
})?;
Ok(Self {
key: Arc::new(key_pair),
})
}
}
impl SigningKey for RsaSigningKey {
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
ALL_RSA_SCHEMES
.iter()
.find(|scheme| offered.contains(scheme))
.map(|scheme| RsaSigner::new(self.key.clone(), *scheme))
}
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
Some(public_key_to_spki(
&alg_id::RSA_ENCRYPTION,
self.key.public_key(),
))
}
fn algorithm(&self) -> SignatureAlgorithm {
SignatureAlgorithm::RSA
}
}
impl Debug for RsaSigningKey {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("RsaSigningKey")
.field("algorithm", &self.algorithm())
.finish()
}
}
struct RsaSigner {
key: Arc<RsaKeyPair>,
scheme: SignatureScheme,
encoding: &'static dyn signature::RsaEncoding,
}
impl RsaSigner {
fn new(key: Arc<RsaKeyPair>, scheme: SignatureScheme) -> Box<dyn Signer> {
let encoding: &dyn signature::RsaEncoding = match scheme {
SignatureScheme::RSA_PKCS1_SHA256 => &signature::RSA_PKCS1_SHA256,
SignatureScheme::RSA_PKCS1_SHA384 => &signature::RSA_PKCS1_SHA384,
SignatureScheme::RSA_PKCS1_SHA512 => &signature::RSA_PKCS1_SHA512,
SignatureScheme::RSA_PSS_SHA256 => &signature::RSA_PSS_SHA256,
SignatureScheme::RSA_PSS_SHA384 => &signature::RSA_PSS_SHA384,
SignatureScheme::RSA_PSS_SHA512 => &signature::RSA_PSS_SHA512,
_ => unreachable!(),
};
Box::new(Self {
key,
scheme,
encoding,
})
}
}
impl Signer for RsaSigner {
fn sign(&self, message: &[u8]) -> Result<Vec<u8>, Error> {
let mut sig = vec![0; self.key.public().modulus_len()];
let rng = SystemRandom::new();
self.key
.sign(self.encoding, &rng, message, &mut sig)
.map(|_| sig)
.map_err(|_| Error::General("signing failed".to_string()))
}
fn scheme(&self) -> SignatureScheme {
self.scheme
}
}
impl Debug for RsaSigner {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("RsaSigner")
.field("scheme", &self.scheme)
.finish()
}
}
/// A SigningKey that uses exactly one TLS-level SignatureScheme
/// and one ring-level signature::SigningAlgorithm.
///
/// Compare this to RsaSigningKey, which for a particular key is
/// willing to sign with several algorithms. This is quite poor
/// cryptography practice, but is necessary because a given RSA key
/// is expected to work in TLS1.2 (PKCS#1 signatures) and TLS1.3
/// (PSS signatures) -- nobody is willing to obtain certificates for
/// different protocol versions.
///
/// Currently this is only implemented for ECDSA keys.
struct EcdsaSigningKey {
key: Arc<EcdsaKeyPair>,
scheme: SignatureScheme,
}
impl EcdsaSigningKey {
/// Make a new `ECDSASigningKey` from a DER encoding in PKCS#8 or SEC1
/// format, expecting a key usable with precisely the given signature
/// scheme.
fn new(
der: &PrivateKeyDer<'_>,
scheme: SignatureScheme,
sigalg: &'static signature::EcdsaSigningAlgorithm,
) -> Result<Self, ()> {
let rng = SystemRandom::new();
let key_pair = match der {
PrivateKeyDer::Sec1(sec1) => {
Self::convert_sec1_to_pkcs8(scheme, sigalg, sec1.secret_sec1_der(), &rng)?
}
PrivateKeyDer::Pkcs8(pkcs8) => {
EcdsaKeyPair::from_pkcs8(sigalg, pkcs8.secret_pkcs8_der(), &rng).map_err(|_| ())?
}
_ => return Err(()),
};
Ok(Self {
key: Arc::new(key_pair),
scheme,
})
}
/// Convert a SEC1 encoding to PKCS8, and ask ring to parse it. This
/// can be removed once <https://github.com/briansmith/ring/pull/1456>
/// (or equivalent) is landed.
fn convert_sec1_to_pkcs8(
scheme: SignatureScheme,
sigalg: &'static signature::EcdsaSigningAlgorithm,
maybe_sec1_der: &[u8],
rng: &dyn SecureRandom,
) -> Result<EcdsaKeyPair, ()> {
let pkcs8_prefix = match scheme {
SignatureScheme::ECDSA_NISTP256_SHA256 => &PKCS8_PREFIX_ECDSA_NISTP256,
SignatureScheme::ECDSA_NISTP384_SHA384 => &PKCS8_PREFIX_ECDSA_NISTP384,
_ => unreachable!(), // all callers are in this file
};
let sec1_wrap = wrap_in_octet_string(maybe_sec1_der);
let pkcs8 = wrap_concat_in_sequence(pkcs8_prefix, &sec1_wrap);
EcdsaKeyPair::from_pkcs8(sigalg, &pkcs8, rng).map_err(|_| ())
}
}
// This is (line-by-line):
// - INTEGER Version = 0
// - SEQUENCE (privateKeyAlgorithm)
// - id-ecPublicKey OID
// - prime256v1 OID
const PKCS8_PREFIX_ECDSA_NISTP256: &[u8] = b"\x02\x01\x00\
\x30\x13\
\x06\x07\x2a\x86\x48\xce\x3d\x02\x01\
\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07";
// This is (line-by-line):
// - INTEGER Version = 0
// - SEQUENCE (privateKeyAlgorithm)
// - id-ecPublicKey OID
// - secp384r1 OID
const PKCS8_PREFIX_ECDSA_NISTP384: &[u8] = b"\x02\x01\x00\
\x30\x10\
\x06\x07\x2a\x86\x48\xce\x3d\x02\x01\
\x06\x05\x2b\x81\x04\x00\x22";
impl SigningKey for EcdsaSigningKey {
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
if offered.contains(&self.scheme) {
Some(Box::new(EcdsaSigner {
key: self.key.clone(),
scheme: self.scheme,
}))
} else {
None
}
}
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
let id = match self.scheme {
SignatureScheme::ECDSA_NISTP256_SHA256 => alg_id::ECDSA_P256,
SignatureScheme::ECDSA_NISTP384_SHA384 => alg_id::ECDSA_P384,
_ => unreachable!(),
};
Some(public_key_to_spki(&id, self.key.public_key()))
}
fn algorithm(&self) -> SignatureAlgorithm {
self.scheme
.algorithm()
.unwrap_or(SignatureAlgorithm::Unknown(0))
}
}
impl Debug for EcdsaSigningKey {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("EcdsaSigningKey")
.field("algorithm", &self.algorithm())
.finish()
}
}
struct EcdsaSigner {
key: Arc<EcdsaKeyPair>,
scheme: SignatureScheme,
}
impl Signer for EcdsaSigner {
fn sign(&self, message: &[u8]) -> Result<Vec<u8>, Error> {
let rng = SystemRandom::new();
self.key
.sign(&rng, message)
.map_err(|_| Error::General("signing failed".into()))
.map(|sig| sig.as_ref().into())
}
fn scheme(&self) -> SignatureScheme {
self.scheme
}
}
impl Debug for EcdsaSigner {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("EcdsaSigner")
.field("scheme", &self.scheme)
.finish()
}
}
/// A SigningKey that uses exactly one TLS-level SignatureScheme
/// and one ring-level signature::SigningAlgorithm.
///
/// Compare this to RsaSigningKey, which for a particular key is
/// willing to sign with several algorithms. This is quite poor
/// cryptography practice, but is necessary because a given RSA key
/// is expected to work in TLS1.2 (PKCS#1 signatures) and TLS1.3
/// (PSS signatures) -- nobody is willing to obtain certificates for
/// different protocol versions.
///
/// Currently this is only implemented for Ed25519 keys.
struct Ed25519SigningKey {
key: Arc<Ed25519KeyPair>,
scheme: SignatureScheme,
}
impl Ed25519SigningKey {
/// Make a new `Ed25519SigningKey` from a DER encoding in PKCS#8 format,
/// expecting a key usable with precisely the given signature scheme.
fn new(der: &PrivatePkcs8KeyDer<'_>, scheme: SignatureScheme) -> Result<Self, Error> {
match Ed25519KeyPair::from_pkcs8_maybe_unchecked(der.secret_pkcs8_der()) {
Ok(key_pair) => Ok(Self {
key: Arc::new(key_pair),
scheme,
}),
Err(e) => Err(Error::General(format!(
"failed to parse Ed25519 private key: {e}"
))),
}
}
}
impl SigningKey for Ed25519SigningKey {
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
if offered.contains(&self.scheme) {
Some(Box::new(Ed25519Signer {
key: self.key.clone(),
scheme: self.scheme,
}))
} else {
None
}
}
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
Some(public_key_to_spki(&alg_id::ED25519, self.key.public_key()))
}
fn algorithm(&self) -> SignatureAlgorithm {
self.scheme
.algorithm()
.unwrap_or(SignatureAlgorithm::Unknown(0))
}
}
impl Debug for Ed25519SigningKey {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Ed25519SigningKey")
.field("algorithm", &self.algorithm())
.finish()
}
}
struct Ed25519Signer {
key: Arc<Ed25519KeyPair>,
scheme: SignatureScheme,
}
impl Signer for Ed25519Signer {
fn sign(&self, message: &[u8]) -> Result<Vec<u8>, Error> {
Ok(self.key.sign(message).as_ref().into())
}
fn scheme(&self) -> SignatureScheme {
self.scheme
}
}
impl Debug for Ed25519Signer {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Ed25519Signer")
.field("scheme", &self.scheme)
.finish()
}
}
#[cfg(test)]
mod tests {
use alloc::format;
use pki_types::{PrivatePkcs1KeyDer, PrivateSec1KeyDer};
use super::*;
#[test]
fn can_load_ecdsa_nistp256_pkcs8() {
let key =
PrivatePkcs8KeyDer::from(&include_bytes!("../../testdata/nistp256key.pkcs8.der")[..]);
assert!(any_eddsa_type(&key).is_err());
let key = PrivateKeyDer::Pkcs8(key);
assert!(any_supported_type(&key).is_ok());
assert!(any_ecdsa_type(&key).is_ok());
}
#[test]
fn can_load_ecdsa_nistp256_sec1() {
let key = PrivateKeyDer::Sec1(PrivateSec1KeyDer::from(
&include_bytes!("../../testdata/nistp256key.der")[..],
));
assert!(any_supported_type(&key).is_ok());
assert!(any_ecdsa_type(&key).is_ok());
}
#[test]
fn can_sign_ecdsa_nistp256() {
let key = PrivateKeyDer::Sec1(PrivateSec1KeyDer::from(
&include_bytes!("../../testdata/nistp256key.der")[..],
));
let k = any_supported_type(&key).unwrap();
assert_eq!(format!("{k:?}"), "EcdsaSigningKey { algorithm: ECDSA }");
assert_eq!(k.algorithm(), SignatureAlgorithm::ECDSA);
assert!(
k.choose_scheme(&[SignatureScheme::RSA_PKCS1_SHA256])
.is_none()
);
assert!(
k.choose_scheme(&[SignatureScheme::ECDSA_NISTP384_SHA384])
.is_none()
);
let s = k
.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256])
.unwrap();
assert_eq!(
format!("{s:?}"),
"EcdsaSigner { scheme: ECDSA_NISTP256_SHA256 }"
);
assert_eq!(s.scheme(), SignatureScheme::ECDSA_NISTP256_SHA256);
// nb. signature is variable length and asn.1-encoded
assert!(
s.sign(b"hello")
.unwrap()
.starts_with(&[0x30])
);
}
#[test]
fn can_load_ecdsa_nistp384_pkcs8() {
let key =
PrivatePkcs8KeyDer::from(&include_bytes!("../../testdata/nistp384key.pkcs8.der")[..]);
assert!(any_eddsa_type(&key).is_err());
let key = PrivateKeyDer::Pkcs8(key);
assert!(any_supported_type(&key).is_ok());
assert!(any_ecdsa_type(&key).is_ok());
}
#[test]
fn can_load_ecdsa_nistp384_sec1() {
let key = PrivateKeyDer::Sec1(PrivateSec1KeyDer::from(
&include_bytes!("../../testdata/nistp384key.der")[..],
));
assert!(any_supported_type(&key).is_ok());
assert!(any_ecdsa_type(&key).is_ok());
}
#[test]
fn can_sign_ecdsa_nistp384() {
let key = PrivateKeyDer::Sec1(PrivateSec1KeyDer::from(
&include_bytes!("../../testdata/nistp384key.der")[..],
));
let k = any_supported_type(&key).unwrap();
assert_eq!(format!("{k:?}"), "EcdsaSigningKey { algorithm: ECDSA }");
assert_eq!(k.algorithm(), SignatureAlgorithm::ECDSA);
assert!(
k.choose_scheme(&[SignatureScheme::RSA_PKCS1_SHA256])
.is_none()
);
assert!(
k.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256])
.is_none()
);
let s = k
.choose_scheme(&[SignatureScheme::ECDSA_NISTP384_SHA384])
.unwrap();
assert_eq!(
format!("{s:?}"),
"EcdsaSigner { scheme: ECDSA_NISTP384_SHA384 }"
);
assert_eq!(s.scheme(), SignatureScheme::ECDSA_NISTP384_SHA384);
// nb. signature is variable length and asn.1-encoded
assert!(
s.sign(b"hello")
.unwrap()
.starts_with(&[0x30])
);
}
#[test]
fn can_load_eddsa_pkcs8() {
let key = PrivatePkcs8KeyDer::from(&include_bytes!("../../testdata/eddsakey.der")[..]);
assert!(any_eddsa_type(&key).is_ok());
let key = PrivateKeyDer::Pkcs8(key);
assert!(any_supported_type(&key).is_ok());
assert!(any_ecdsa_type(&key).is_err());
}
#[test]
fn can_sign_eddsa() {
let key = PrivatePkcs8KeyDer::from(&include_bytes!("../../testdata/eddsakey.der")[..]);
let k = any_eddsa_type(&key).unwrap();
assert_eq!(format!("{k:?}"), "Ed25519SigningKey { algorithm: ED25519 }");
assert_eq!(k.algorithm(), SignatureAlgorithm::ED25519);
assert!(
k.choose_scheme(&[SignatureScheme::RSA_PKCS1_SHA256])
.is_none()
);
assert!(
k.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256])
.is_none()
);
let s = k
.choose_scheme(&[SignatureScheme::ED25519])
.unwrap();
assert_eq!(format!("{s:?}"), "Ed25519Signer { scheme: ED25519 }");
assert_eq!(s.scheme(), SignatureScheme::ED25519);
assert_eq!(s.sign(b"hello").unwrap().len(), 64);
}
#[test]
fn can_load_rsa2048_pkcs8() {
let key =
PrivatePkcs8KeyDer::from(&include_bytes!("../../testdata/rsa2048key.pkcs8.der")[..]);
assert!(any_eddsa_type(&key).is_err());
let key = PrivateKeyDer::Pkcs8(key);
assert!(any_supported_type(&key).is_ok());
assert!(any_ecdsa_type(&key).is_err());
}
#[test]
fn can_load_rsa2048_pkcs1() {
let key = PrivateKeyDer::Pkcs1(PrivatePkcs1KeyDer::from(
&include_bytes!("../../testdata/rsa2048key.pkcs1.der")[..],
));
assert!(any_supported_type(&key).is_ok());
assert!(any_ecdsa_type(&key).is_err());
}
#[test]
fn can_sign_rsa2048() {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/rsa2048key.pkcs8.der")[..],
));
let k = any_supported_type(&key).unwrap();
assert_eq!(format!("{k:?}"), "RsaSigningKey { algorithm: RSA }");
assert_eq!(k.algorithm(), SignatureAlgorithm::RSA);
assert!(
k.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256])
.is_none()
);
assert!(
k.choose_scheme(&[SignatureScheme::ED25519])
.is_none()
);
let s = k
.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256])
.unwrap();
assert_eq!(format!("{s:?}"), "RsaSigner { scheme: RSA_PSS_SHA256 }");
assert_eq!(s.scheme(), SignatureScheme::RSA_PSS_SHA256);
assert_eq!(s.sign(b"hello").unwrap().len(), 256);
for scheme in &[
SignatureScheme::RSA_PKCS1_SHA256,
SignatureScheme::RSA_PKCS1_SHA384,
SignatureScheme::RSA_PKCS1_SHA512,
SignatureScheme::RSA_PSS_SHA256,
SignatureScheme::RSA_PSS_SHA384,
SignatureScheme::RSA_PSS_SHA512,
] {
k.choose_scheme(&[*scheme]).unwrap();
}
}
#[test]
fn cannot_load_invalid_pkcs8_encoding() {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(&b"invalid"[..]));
assert_eq!(
any_supported_type(&key).err(),
Some(Error::General(
"failed to parse private key as RSA, ECDSA, or EdDSA".into()
))
);
assert_eq!(
any_ecdsa_type(&key).err(),
Some(Error::General(
"failed to parse ECDSA private key as PKCS#8 or SEC1".into()
))
);
assert_eq!(
RsaSigningKey::new(&key).err(),
Some(Error::General(
"failed to parse RSA private key: InvalidEncoding".into()
))
);
}
}
#[cfg(bench)]
mod benchmarks {
use super::{PrivateKeyDer, PrivatePkcs8KeyDer, SignatureScheme};
#[bench]
fn bench_rsa2048_pkcs1_sha256(b: &mut test::Bencher) {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/rsa2048key.pkcs8.der")[..],
));
let sk = super::any_supported_type(&key).unwrap();
let signer = sk
.choose_scheme(&[SignatureScheme::RSA_PKCS1_SHA256])
.unwrap();
b.iter(|| {
test::black_box(
signer
.sign(SAMPLE_TLS13_MESSAGE)
.unwrap(),
);
});
}
#[bench]
fn bench_rsa2048_pss_sha256(b: &mut test::Bencher) {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/rsa2048key.pkcs8.der")[..],
));
let sk = super::any_supported_type(&key).unwrap();
let signer = sk
.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256])
.unwrap();
b.iter(|| {
test::black_box(
signer
.sign(SAMPLE_TLS13_MESSAGE)
.unwrap(),
);
});
}
#[bench]
fn bench_eddsa(b: &mut test::Bencher) {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/eddsakey.der")[..],
));
let sk = super::any_supported_type(&key).unwrap();
let signer = sk
.choose_scheme(&[SignatureScheme::ED25519])
.unwrap();
b.iter(|| {
test::black_box(
signer
.sign(SAMPLE_TLS13_MESSAGE)
.unwrap(),
);
});
}
#[bench]
fn bench_ecdsa_p256_sha256(b: &mut test::Bencher) {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/nistp256key.pkcs8.der")[..],
));
let sk = super::any_supported_type(&key).unwrap();
let signer = sk
.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256])
.unwrap();
b.iter(|| {
test::black_box(
signer
.sign(SAMPLE_TLS13_MESSAGE)
.unwrap(),
);
});
}
#[bench]
fn bench_ecdsa_p384_sha384(b: &mut test::Bencher) {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/nistp384key.pkcs8.der")[..],
));
let sk = super::any_supported_type(&key).unwrap();
let signer = sk
.choose_scheme(&[SignatureScheme::ECDSA_NISTP384_SHA384])
.unwrap();
b.iter(|| {
test::black_box(
signer
.sign(SAMPLE_TLS13_MESSAGE)
.unwrap(),
);
});
}
#[bench]
fn bench_load_and_validate_rsa2048(b: &mut test::Bencher) {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/rsa2048key.pkcs8.der")[..],
));
b.iter(|| {
test::black_box(super::any_supported_type(&key).unwrap());
});
}
#[bench]
fn bench_load_and_validate_rsa4096(b: &mut test::Bencher) {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/rsa4096key.pkcs8.der")[..],
));
b.iter(|| {
test::black_box(super::any_supported_type(&key).unwrap());
});
}
#[bench]
fn bench_load_and_validate_p256(b: &mut test::Bencher) {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/nistp256key.pkcs8.der")[..],
));
b.iter(|| {
test::black_box(super::any_ecdsa_type(&key).unwrap());
});
}
#[bench]
fn bench_load_and_validate_p384(b: &mut test::Bencher) {
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
&include_bytes!("../../testdata/nistp384key.pkcs8.der")[..],
));
b.iter(|| {
test::black_box(super::any_ecdsa_type(&key).unwrap());
});
}
#[bench]
fn bench_load_and_validate_eddsa(b: &mut test::Bencher) {
let key = PrivatePkcs8KeyDer::from(&include_bytes!("../../testdata/eddsakey.der")[..]);
b.iter(|| {
test::black_box(super::any_eddsa_type(&key).unwrap());
});
}
const SAMPLE_TLS13_MESSAGE: &[u8] = &[
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x54, 0x4c, 0x53, 0x20, 0x31, 0x2e, 0x33, 0x2c, 0x20, 0x73, 0x65,
0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74,
0x65, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x00, 0x04, 0xca, 0xc4, 0x48, 0x0e, 0x70, 0xf2,
0x1b, 0xa9, 0x1c, 0x16, 0xca, 0x90, 0x48, 0xbe, 0x28, 0x2f, 0xc7, 0xf8, 0x9b, 0x87, 0x72,
0x93, 0xda, 0x4d, 0x2f, 0x80, 0x80, 0x60, 0x1a, 0xd3, 0x08, 0xe2, 0xb7, 0x86, 0x14, 0x1b,
0x54, 0xda, 0x9a, 0xc9, 0x6d, 0xe9, 0x66, 0xb4, 0x9f, 0xe2, 0x2c,
];
}
+366
View File
@@ -0,0 +1,366 @@
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt;
use core::fmt::{Debug, Formatter};
use core::sync::atomic::{AtomicUsize, Ordering};
use subtle::ConstantTimeEq;
use super::ring_like::aead;
use super::ring_like::rand::{SecureRandom, SystemRandom};
use crate::error::Error;
#[cfg(debug_assertions)]
use crate::log::debug;
use crate::polyfill::try_split_at;
use crate::rand::GetRandomFailed;
use crate::server::ProducesTickets;
use crate::sync::Arc;
/// A concrete, safe ticket creation mechanism.
pub struct Ticketer {}
impl Ticketer {
/// Make the recommended `Ticketer`. This produces tickets
/// with a 12 hour life and randomly generated keys.
///
/// The encryption mechanism used is Chacha20Poly1305.
#[cfg(feature = "std")]
pub fn new() -> Result<Arc<dyn ProducesTickets>, Error> {
Ok(Arc::new(crate::ticketer::TicketRotator::new(
6 * 60 * 60,
make_ticket_generator,
)?))
}
}
fn make_ticket_generator() -> Result<Box<dyn ProducesTickets>, GetRandomFailed> {
Ok(Box::new(AeadTicketer::new()?))
}
/// This is a `ProducesTickets` implementation which uses
/// any *ring* `aead::Algorithm` to encrypt and authentication
/// the ticket payload. It does not enforce any lifetime
/// constraint.
struct AeadTicketer {
alg: &'static aead::Algorithm,
key: aead::LessSafeKey,
key_name: [u8; 16],
lifetime: u32,
/// Tracks the largest ciphertext produced by `encrypt`, and
/// uses it to early-reject `decrypt` queries that are too long.
///
/// Accepting excessively long ciphertexts means a "Partitioning
/// Oracle Attack" (see <https://eprint.iacr.org/2020/1491.pdf>)
/// can be more efficient, though also note that these are thought
/// to be cryptographically hard if the key is full-entropy (as it
/// is here).
maximum_ciphertext_len: AtomicUsize,
}
impl AeadTicketer {
fn new() -> Result<Self, GetRandomFailed> {
let mut key = [0u8; 32];
SystemRandom::new()
.fill(&mut key)
.map_err(|_| GetRandomFailed)?;
let key = aead::UnboundKey::new(TICKETER_AEAD, &key).unwrap();
let mut key_name = [0u8; 16];
SystemRandom::new()
.fill(&mut key_name)
.map_err(|_| GetRandomFailed)?;
Ok(Self {
alg: TICKETER_AEAD,
key: aead::LessSafeKey::new(key),
key_name,
lifetime: 60 * 60 * 12,
maximum_ciphertext_len: AtomicUsize::new(0),
})
}
}
impl ProducesTickets for AeadTicketer {
fn enabled(&self) -> bool {
true
}
fn lifetime(&self) -> u32 {
self.lifetime
}
/// Encrypt `message` and return the ciphertext.
fn encrypt(&self, message: &[u8]) -> Option<Vec<u8>> {
// Random nonce, because a counter is a privacy leak.
let mut nonce_buf = [0u8; 12];
SystemRandom::new()
.fill(&mut nonce_buf)
.ok()?;
let nonce = aead::Nonce::assume_unique_for_key(nonce_buf);
let aad = aead::Aad::from(self.key_name);
// ciphertext structure is:
// key_name: [u8; 16]
// nonce: [u8; 12]
// message: [u8, _]
// tag: [u8; 16]
let mut ciphertext = Vec::with_capacity(
self.key_name.len() + nonce_buf.len() + message.len() + self.key.algorithm().tag_len(),
);
ciphertext.extend(self.key_name);
ciphertext.extend(nonce_buf);
ciphertext.extend(message);
let ciphertext = self
.key
.seal_in_place_separate_tag(
nonce,
aad,
&mut ciphertext[self.key_name.len() + nonce_buf.len()..],
)
.map(|tag| {
ciphertext.extend(tag.as_ref());
ciphertext
})
.ok()?;
self.maximum_ciphertext_len
.fetch_max(ciphertext.len(), Ordering::SeqCst);
Some(ciphertext)
}
/// Decrypt `ciphertext` and recover the original message.
fn decrypt(&self, ciphertext: &[u8]) -> Option<Vec<u8>> {
if ciphertext.len()
> self
.maximum_ciphertext_len
.load(Ordering::SeqCst)
{
#[cfg(debug_assertions)]
debug!("rejected over-length ticket");
return None;
}
let (alleged_key_name, ciphertext) = try_split_at(ciphertext, self.key_name.len())?;
let (nonce, ciphertext) = try_split_at(ciphertext, self.alg.nonce_len())?;
// checking the key_name is the expected one, *and* then putting it into the
// additionally authenticated data is duplicative. this check quickly rejects
// tickets for a different ticketer (see `TicketSwitcher`), while including it
// in the AAD ensures it is authenticated independent of that check and that
// any attempted attack on the integrity such as [^1] must happen for each
// `key_label`, not over a population of potential keys. this approach
// is overall similar to [^2].
//
// [^1]: https://eprint.iacr.org/2020/1491.pdf
// [^2]: "Authenticated Encryption with Key Identification", fig 6
// <https://eprint.iacr.org/2022/1680.pdf>
if ConstantTimeEq::ct_ne(&self.key_name[..], alleged_key_name).into() {
#[cfg(debug_assertions)]
debug!("rejected ticket with wrong ticket_name");
return None;
}
// This won't fail since `nonce` has the required length.
let nonce = aead::Nonce::try_assume_unique_for_key(nonce).ok()?;
let mut out = Vec::from(ciphertext);
let plain_len = self
.key
.open_in_place(nonce, aead::Aad::from(alleged_key_name), &mut out)
.ok()?
.len();
out.truncate(plain_len);
Some(out)
}
}
impl Debug for AeadTicketer {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
// Note: we deliberately omit the key from the debug output.
f.debug_struct("AeadTicketer")
.field("alg", &self.alg)
.field("lifetime", &self.lifetime)
.finish()
}
}
static TICKETER_AEAD: &aead::Algorithm = &aead::CHACHA20_POLY1305;
#[cfg(test)]
mod tests {
use core::time::Duration;
use pki_types::UnixTime;
use super::*;
#[test]
fn basic_pairwise_test() {
let t = Ticketer::new().unwrap();
assert!(t.enabled());
let cipher = t.encrypt(b"hello world").unwrap();
let plain = t.decrypt(&cipher).unwrap();
assert_eq!(plain, b"hello world");
}
#[test]
fn refuses_decrypt_before_encrypt() {
let t = Ticketer::new().unwrap();
assert_eq!(t.decrypt(b"hello"), None);
}
#[test]
fn refuses_decrypt_larger_than_largest_encryption() {
let t = Ticketer::new().unwrap();
let mut cipher = t.encrypt(b"hello world").unwrap();
assert_eq!(t.decrypt(&cipher), Some(b"hello world".to_vec()));
// obviously this would never work anyway, but this
// and `cannot_decrypt_before_encrypt` exercise the
// first branch in `decrypt()`
cipher.push(0);
assert_eq!(t.decrypt(&cipher), None);
}
#[test]
fn ticketrotator_switching_test() {
let t = Arc::new(crate::ticketer::TicketRotator::new(1, make_ticket_generator).unwrap());
let now = UnixTime::now();
let cipher1 = t.encrypt(b"ticket 1").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
{
// Trigger new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 10,
)));
}
let cipher2 = t.encrypt(b"ticket 2").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
{
// Trigger new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 20,
)));
}
let cipher3 = t.encrypt(b"ticket 3").unwrap();
assert!(t.decrypt(&cipher1).is_none());
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
}
#[test]
fn ticketrotator_remains_usable_over_temporary_ticketer_creation_failure() {
let mut t = crate::ticketer::TicketRotator::new(1, make_ticket_generator).unwrap();
let now = UnixTime::now();
let cipher1 = t.encrypt(b"ticket 1").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
t.generator = fail_generator;
{
// Failed new ticketer; this means we still need to
// rotate.
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 10,
)));
}
// check post-failure encryption/decryption still works
let cipher2 = t.encrypt(b"ticket 2").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
// do the rotation for real
t.generator = make_ticket_generator;
{
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 20,
)));
}
let cipher3 = t.encrypt(b"ticket 3").unwrap();
assert!(t.decrypt(&cipher1).is_some());
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
}
#[test]
fn ticketswitcher_switching_test() {
#[expect(deprecated)]
let t = Arc::new(crate::ticketer::TicketSwitcher::new(1, make_ticket_generator).unwrap());
let now = UnixTime::now();
let cipher1 = t.encrypt(b"ticket 1").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
{
// Trigger new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 10,
)));
}
let cipher2 = t.encrypt(b"ticket 2").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
{
// Trigger new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 20,
)));
}
let cipher3 = t.encrypt(b"ticket 3").unwrap();
assert!(t.decrypt(&cipher1).is_none());
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
}
#[test]
fn ticketswitcher_recover_test() {
#[expect(deprecated)]
let mut t = crate::ticketer::TicketSwitcher::new(1, make_ticket_generator).unwrap();
let now = UnixTime::now();
let cipher1 = t.encrypt(b"ticket 1").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
t.generator = fail_generator;
{
// Failed new ticketer
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 10,
)));
}
t.generator = make_ticket_generator;
let cipher2 = t.encrypt(b"ticket 2").unwrap();
assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
{
// recover
t.maybe_roll(UnixTime::since_unix_epoch(Duration::from_secs(
now.as_secs() + 20,
)));
}
let cipher3 = t.encrypt(b"ticket 3").unwrap();
assert!(t.decrypt(&cipher1).is_none());
assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
}
#[test]
fn aeadticketer_is_debug_and_producestickets() {
use alloc::format;
use super::*;
let t = make_ticket_generator().unwrap();
let expect = format!("AeadTicketer {{ alg: {TICKETER_AEAD:?}, lifetime: 43200 }}");
assert_eq!(format!("{t:?}"), expect);
assert!(t.enabled());
assert_eq!(t.lifetime(), 43200);
}
fn fail_generator() -> Result<Box<dyn ProducesTickets>, GetRandomFailed> {
Err(GetRandomFailed)
}
}
+406
View File
@@ -0,0 +1,406 @@
use alloc::boxed::Box;
use super::ring_like::aead;
use crate::crypto::KeyExchangeAlgorithm;
use crate::crypto::cipher::{
AeadKey, InboundOpaqueMessage, Iv, KeyBlockShape, MessageDecrypter, MessageEncrypter,
NONCE_LEN, Nonce, Tls12AeadAlgorithm, UnsupportedOperationError, make_tls12_aad,
};
use crate::crypto::tls12::PrfUsingHmac;
use crate::enums::{CipherSuite, SignatureScheme};
use crate::error::Error;
use crate::msgs::fragmenter::MAX_FRAGMENT_LEN;
use crate::msgs::message::{
InboundPlainMessage, OutboundOpaqueMessage, OutboundPlainMessage, PrefixedPayload,
};
use crate::suites::{CipherSuiteCommon, ConnectionTrafficSecrets, SupportedCipherSuite};
use crate::tls12::Tls12CipherSuite;
/// The TLS1.2 ciphersuite TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256.
pub static TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: u64::MAX,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_ECDSA_SCHEMES,
aead_alg: &ChaCha20Poly1305,
prf_provider: &PrfUsingHmac(&super::hmac::HMAC_SHA256),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
pub static TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: u64::MAX,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_RSA_SCHEMES,
aead_alg: &ChaCha20Poly1305,
prf_provider: &PrfUsingHmac(&super::hmac::HMAC_SHA256),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
pub static TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: 1 << 24,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_RSA_SCHEMES,
aead_alg: &AES128_GCM,
prf_provider: &PrfUsingHmac(&super::hmac::HMAC_SHA256),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
pub static TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
hash_provider: &super::hash::SHA384,
confidentiality_limit: 1 << 24,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_RSA_SCHEMES,
aead_alg: &AES256_GCM,
prf_provider: &PrfUsingHmac(&super::hmac::HMAC_SHA384),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
pub static TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: 1 << 24,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_ECDSA_SCHEMES,
aead_alg: &AES128_GCM,
prf_provider: &PrfUsingHmac(&super::hmac::HMAC_SHA256),
});
/// The TLS1.2 ciphersuite TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
pub static TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
hash_provider: &super::hash::SHA384,
confidentiality_limit: 1 << 24,
},
kx: KeyExchangeAlgorithm::ECDHE,
sign: TLS12_ECDSA_SCHEMES,
aead_alg: &AES256_GCM,
prf_provider: &PrfUsingHmac(&super::hmac::HMAC_SHA384),
});
static TLS12_ECDSA_SCHEMES: &[SignatureScheme] = &[
SignatureScheme::ED25519,
SignatureScheme::ECDSA_NISTP521_SHA512,
SignatureScheme::ECDSA_NISTP384_SHA384,
SignatureScheme::ECDSA_NISTP256_SHA256,
];
static TLS12_RSA_SCHEMES: &[SignatureScheme] = &[
SignatureScheme::RSA_PSS_SHA512,
SignatureScheme::RSA_PSS_SHA384,
SignatureScheme::RSA_PSS_SHA256,
SignatureScheme::RSA_PKCS1_SHA512,
SignatureScheme::RSA_PKCS1_SHA384,
SignatureScheme::RSA_PKCS1_SHA256,
];
pub(crate) static AES128_GCM: GcmAlgorithm = GcmAlgorithm(&aead::AES_128_GCM);
pub(crate) static AES256_GCM: GcmAlgorithm = GcmAlgorithm(&aead::AES_256_GCM);
pub(crate) struct GcmAlgorithm(&'static aead::Algorithm);
impl Tls12AeadAlgorithm for GcmAlgorithm {
fn decrypter(&self, dec_key: AeadKey, dec_iv: &[u8]) -> Box<dyn MessageDecrypter> {
let dec_key =
aead::LessSafeKey::new(aead::UnboundKey::new(self.0, dec_key.as_ref()).unwrap());
let mut ret = GcmMessageDecrypter {
dec_key,
dec_salt: [0u8; 4],
};
debug_assert_eq!(dec_iv.len(), 4);
ret.dec_salt.copy_from_slice(dec_iv);
Box::new(ret)
}
fn encrypter(
&self,
enc_key: AeadKey,
write_iv: &[u8],
explicit: &[u8],
) -> Box<dyn MessageEncrypter> {
let enc_key =
aead::LessSafeKey::new(aead::UnboundKey::new(self.0, enc_key.as_ref()).unwrap());
let iv = gcm_iv(write_iv, explicit);
Box::new(GcmMessageEncrypter { enc_key, iv })
}
fn key_block_shape(&self) -> KeyBlockShape {
KeyBlockShape {
enc_key_len: self.0.key_len(),
fixed_iv_len: 4,
explicit_nonce_len: 8,
}
}
fn extract_keys(
&self,
key: AeadKey,
write_iv: &[u8],
explicit: &[u8],
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
let iv = gcm_iv(write_iv, explicit);
Ok(match self.0.key_len() {
16 => ConnectionTrafficSecrets::Aes128Gcm { key, iv },
32 => ConnectionTrafficSecrets::Aes256Gcm { key, iv },
_ => unreachable!(),
})
}
fn fips(&self) -> bool {
super::fips()
}
}
pub(crate) struct ChaCha20Poly1305;
impl Tls12AeadAlgorithm for ChaCha20Poly1305 {
fn decrypter(&self, dec_key: AeadKey, iv: &[u8]) -> Box<dyn MessageDecrypter> {
let dec_key = aead::LessSafeKey::new(
aead::UnboundKey::new(&aead::CHACHA20_POLY1305, dec_key.as_ref()).unwrap(),
);
Box::new(ChaCha20Poly1305MessageDecrypter {
dec_key,
dec_offset: Iv::copy(iv),
})
}
fn encrypter(&self, enc_key: AeadKey, enc_iv: &[u8], _: &[u8]) -> Box<dyn MessageEncrypter> {
let enc_key = aead::LessSafeKey::new(
aead::UnboundKey::new(&aead::CHACHA20_POLY1305, enc_key.as_ref()).unwrap(),
);
Box::new(ChaCha20Poly1305MessageEncrypter {
enc_key,
enc_offset: Iv::copy(enc_iv),
})
}
fn key_block_shape(&self) -> KeyBlockShape {
KeyBlockShape {
enc_key_len: 32,
fixed_iv_len: 12,
explicit_nonce_len: 0,
}
}
fn extract_keys(
&self,
key: AeadKey,
iv: &[u8],
_explicit: &[u8],
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
// This should always be true because KeyBlockShape and the Iv nonce len are in agreement.
debug_assert_eq!(aead::NONCE_LEN, iv.len());
Ok(ConnectionTrafficSecrets::Chacha20Poly1305 {
key,
iv: Iv::new(iv[..].try_into().unwrap()),
})
}
fn fips(&self) -> bool {
false // not fips approved
}
}
/// A `MessageEncrypter` for AES-GCM AEAD ciphersuites. TLS 1.2 only.
struct GcmMessageEncrypter {
enc_key: aead::LessSafeKey,
iv: Iv,
}
/// A `MessageDecrypter` for AES-GCM AEAD ciphersuites. TLS1.2 only.
struct GcmMessageDecrypter {
dec_key: aead::LessSafeKey,
dec_salt: [u8; 4],
}
const GCM_EXPLICIT_NONCE_LEN: usize = 8;
const GCM_OVERHEAD: usize = GCM_EXPLICIT_NONCE_LEN + 16;
impl MessageDecrypter for GcmMessageDecrypter {
fn decrypt<'a>(
&mut self,
mut msg: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, Error> {
let payload = &msg.payload;
if payload.len() < GCM_OVERHEAD {
return Err(Error::DecryptError);
}
let nonce = {
let mut nonce = [0u8; 12];
nonce[..4].copy_from_slice(&self.dec_salt);
nonce[4..].copy_from_slice(&payload[..8]);
aead::Nonce::assume_unique_for_key(nonce)
};
let aad = aead::Aad::from(make_tls12_aad(
seq,
msg.typ,
msg.version,
payload.len() - GCM_OVERHEAD,
));
let payload = &mut msg.payload;
let plain_len = self
.dec_key
.open_within(nonce, aad, payload, GCM_EXPLICIT_NONCE_LEN..)
.map_err(|_| Error::DecryptError)?
.len();
if plain_len > MAX_FRAGMENT_LEN {
return Err(Error::PeerSentOversizedRecord);
}
payload.truncate(plain_len);
Ok(msg.into_plain_message())
}
}
impl MessageEncrypter for GcmMessageEncrypter {
fn encrypt(
&mut self,
msg: OutboundPlainMessage<'_>,
seq: u64,
) -> Result<OutboundOpaqueMessage, Error> {
let total_len = self.encrypted_payload_len(msg.payload.len());
let mut payload = PrefixedPayload::with_capacity(total_len);
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, seq).0);
let aad = aead::Aad::from(make_tls12_aad(seq, msg.typ, msg.version, msg.payload.len()));
payload.extend_from_slice(&nonce.as_ref()[4..]);
payload.extend_from_chunks(&msg.payload);
self.enc_key
.seal_in_place_separate_tag(nonce, aad, &mut payload.as_mut()[GCM_EXPLICIT_NONCE_LEN..])
.map(|tag| payload.extend_from_slice(tag.as_ref()))
.map_err(|_| Error::EncryptError)?;
Ok(OutboundOpaqueMessage::new(msg.typ, msg.version, payload))
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len + GCM_EXPLICIT_NONCE_LEN + self.enc_key.algorithm().tag_len()
}
}
/// The RFC7905/RFC7539 ChaCha20Poly1305 construction.
/// This implementation does the AAD construction required in TLS1.2.
/// TLS1.3 uses `TLS13MessageEncrypter`.
struct ChaCha20Poly1305MessageEncrypter {
enc_key: aead::LessSafeKey,
enc_offset: Iv,
}
/// The RFC7905/RFC7539 ChaCha20Poly1305 construction.
/// This implementation does the AAD construction required in TLS1.2.
/// TLS1.3 uses `TLS13MessageDecrypter`.
struct ChaCha20Poly1305MessageDecrypter {
dec_key: aead::LessSafeKey,
dec_offset: Iv,
}
const CHACHAPOLY1305_OVERHEAD: usize = 16;
impl MessageDecrypter for ChaCha20Poly1305MessageDecrypter {
fn decrypt<'a>(
&mut self,
mut msg: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, Error> {
let payload = &msg.payload;
if payload.len() < CHACHAPOLY1305_OVERHEAD {
return Err(Error::DecryptError);
}
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.dec_offset, seq).0);
let aad = aead::Aad::from(make_tls12_aad(
seq,
msg.typ,
msg.version,
payload.len() - CHACHAPOLY1305_OVERHEAD,
));
let payload = &mut msg.payload;
let plain_len = self
.dec_key
.open_in_place(nonce, aad, payload)
.map_err(|_| Error::DecryptError)?
.len();
if plain_len > MAX_FRAGMENT_LEN {
return Err(Error::PeerSentOversizedRecord);
}
payload.truncate(plain_len);
Ok(msg.into_plain_message())
}
}
impl MessageEncrypter for ChaCha20Poly1305MessageEncrypter {
fn encrypt(
&mut self,
msg: OutboundPlainMessage<'_>,
seq: u64,
) -> Result<OutboundOpaqueMessage, Error> {
let total_len = self.encrypted_payload_len(msg.payload.len());
let mut payload = PrefixedPayload::with_capacity(total_len);
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.enc_offset, seq).0);
let aad = aead::Aad::from(make_tls12_aad(seq, msg.typ, msg.version, msg.payload.len()));
payload.extend_from_chunks(&msg.payload);
self.enc_key
.seal_in_place_append_tag(nonce, aad, &mut payload)
.map_err(|_| Error::EncryptError)?;
Ok(OutboundOpaqueMessage::new(msg.typ, msg.version, payload))
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len + self.enc_key.algorithm().tag_len()
}
}
fn gcm_iv(write_iv: &[u8], explicit: &[u8]) -> Iv {
debug_assert_eq!(write_iv.len(), 4);
debug_assert_eq!(explicit.len(), 8);
// The GCM nonce is constructed from a 32-bit 'salt' derived
// from the master-secret, and a 64-bit explicit part,
// with no specified construction. Thanks for that.
//
// We use the same construction as TLS1.3/ChaCha20Poly1305:
// a starting point extracted from the key block, xored with
// the sequence number.
let mut iv = [0; NONCE_LEN];
iv[..4].copy_from_slice(write_iv);
iv[4..].copy_from_slice(explicit);
Iv::new(iv)
}
+336
View File
@@ -0,0 +1,336 @@
use alloc::boxed::Box;
use super::ring_like::hkdf::KeyType;
use super::ring_like::{aead, hkdf, hmac};
use crate::crypto;
use crate::crypto::cipher::{
AeadKey, InboundOpaqueMessage, Iv, MessageDecrypter, MessageEncrypter, Nonce,
Tls13AeadAlgorithm, UnsupportedOperationError, make_tls13_aad,
};
use crate::crypto::tls13::{Hkdf, HkdfExpander, OkmBlock, OutputLengthError};
use crate::enums::{CipherSuite, ContentType, ProtocolVersion};
use crate::error::Error;
use crate::msgs::message::{
InboundPlainMessage, OutboundOpaqueMessage, OutboundPlainMessage, PrefixedPayload,
};
use crate::suites::{CipherSuiteCommon, ConnectionTrafficSecrets, SupportedCipherSuite};
use crate::tls13::Tls13CipherSuite;
/// The TLS1.3 ciphersuite TLS_CHACHA20_POLY1305_SHA256
pub static TLS13_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls13(TLS13_CHACHA20_POLY1305_SHA256_INTERNAL);
pub(crate) static TLS13_CHACHA20_POLY1305_SHA256_INTERNAL: &Tls13CipherSuite = &Tls13CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS13_CHACHA20_POLY1305_SHA256,
hash_provider: &super::hash::SHA256,
// ref: <https://www.ietf.org/archive/id/draft-irtf-cfrg-aead-limits-08.html#section-5.2.1>
confidentiality_limit: u64::MAX,
},
hkdf_provider: &RingHkdf(hkdf::HKDF_SHA256, hmac::HMAC_SHA256),
aead_alg: &Chacha20Poly1305Aead(AeadAlgorithm(&aead::CHACHA20_POLY1305)),
quic: Some(&super::quic::KeyBuilder {
packet_alg: &aead::CHACHA20_POLY1305,
header_alg: &aead::quic::CHACHA20,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-6.6>
confidentiality_limit: u64::MAX,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-6.6>
integrity_limit: 1 << 36,
}),
};
/// The TLS1.3 ciphersuite TLS_AES_256_GCM_SHA384
pub static TLS13_AES_256_GCM_SHA384: SupportedCipherSuite =
SupportedCipherSuite::Tls13(&Tls13CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS13_AES_256_GCM_SHA384,
hash_provider: &super::hash::SHA384,
confidentiality_limit: 1 << 24,
},
hkdf_provider: &RingHkdf(hkdf::HKDF_SHA384, hmac::HMAC_SHA384),
aead_alg: &Aes256GcmAead(AeadAlgorithm(&aead::AES_256_GCM)),
quic: Some(&super::quic::KeyBuilder {
packet_alg: &aead::AES_256_GCM,
header_alg: &aead::quic::AES_256,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-b.1.1>
confidentiality_limit: 1 << 23,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-b.1.2>
integrity_limit: 1 << 52,
}),
});
/// The TLS1.3 ciphersuite TLS_AES_128_GCM_SHA256
pub static TLS13_AES_128_GCM_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls13(TLS13_AES_128_GCM_SHA256_INTERNAL);
pub(crate) static TLS13_AES_128_GCM_SHA256_INTERNAL: &Tls13CipherSuite = &Tls13CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS13_AES_128_GCM_SHA256,
hash_provider: &super::hash::SHA256,
confidentiality_limit: 1 << 24,
},
hkdf_provider: &RingHkdf(hkdf::HKDF_SHA256, hmac::HMAC_SHA256),
aead_alg: &Aes128GcmAead(AeadAlgorithm(&aead::AES_128_GCM)),
quic: Some(&super::quic::KeyBuilder {
packet_alg: &aead::AES_128_GCM,
header_alg: &aead::quic::AES_128,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-b.1.1>
confidentiality_limit: 1 << 23,
// ref: <https://datatracker.ietf.org/doc/html/rfc9001#section-b.1.2>
integrity_limit: 1 << 52,
}),
};
struct Chacha20Poly1305Aead(AeadAlgorithm);
impl Tls13AeadAlgorithm for Chacha20Poly1305Aead {
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter> {
self.0.encrypter(key, iv)
}
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter> {
self.0.decrypter(key, iv)
}
fn key_len(&self) -> usize {
self.0.key_len()
}
fn extract_keys(
&self,
key: AeadKey,
iv: Iv,
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
Ok(ConnectionTrafficSecrets::Chacha20Poly1305 { key, iv })
}
fn fips(&self) -> bool {
false // chacha20poly1305 not FIPS approved
}
}
struct Aes256GcmAead(AeadAlgorithm);
impl Tls13AeadAlgorithm for Aes256GcmAead {
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter> {
self.0.encrypter(key, iv)
}
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter> {
self.0.decrypter(key, iv)
}
fn key_len(&self) -> usize {
self.0.key_len()
}
fn extract_keys(
&self,
key: AeadKey,
iv: Iv,
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
Ok(ConnectionTrafficSecrets::Aes256Gcm { key, iv })
}
fn fips(&self) -> bool {
super::fips()
}
}
struct Aes128GcmAead(AeadAlgorithm);
impl Tls13AeadAlgorithm for Aes128GcmAead {
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter> {
self.0.encrypter(key, iv)
}
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter> {
self.0.decrypter(key, iv)
}
fn key_len(&self) -> usize {
self.0.key_len()
}
fn extract_keys(
&self,
key: AeadKey,
iv: Iv,
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
Ok(ConnectionTrafficSecrets::Aes128Gcm { key, iv })
}
fn fips(&self) -> bool {
super::fips()
}
}
// common encrypter/decrypter/key_len items for above Tls13AeadAlgorithm impls
struct AeadAlgorithm(&'static aead::Algorithm);
impl AeadAlgorithm {
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter> {
// safety: the caller arranges that `key` is `key_len()` in bytes, so this unwrap is safe.
Box::new(Tls13MessageEncrypter {
enc_key: aead::LessSafeKey::new(aead::UnboundKey::new(self.0, key.as_ref()).unwrap()),
iv,
})
}
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter> {
// safety: the caller arranges that `key` is `key_len()` in bytes, so this unwrap is safe.
Box::new(Tls13MessageDecrypter {
dec_key: aead::LessSafeKey::new(aead::UnboundKey::new(self.0, key.as_ref()).unwrap()),
iv,
})
}
fn key_len(&self) -> usize {
self.0.key_len()
}
}
struct Tls13MessageEncrypter {
enc_key: aead::LessSafeKey,
iv: Iv,
}
struct Tls13MessageDecrypter {
dec_key: aead::LessSafeKey,
iv: Iv,
}
impl MessageEncrypter for Tls13MessageEncrypter {
fn encrypt(
&mut self,
msg: OutboundPlainMessage<'_>,
seq: u64,
) -> Result<OutboundOpaqueMessage, Error> {
let total_len = self.encrypted_payload_len(msg.payload.len());
let mut payload = PrefixedPayload::with_capacity(total_len);
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, seq).0);
let aad = aead::Aad::from(make_tls13_aad(total_len));
payload.extend_from_chunks(&msg.payload);
payload.extend_from_slice(&msg.typ.to_array());
self.enc_key
.seal_in_place_append_tag(nonce, aad, &mut payload)
.map_err(|_| Error::EncryptError)?;
Ok(OutboundOpaqueMessage::new(
ContentType::ApplicationData,
// Note: all TLS 1.3 application data records use TLSv1_2 (0x0303) as the legacy record
// protocol version, see https://www.rfc-editor.org/rfc/rfc8446#section-5.1
ProtocolVersion::TLSv1_2,
payload,
))
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len + 1 + self.enc_key.algorithm().tag_len()
}
}
impl MessageDecrypter for Tls13MessageDecrypter {
fn decrypt<'a>(
&mut self,
mut msg: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, Error> {
let payload = &mut msg.payload;
if payload.len() < self.dec_key.algorithm().tag_len() {
return Err(Error::DecryptError);
}
let nonce = aead::Nonce::assume_unique_for_key(Nonce::new(&self.iv, seq).0);
let aad = aead::Aad::from(make_tls13_aad(payload.len()));
let plain_len = self
.dec_key
.open_in_place(nonce, aad, payload)
.map_err(|_| Error::DecryptError)?
.len();
payload.truncate(plain_len);
msg.into_tls13_unpadded_message()
}
}
struct RingHkdf(hkdf::Algorithm, hmac::Algorithm);
impl Hkdf for RingHkdf {
fn extract_from_zero_ikm(&self, salt: Option<&[u8]>) -> Box<dyn HkdfExpander> {
let zeroes = [0u8; OkmBlock::MAX_LEN];
let salt = match salt {
Some(salt) => salt,
None => &zeroes[..self.0.len()],
};
Box::new(RingHkdfExpander {
alg: self.0,
prk: hkdf::Salt::new(self.0, salt).extract(&zeroes[..self.0.len()]),
})
}
fn extract_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Box<dyn HkdfExpander> {
let zeroes = [0u8; OkmBlock::MAX_LEN];
let salt = match salt {
Some(salt) => salt,
None => &zeroes[..self.0.len()],
};
Box::new(RingHkdfExpander {
alg: self.0,
prk: hkdf::Salt::new(self.0, salt).extract(secret),
})
}
fn expander_for_okm(&self, okm: &OkmBlock) -> Box<dyn HkdfExpander> {
Box::new(RingHkdfExpander {
alg: self.0,
prk: hkdf::Prk::new_less_safe(self.0, okm.as_ref()),
})
}
fn hmac_sign(&self, key: &OkmBlock, message: &[u8]) -> crypto::hmac::Tag {
crypto::hmac::Tag::new(hmac::sign(&hmac::Key::new(self.1, key.as_ref()), message).as_ref())
}
fn fips(&self) -> bool {
super::fips()
}
}
struct RingHkdfExpander {
alg: hkdf::Algorithm,
prk: hkdf::Prk,
}
impl HkdfExpander for RingHkdfExpander {
fn expand_slice(&self, info: &[&[u8]], output: &mut [u8]) -> Result<(), OutputLengthError> {
self.prk
.expand(info, Len(output.len()))
.and_then(|okm| okm.fill(output))
.map_err(|_| OutputLengthError)
}
fn expand_block(&self, info: &[&[u8]]) -> OkmBlock {
let mut buf = [0u8; OkmBlock::MAX_LEN];
let output = &mut buf[..self.hash_len()];
self.prk
.expand(info, Len(output.len()))
.and_then(|okm| okm.fill(output))
.unwrap();
OkmBlock::new(output)
}
fn hash_len(&self) -> usize {
self.alg.len()
}
}
struct Len(usize);
impl KeyType for Len {
fn len(&self) -> usize {
self.0
}
}
+233
View File
@@ -0,0 +1,233 @@
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt::Debug;
use pki_types::{AlgorithmIdentifier, CertificateDer, PrivateKeyDer, SubjectPublicKeyInfoDer};
use super::CryptoProvider;
use crate::client::ResolvesClientCert;
use crate::enums::{SignatureAlgorithm, SignatureScheme};
use crate::error::{Error, InconsistentKeys};
use crate::server::{ClientHello, ParsedCertificate, ResolvesServerCert};
use crate::sync::Arc;
use crate::x509;
/// An abstract signing key.
///
/// This interface is used by rustls to use a private signing key
/// for authentication. This includes server and client authentication.
///
/// Objects of this type are always used within Rustls as
/// `Arc<dyn SigningKey>`. There are no concrete public structs in Rustls
/// that implement this trait.
///
/// There are two main ways to get a signing key:
///
/// - [`KeyProvider::load_private_key()`], or
/// - some other method outside of the `KeyProvider` extension trait,
/// for instance:
/// - [`crypto::ring::sign::any_ecdsa_type()`]
/// - [`crypto::ring::sign::any_eddsa_type()`]
/// - [`crypto::ring::sign::any_supported_type()`]
/// - [`crypto::aws_lc_rs::sign::any_ecdsa_type()`]
/// - [`crypto::aws_lc_rs::sign::any_eddsa_type()`]
/// - [`crypto::aws_lc_rs::sign::any_supported_type()`]
///
/// The `KeyProvider` method `load_private_key()` is called under the hood by
/// [`ConfigBuilder::with_single_cert()`],
/// [`ConfigBuilder::with_client_auth_cert()`], and
/// [`ConfigBuilder::with_single_cert_with_ocsp()`].
///
/// A signing key created outside of the `KeyProvider` extension trait can be used
/// to create a [`CertifiedKey`], which in turn can be used to create a
/// [`ResolvesServerCertUsingSni`]. Alternately, a `CertifiedKey` can be returned from a
/// custom implementation of the [`ResolvesServerCert`] or [`ResolvesClientCert`] traits.
///
/// [`KeyProvider::load_private_key()`]: crate::crypto::KeyProvider::load_private_key
/// [`ConfigBuilder::with_single_cert()`]: crate::ConfigBuilder::with_single_cert
/// [`ConfigBuilder::with_single_cert_with_ocsp()`]: crate::ConfigBuilder::with_single_cert_with_ocsp
/// [`ConfigBuilder::with_client_auth_cert()`]: crate::ConfigBuilder::with_client_auth_cert
/// [`crypto::ring::sign::any_ecdsa_type()`]: crate::crypto::ring::sign::any_ecdsa_type
/// [`crypto::ring::sign::any_eddsa_type()`]: crate::crypto::ring::sign::any_eddsa_type
/// [`crypto::ring::sign::any_supported_type()`]: crate::crypto::ring::sign::any_supported_type
/// [`crypto::aws_lc_rs::sign::any_ecdsa_type()`]: crate::crypto::aws_lc_rs::sign::any_ecdsa_type
/// [`crypto::aws_lc_rs::sign::any_eddsa_type()`]: crate::crypto::aws_lc_rs::sign::any_eddsa_type
/// [`crypto::aws_lc_rs::sign::any_supported_type()`]: crate::crypto::aws_lc_rs::sign::any_supported_type
/// [`ResolvesServerCertUsingSni`]: crate::server::ResolvesServerCertUsingSni
/// [`ResolvesServerCert`]: crate::server::ResolvesServerCert
/// [`ResolvesClientCert`]: crate::client::ResolvesClientCert
pub trait SigningKey: Debug + Send + Sync {
/// Choose a `SignatureScheme` from those offered.
///
/// Expresses the choice by returning something that implements `Signer`,
/// using the chosen scheme.
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>>;
/// Get the RFC 5280-compliant SubjectPublicKeyInfo (SPKI) of this [`SigningKey`] if available.
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
// Opt-out by default
None
}
/// What kind of key we have.
fn algorithm(&self) -> SignatureAlgorithm;
}
/// A thing that can sign a message.
pub trait Signer: Debug + Send + Sync {
/// Signs `message` using the selected scheme.
///
/// `message` is not hashed; the implementer must hash it using the hash function
/// implicit in [`Self::scheme()`].
///
/// The returned signature format is also defined by [`Self::scheme()`].
fn sign(&self, message: &[u8]) -> Result<Vec<u8>, Error>;
/// Reveals which scheme will be used when you call [`Self::sign()`].
fn scheme(&self) -> SignatureScheme;
}
/// Server certificate resolver which always resolves to the same certificate and key.
///
/// For use with [`ConfigBuilder::with_cert_resolver()`].
///
/// [`ConfigBuilder::with_cert_resolver()`]: crate::ConfigBuilder::with_cert_resolver
#[derive(Debug)]
pub struct SingleCertAndKey(Arc<CertifiedKey>);
impl From<CertifiedKey> for SingleCertAndKey {
fn from(certified_key: CertifiedKey) -> Self {
Self(Arc::new(certified_key))
}
}
impl From<Arc<CertifiedKey>> for SingleCertAndKey {
fn from(certified_key: Arc<CertifiedKey>) -> Self {
Self(certified_key)
}
}
impl ResolvesClientCert for SingleCertAndKey {
fn resolve(
&self,
_root_hint_subjects: &[&[u8]],
_sigschemes: &[SignatureScheme],
) -> Option<Arc<CertifiedKey>> {
Some(self.0.clone())
}
fn has_certs(&self) -> bool {
true
}
}
impl ResolvesServerCert for SingleCertAndKey {
fn resolve(&self, _client_hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
Some(self.0.clone())
}
}
/// A packaged-together certificate chain, matching `SigningKey` and
/// optional stapled OCSP response.
///
/// Note: this struct is also used to represent an [RFC 7250] raw public key,
/// when the client/server is configured to use raw public keys instead of
/// certificates.
///
/// [RFC 7250]: https://tools.ietf.org/html/rfc7250
#[derive(Clone, Debug)]
pub struct CertifiedKey {
/// The certificate chain or raw public key.
pub cert: Vec<CertificateDer<'static>>,
/// The certified key.
pub key: Arc<dyn SigningKey>,
/// An optional OCSP response from the certificate issuer,
/// attesting to its continued validity.
pub ocsp: Option<Vec<u8>>,
}
impl CertifiedKey {
/// Create a new `CertifiedKey` from a certificate chain and DER-encoded private key.
///
/// Attempt to parse the private key with the given [`CryptoProvider`]'s [`KeyProvider`] and
/// verify that it matches the public key in the first certificate of the `cert_chain`
/// if possible.
///
/// [`KeyProvider`]: crate::crypto::KeyProvider
pub fn from_der(
cert_chain: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
provider: &CryptoProvider,
) -> Result<Self, Error> {
let private_key = provider
.key_provider
.load_private_key(key)?;
let certified_key = Self::new(cert_chain, private_key);
match certified_key.keys_match() {
// Don't treat unknown consistency as an error
Ok(()) | Err(Error::InconsistentKeys(InconsistentKeys::Unknown)) => Ok(certified_key),
Err(err) => Err(err),
}
}
/// Make a new CertifiedKey, with the given chain and key.
///
/// The cert chain must not be empty. The first certificate in the chain
/// must be the end-entity certificate.
pub fn new(cert: Vec<CertificateDer<'static>>, key: Arc<dyn SigningKey>) -> Self {
Self {
cert,
key,
ocsp: None,
}
}
/// Verify the consistency of this [`CertifiedKey`]'s public and private keys.
/// This is done by performing a comparison of SubjectPublicKeyInfo bytes.
pub fn keys_match(&self) -> Result<(), Error> {
let Some(key_spki) = self.key.public_key() else {
return Err(InconsistentKeys::Unknown.into());
};
let cert = ParsedCertificate::try_from(self.end_entity_cert()?)?;
match key_spki == cert.subject_public_key_info() {
true => Ok(()),
false => Err(InconsistentKeys::KeyMismatch.into()),
}
}
/// The end-entity certificate.
pub fn end_entity_cert(&self) -> Result<&CertificateDer<'_>, Error> {
self.cert
.first()
.ok_or(Error::NoCertificatesPresented)
}
}
/// Convert a public key and algorithm identifier into [`SubjectPublicKeyInfoDer`].
pub fn public_key_to_spki(
alg_id: &AlgorithmIdentifier,
public_key: impl AsRef<[u8]>,
) -> SubjectPublicKeyInfoDer<'static> {
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
//
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL }
//
// note that the `pki_types::AlgorithmIdentifier` type is the
// concatenation of `algorithm` and `parameters`, but misses the
// outer `Sequence`.
let mut spki_inner = x509::wrap_in_sequence(alg_id.as_ref());
spki_inner.extend(&x509::wrap_in_bit_string(public_key.as_ref()));
let spki = x509::wrap_in_sequence(&spki_inner);
SubjectPublicKeyInfoDer::from(spki)
}
+169
View File
@@ -0,0 +1,169 @@
use alloc::boxed::Box;
use super::{ActiveKeyExchange, hmac};
use crate::error::Error;
use crate::version::TLS12;
/// Implements [`Prf`] using a [`hmac::Hmac`].
pub struct PrfUsingHmac<'a>(pub &'a dyn hmac::Hmac);
impl Prf for PrfUsingHmac<'_> {
fn for_key_exchange(
&self,
output: &mut [u8; 48],
kx: Box<dyn ActiveKeyExchange>,
peer_pub_key: &[u8],
label: &[u8],
seed: &[u8],
) -> Result<(), Error> {
prf(
output,
self.0
.with_key(
kx.complete_for_tls_version(peer_pub_key, &TLS12)?
.secret_bytes(),
)
.as_ref(),
label,
seed,
);
Ok(())
}
fn for_secret(&self, output: &mut [u8], secret: &[u8], label: &[u8], seed: &[u8]) {
prf(output, self.0.with_key(secret).as_ref(), label, seed);
}
}
/// An instantiation of the TLS1.2 PRF with a specific, implicit hash function.
///
/// See the definition in [RFC5246 section 5](https://www.rfc-editor.org/rfc/rfc5246#section-5).
///
/// See [`PrfUsingHmac`] as a route to implementing this trait with just
/// an implementation of [`hmac::Hmac`].
pub trait Prf: Send + Sync {
/// Computes `PRF(secret, label, seed)` using the secret from a completed key exchange.
///
/// Completes the given key exchange, and then uses the resulting shared secret
/// to compute the PRF, writing the result into `output`.
///
/// The caller guarantees that `label`, `seed` are non-empty. The caller makes no
/// guarantees about the contents of `peer_pub_key`. It must be validated by
/// [`ActiveKeyExchange::complete`].
fn for_key_exchange(
&self,
output: &mut [u8; 48],
kx: Box<dyn ActiveKeyExchange>,
peer_pub_key: &[u8],
label: &[u8],
seed: &[u8],
) -> Result<(), Error>;
/// Computes `PRF(secret, label, seed)`, writing the result into `output`.
///
/// The caller guarantees that `secret`, `label`, and `seed` are non-empty.
fn for_secret(&self, output: &mut [u8], secret: &[u8], label: &[u8], seed: &[u8]);
/// Return `true` if this is backed by a FIPS-approved implementation.
fn fips(&self) -> bool {
false
}
}
pub(crate) fn prf(out: &mut [u8], hmac_key: &dyn hmac::Key, label: &[u8], seed: &[u8]) {
// A(1)
let mut current_a = hmac_key.sign(&[label, seed]);
let chunk_size = hmac_key.tag_len();
for chunk in out.chunks_mut(chunk_size) {
// P_hash[i] = HMAC_hash(secret, A(i) + seed)
let p_term = hmac_key.sign(&[current_a.as_ref(), label, seed]);
chunk.copy_from_slice(&p_term.as_ref()[..chunk.len()]);
// A(i+1) = HMAC_hash(secret, A(i))
current_a = hmac_key.sign(&[current_a.as_ref()]);
}
}
#[cfg(all(test, feature = "ring"))]
mod tests {
use crate::crypto::hmac::Hmac;
// nb: crypto::aws_lc_rs provider doesn't provide (or need) hmac,
// so cannot be used for this test.
use crate::crypto::ring::hmac;
// Below known answer tests come from https://mailarchive.ietf.org/arch/msg/tls/fzVCzk-z3FShgGJ6DOXqM1ydxms/
#[test]
fn check_sha256() {
let secret = b"\x9b\xbe\x43\x6b\xa9\x40\xf0\x17\xb1\x76\x52\x84\x9a\x71\xdb\x35";
let seed = b"\xa0\xba\x9f\x93\x6c\xda\x31\x18\x27\xa6\xf7\x96\xff\xd5\x19\x8c";
let label = b"test label";
let expect = include_bytes!("../testdata/prf-result.1.bin");
let mut output = [0u8; 100];
super::prf(
&mut output,
&*hmac::HMAC_SHA256.with_key(secret),
label,
seed,
);
assert_eq!(expect.len(), output.len());
assert_eq!(expect.to_vec(), output.to_vec());
}
#[test]
fn check_sha512() {
let secret = b"\xb0\x32\x35\x23\xc1\x85\x35\x99\x58\x4d\x88\x56\x8b\xbb\x05\xeb";
let seed = b"\xd4\x64\x0e\x12\xe4\xbc\xdb\xfb\x43\x7f\x03\xe6\xae\x41\x8e\xe5";
let label = b"test label";
let expect = include_bytes!("../testdata/prf-result.2.bin");
let mut output = [0u8; 196];
super::prf(
&mut output,
&*hmac::HMAC_SHA512.with_key(secret),
label,
seed,
);
assert_eq!(expect.len(), output.len());
assert_eq!(expect.to_vec(), output.to_vec());
}
#[test]
fn check_sha384() {
let secret = b"\xb8\x0b\x73\x3d\x6c\xee\xfc\xdc\x71\x56\x6e\xa4\x8e\x55\x67\xdf";
let seed = b"\xcd\x66\x5c\xf6\xa8\x44\x7d\xd6\xff\x8b\x27\x55\x5e\xdb\x74\x65";
let label = b"test label";
let expect = include_bytes!("../testdata/prf-result.3.bin");
let mut output = [0u8; 148];
super::prf(
&mut output,
&*hmac::HMAC_SHA384.with_key(secret),
label,
seed,
);
assert_eq!(expect.len(), output.len());
assert_eq!(expect.to_vec(), output.to_vec());
}
}
#[cfg(all(bench, feature = "ring"))]
mod benchmarks {
#[bench]
fn bench_sha256(b: &mut test::Bencher) {
use crate::crypto::hmac::Hmac;
use crate::crypto::ring::hmac;
let label = &b"extended master secret"[..];
let seed = [0u8; 32];
let key = &b"secret"[..];
b.iter(|| {
let mut out = [0u8; 48];
super::prf(&mut out, &*hmac::HMAC_SHA256.with_key(key), &label, &seed);
test::black_box(out);
});
}
}
+406
View File
@@ -0,0 +1,406 @@
use alloc::boxed::Box;
use alloc::vec::Vec;
use zeroize::Zeroize;
use super::{ActiveKeyExchange, hmac};
use crate::error::Error;
use crate::version::TLS13;
/// Implementation of `HkdfExpander` via `hmac::Key`.
pub struct HkdfExpanderUsingHmac(Box<dyn hmac::Key>);
impl HkdfExpanderUsingHmac {
fn expand_unchecked(&self, info: &[&[u8]], output: &mut [u8]) {
let mut term = hmac::Tag::new(b"");
for (n, chunk) in output
.chunks_mut(self.0.tag_len())
.enumerate()
{
term = self
.0
.sign_concat(term.as_ref(), info, &[(n + 1) as u8]);
chunk.copy_from_slice(&term.as_ref()[..chunk.len()]);
}
}
}
impl HkdfExpander for HkdfExpanderUsingHmac {
fn expand_slice(&self, info: &[&[u8]], output: &mut [u8]) -> Result<(), OutputLengthError> {
if output.len() > 255 * self.0.tag_len() {
return Err(OutputLengthError);
}
self.expand_unchecked(info, output);
Ok(())
}
fn expand_block(&self, info: &[&[u8]]) -> OkmBlock {
let mut tag = [0u8; hmac::Tag::MAX_LEN];
let reduced_tag = &mut tag[..self.0.tag_len()];
self.expand_unchecked(info, reduced_tag);
OkmBlock::new(reduced_tag)
}
fn hash_len(&self) -> usize {
self.0.tag_len()
}
}
/// Implementation of `Hkdf` (and thence `HkdfExpander`) via `hmac::Hmac`.
pub struct HkdfUsingHmac<'a>(pub &'a dyn hmac::Hmac);
impl Hkdf for HkdfUsingHmac<'_> {
fn extract_from_zero_ikm(&self, salt: Option<&[u8]>) -> Box<dyn HkdfExpander> {
let zeroes = [0u8; hmac::Tag::MAX_LEN];
Box::new(HkdfExpanderUsingHmac(self.0.with_key(
&self.extract_prk_from_secret(salt, &zeroes[..self.0.hash_output_len()]),
)))
}
fn extract_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Box<dyn HkdfExpander> {
Box::new(HkdfExpanderUsingHmac(
self.0
.with_key(&self.extract_prk_from_secret(salt, secret)),
))
}
fn expander_for_okm(&self, okm: &OkmBlock) -> Box<dyn HkdfExpander> {
Box::new(HkdfExpanderUsingHmac(self.0.with_key(okm.as_ref())))
}
fn hmac_sign(&self, key: &OkmBlock, message: &[u8]) -> hmac::Tag {
self.0
.with_key(key.as_ref())
.sign(&[message])
}
}
impl HkdfPrkExtract for HkdfUsingHmac<'_> {
fn extract_prk_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Vec<u8> {
let zeroes = [0u8; hmac::Tag::MAX_LEN];
let salt = match salt {
Some(salt) => salt,
None => &zeroes[..self.0.hash_output_len()],
};
self.0
.with_key(salt)
.sign(&[secret])
.as_ref()
.to_vec()
}
}
/// Implementation of `HKDF-Expand` with an implicitly stored and immutable `PRK`.
pub trait HkdfExpander: Send + Sync {
/// `HKDF-Expand(PRK, info, L)` into a slice.
///
/// Where:
///
/// - `PRK` is the implicit key material represented by this instance.
/// - `L` is `output.len()`.
/// - `info` is a slice of byte slices, which should be processed sequentially
/// (or concatenated if that is not possible).
///
/// Returns `Err(OutputLengthError)` if `L` is larger than `255 * HashLen`.
/// Otherwise, writes to `output`.
fn expand_slice(&self, info: &[&[u8]], output: &mut [u8]) -> Result<(), OutputLengthError>;
/// `HKDF-Expand(PRK, info, L=HashLen)` returned as a value.
///
/// - `PRK` is the implicit key material represented by this instance.
/// - `L := HashLen`.
/// - `info` is a slice of byte slices, which should be processed sequentially
/// (or concatenated if that is not possible).
///
/// This is infallible, because by definition `OkmBlock` is always exactly
/// `HashLen` bytes long.
fn expand_block(&self, info: &[&[u8]]) -> OkmBlock;
/// Return what `HashLen` is for this instance.
///
/// This must be no larger than [`OkmBlock::MAX_LEN`].
fn hash_len(&self) -> usize;
}
/// A HKDF implementation oriented to the needs of TLS1.3.
///
/// See [RFC5869](https://datatracker.ietf.org/doc/html/rfc5869) for the terminology
/// used in this definition.
///
/// You can use [`HkdfUsingHmac`] which implements this trait on top of an implementation
/// of [`hmac::Hmac`].
pub trait Hkdf: Send + Sync {
/// `HKDF-Extract(salt, 0_HashLen)`
///
/// `0_HashLen` is a string of `HashLen` zero bytes.
///
/// A `salt` of `None` should be treated as a sequence of `HashLen` zero bytes.
fn extract_from_zero_ikm(&self, salt: Option<&[u8]>) -> Box<dyn HkdfExpander>;
/// `HKDF-Extract(salt, secret)`
///
/// A `salt` of `None` should be treated as a sequence of `HashLen` zero bytes.
fn extract_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Box<dyn HkdfExpander>;
/// `HKDF-Extract(salt, shared_secret)` where `shared_secret` is the result of a key exchange.
///
/// Custom implementations should complete the key exchange by calling
/// `kx.complete(peer_pub_key)` and then using this as the input keying material to
/// `HKDF-Extract`.
///
/// A `salt` of `None` should be treated as a sequence of `HashLen` zero bytes.
fn extract_from_kx_shared_secret(
&self,
salt: Option<&[u8]>,
kx: Box<dyn ActiveKeyExchange>,
peer_pub_key: &[u8],
) -> Result<Box<dyn HkdfExpander>, Error> {
Ok(self.extract_from_secret(
salt,
kx.complete_for_tls_version(peer_pub_key, &TLS13)?
.secret_bytes(),
))
}
/// Build a `HkdfExpander` using `okm` as the secret PRK.
fn expander_for_okm(&self, okm: &OkmBlock) -> Box<dyn HkdfExpander>;
/// Signs `message` using `key` viewed as a HMAC key.
///
/// This should use the same hash function as the HKDF functions in this
/// trait.
///
/// See [RFC2104](https://datatracker.ietf.org/doc/html/rfc2104) for the
/// definition of HMAC.
fn hmac_sign(&self, key: &OkmBlock, message: &[u8]) -> hmac::Tag;
/// Return `true` if this is backed by a FIPS-approved implementation.
fn fips(&self) -> bool {
false
}
}
/// An extended HKDF implementation that supports directly extracting a pseudo-random key (PRK).
///
/// The base [`Hkdf`] trait is tailored to the needs of TLS 1.3, where all extracted PRKs
/// are expanded as-is, and so can be safely encapsulated without exposing the caller
/// to the key material.
///
/// In other contexts (for example, hybrid public key encryption (HPKE)) it may be necessary
/// to use the extracted PRK directly for purposes other than an immediate expansion.
/// This trait can be implemented to offer this functionality when it is required.
pub(crate) trait HkdfPrkExtract: Hkdf {
/// `HKDF-Extract(salt, secret)`
///
/// A `salt` of `None` should be treated as a sequence of `HashLen` zero bytes.
///
/// In most cases you should prefer [`Hkdf::extract_from_secret`] and using the
/// returned [HkdfExpander] instead of handling the PRK directly.
fn extract_prk_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Vec<u8>;
}
/// `HKDF-Expand(PRK, info, L)` to construct any type from a byte array.
///
/// - `PRK` is the implicit key material represented by this instance.
/// - `L := N`; N is the size of the byte array.
/// - `info` is a slice of byte slices, which should be processed sequentially
/// (or concatenated if that is not possible).
///
/// This is infallible, because the set of types (and therefore their length) is known
/// at compile time.
pub fn expand<T, const N: usize>(expander: &dyn HkdfExpander, info: &[&[u8]]) -> T
where
T: From<[u8; N]>,
{
let mut output = [0u8; N];
expander
.expand_slice(info, &mut output)
.expect("expand type parameter T is too large");
T::from(output)
}
/// Output key material from HKDF, as a value type.
#[derive(Clone)]
pub struct OkmBlock {
buf: [u8; Self::MAX_LEN],
used: usize,
}
impl OkmBlock {
/// Build a single OKM block by copying a byte slice.
///
/// The slice can be up to [`OkmBlock::MAX_LEN`] bytes in length.
pub fn new(bytes: &[u8]) -> Self {
let mut tag = Self {
buf: [0u8; Self::MAX_LEN],
used: bytes.len(),
};
tag.buf[..bytes.len()].copy_from_slice(bytes);
tag
}
/// Maximum supported HMAC tag size: supports up to SHA512.
pub const MAX_LEN: usize = 64;
}
impl Drop for OkmBlock {
fn drop(&mut self) {
self.buf.zeroize();
}
}
impl AsRef<[u8]> for OkmBlock {
fn as_ref(&self) -> &[u8] {
&self.buf[..self.used]
}
}
/// An error type used for `HkdfExpander::expand_slice` when
/// the slice exceeds the maximum HKDF output length.
#[derive(Debug)]
pub struct OutputLengthError;
#[cfg(all(test, feature = "ring"))]
mod tests {
use std::prelude::v1::*;
use super::{Hkdf, HkdfUsingHmac, expand};
// nb: crypto::aws_lc_rs provider doesn't provide (or need) hmac,
// so cannot be used for this test.
use crate::crypto::ring::hmac;
struct ByteArray<const N: usize>([u8; N]);
impl<const N: usize> From<[u8; N]> for ByteArray<N> {
fn from(array: [u8; N]) -> Self {
Self(array)
}
}
/// Test cases from appendix A in the RFC, minus cases requiring SHA1.
#[test]
fn test_case_1() {
let hkdf = HkdfUsingHmac(&hmac::HMAC_SHA256);
let ikm = &[0x0b; 22];
let salt = &[
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
];
let info: &[&[u8]] = &[
&[0xf0, 0xf1, 0xf2],
&[0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9],
];
let output: ByteArray<42> = expand(
hkdf.extract_from_secret(Some(salt), ikm)
.as_ref(),
info,
);
assert_eq!(
&output.0,
&[
0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36,
0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56,
0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65
]
);
}
#[test]
fn test_case_2() {
let hkdf = HkdfUsingHmac(&hmac::HMAC_SHA256);
let ikm: Vec<u8> = (0x00u8..=0x4f).collect();
let salt: Vec<u8> = (0x60u8..=0xaf).collect();
let info: Vec<u8> = (0xb0u8..=0xff).collect();
let output: ByteArray<82> = expand(
hkdf.extract_from_secret(Some(&salt), &ikm)
.as_ref(),
&[&info],
);
assert_eq!(
&output.0,
&[
0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 0xf7, 0x8c, 0x59, 0x6a,
0x49, 0x34, 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c,
0x19, 0xaf, 0xa9, 0x7c, 0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb,
0x41, 0xc6, 0x5e, 0x59, 0x0e, 0x09, 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8,
0x36, 0x77, 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec,
0x3e, 0x87, 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x1d, 0x87
]
);
}
#[test]
fn test_case_3() {
let hkdf = HkdfUsingHmac(&hmac::HMAC_SHA256);
let ikm = &[0x0b; 22];
let salt = &[];
let info = &[];
let output: ByteArray<42> = expand(
hkdf.extract_from_secret(Some(salt), ikm)
.as_ref(),
info,
);
assert_eq!(
&output.0,
&[
0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f, 0x80, 0x2a, 0x06, 0x3c,
0x5a, 0x31, 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f,
0x3c, 0x73, 0x8d, 0x2d, 0x9d, 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0xc8
]
);
}
#[test]
fn test_salt_not_provided() {
// can't use test case 7, because we don't have (or want) SHA1.
//
// this output is generated with cryptography.io:
//
// >>> hkdf.HKDF(algorithm=hashes.SHA384(), length=96, salt=None, info=b"hello").derive(b"\x0b" * 40)
let hkdf = HkdfUsingHmac(&hmac::HMAC_SHA384);
let ikm = &[0x0b; 40];
let info = &[&b"hel"[..], &b"lo"[..]];
let output: ByteArray<96> = expand(
hkdf.extract_from_secret(None, ikm)
.as_ref(),
info,
);
assert_eq!(
&output.0,
&[
0xd5, 0x45, 0xdd, 0x3a, 0xff, 0x5b, 0x19, 0x46, 0xd4, 0x86, 0xfd, 0xb8, 0xd8, 0x88,
0x2e, 0xe0, 0x1c, 0xc1, 0xa5, 0x48, 0xb6, 0x05, 0x75, 0xe4, 0xd7, 0x5d, 0x0f, 0x5f,
0x23, 0x40, 0xee, 0x6c, 0x9e, 0x7c, 0x65, 0xd0, 0xee, 0x79, 0xdb, 0xb2, 0x07, 0x1d,
0x66, 0xa5, 0x50, 0xc4, 0x8a, 0xa3, 0x93, 0x86, 0x8b, 0x7c, 0x69, 0x41, 0x6b, 0x3e,
0x61, 0x44, 0x98, 0xb8, 0xc2, 0xfc, 0x82, 0x82, 0xae, 0xcd, 0x46, 0xcf, 0xb1, 0x47,
0xdc, 0xd0, 0x69, 0x0d, 0x19, 0xad, 0xe6, 0x6c, 0x70, 0xfe, 0x87, 0x92, 0x04, 0xb6,
0x82, 0x2d, 0x97, 0x7e, 0x46, 0x80, 0x4c, 0xe5, 0x76, 0x72, 0xb4, 0xb8
]
);
}
#[test]
fn test_output_length_bounds() {
let hkdf = HkdfUsingHmac(&hmac::HMAC_SHA256);
let ikm = &[];
let info = &[];
let mut output = [0u8; 32 * 255 + 1];
assert!(
hkdf.extract_from_secret(None, ikm)
.expand_slice(info, &mut output)
.is_err()
);
}
}