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
+133
View File
@@ -0,0 +1,133 @@
use alloc::vec::Vec;
use core::marker::PhantomData;
use pki_types::{CertificateDer, PrivateKeyDer};
use super::{ResolvesServerCert, ServerConfig, handy};
use crate::builder::{ConfigBuilder, WantsVerifier};
use crate::error::Error;
use crate::sign::{CertifiedKey, SingleCertAndKey};
use crate::sync::Arc;
use crate::verify::{ClientCertVerifier, NoClientAuth};
use crate::{NoKeyLog, compress, versions};
impl ConfigBuilder<ServerConfig, WantsVerifier> {
/// Choose how to verify client certificates.
pub fn with_client_cert_verifier(
self,
client_cert_verifier: Arc<dyn ClientCertVerifier>,
) -> ConfigBuilder<ServerConfig, WantsServerCert> {
ConfigBuilder {
state: WantsServerCert {
versions: self.state.versions,
verifier: client_cert_verifier,
},
provider: self.provider,
time_provider: self.time_provider,
side: PhantomData,
}
}
/// Disable client authentication.
pub fn with_no_client_auth(self) -> ConfigBuilder<ServerConfig, WantsServerCert> {
self.with_client_cert_verifier(Arc::new(NoClientAuth))
}
}
/// A config builder state where the caller must supply how to provide a server certificate to
/// the connecting peer.
///
/// For more information, see the [`ConfigBuilder`] documentation.
#[derive(Clone, Debug)]
pub struct WantsServerCert {
versions: versions::EnabledVersions,
verifier: Arc<dyn ClientCertVerifier>,
}
impl ConfigBuilder<ServerConfig, WantsServerCert> {
/// Sets a single certificate chain and matching private key. This
/// certificate and key is used for all subsequent connections,
/// irrespective of things like SNI hostname.
///
/// Note that the end-entity certificate must have the
/// [Subject Alternative Name](https://tools.ietf.org/html/rfc6125#section-4.1)
/// extension to describe, e.g., the valid DNS name. The `commonName` field is
/// disregarded.
///
/// `cert_chain` is a vector of DER-encoded certificates.
/// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
/// `aws-lc-rs` and `ring` [`CryptoProvider`][crate::CryptoProvider]s support
/// all three encodings, but other `CryptoProviders` may not.
///
/// This function fails if `key_der` is invalid, or if the
/// `SubjectPublicKeyInfo` from the private key does not match the public
/// key for the end-entity certificate from the `cert_chain`.
pub fn with_single_cert(
self,
cert_chain: Vec<CertificateDer<'static>>,
key_der: PrivateKeyDer<'static>,
) -> Result<ServerConfig, Error> {
let certified_key = CertifiedKey::from_der(cert_chain, key_der, self.crypto_provider())?;
Ok(self.with_cert_resolver(Arc::new(SingleCertAndKey::from(certified_key))))
}
/// Sets a single certificate chain, matching private key and optional OCSP
/// response. This certificate and key is used for all
/// subsequent connections, irrespective of things like SNI hostname.
///
/// `cert_chain` is a vector of DER-encoded certificates.
/// `key_der` is a DER-encoded private key as PKCS#1, PKCS#8, or SEC1. The
/// `aws-lc-rs` and `ring` [`CryptoProvider`][crate::CryptoProvider]s support
/// all three encodings, but other `CryptoProviders` may not.
/// `ocsp` is a DER-encoded OCSP response. Ignored if zero length.
///
/// This function fails if `key_der` is invalid, or if the
/// `SubjectPublicKeyInfo` from the private key does not match the public
/// key for the end-entity certificate from the `cert_chain`.
pub fn with_single_cert_with_ocsp(
self,
cert_chain: Vec<CertificateDer<'static>>,
key_der: PrivateKeyDer<'static>,
ocsp: Vec<u8>,
) -> Result<ServerConfig, Error> {
let mut certified_key =
CertifiedKey::from_der(cert_chain, key_der, self.crypto_provider())?;
if !ocsp.is_empty() {
certified_key.ocsp = Some(ocsp);
}
Ok(self.with_cert_resolver(Arc::new(SingleCertAndKey::from(certified_key))))
}
/// Sets a custom [`ResolvesServerCert`].
pub fn with_cert_resolver(self, cert_resolver: Arc<dyn ResolvesServerCert>) -> ServerConfig {
#[cfg(feature = "tls12")]
let require_ems = self.provider.fips();
ServerConfig {
provider: self.provider,
verifier: self.state.verifier,
cert_resolver,
ignore_client_order: false,
max_fragment_size: None,
#[cfg(feature = "std")]
session_storage: handy::ServerSessionMemoryCache::new(256),
#[cfg(not(feature = "std"))]
session_storage: Arc::new(handy::NoServerSessionStorage {}),
ticketer: Arc::new(handy::NeverProducesTickets {}),
alpn_protocols: Vec::new(),
versions: self.state.versions,
key_log: Arc::new(NoKeyLog {}),
enable_secret_extraction: false,
max_early_data_size: 0,
send_half_rtt_data: false,
send_tls13_tickets: 2,
max_tls13_tickets: 0,
#[cfg(feature = "tls12")]
require_ems,
time_provider: self.time_provider,
cert_compressors: compress::default_cert_compressors().to_vec(),
cert_compression_cache: Arc::new(compress::CompressionCache::default()),
cert_decompressors: compress::default_cert_decompressors().to_vec(),
}
}
}
+35
View File
@@ -0,0 +1,35 @@
use pki_types::CertificateDer;
use crate::sign;
/// ActiveCertifiedKey wraps [`sign::CertifiedKey`] and tracks OSCP state in a single handshake.
pub(super) struct ActiveCertifiedKey<'a> {
key: &'a sign::CertifiedKey,
ocsp: Option<&'a [u8]>,
}
impl ActiveCertifiedKey<'_> {
pub(super) fn from_certified_key(key: &sign::CertifiedKey) -> ActiveCertifiedKey<'_> {
ActiveCertifiedKey {
key,
ocsp: key.ocsp.as_deref(),
}
}
/// Get the certificate chain
#[inline]
pub(super) fn get_cert(&self) -> &[CertificateDer<'static>] {
&self.key.cert
}
/// Get the signing key
#[inline]
pub(super) fn get_key(&self) -> &dyn sign::SigningKey {
&*self.key.key
}
#[inline]
pub(super) fn get_ocsp(&self) -> Option<&[u8]> {
self.ocsp
}
}
+356
View File
@@ -0,0 +1,356 @@
use alloc::vec::Vec;
use core::fmt::Debug;
use crate::server::ClientHello;
use crate::sync::Arc;
use crate::{server, sign};
/// Something which never stores sessions.
#[derive(Debug)]
pub struct NoServerSessionStorage {}
impl server::StoresServerSessions for NoServerSessionStorage {
fn put(&self, _id: Vec<u8>, _sec: Vec<u8>) -> bool {
false
}
fn get(&self, _id: &[u8]) -> Option<Vec<u8>> {
None
}
fn take(&self, _id: &[u8]) -> Option<Vec<u8>> {
None
}
fn can_cache(&self) -> bool {
false
}
}
#[cfg(any(feature = "std", feature = "hashbrown"))]
mod cache {
use alloc::vec::Vec;
use core::fmt::{Debug, Formatter};
use crate::lock::Mutex;
use crate::sync::Arc;
use crate::{limited_cache, server};
/// An implementer of `StoresServerSessions` that stores everything
/// in memory. If enforces a limit on the number of stored sessions
/// to bound memory usage.
pub struct ServerSessionMemoryCache {
cache: Mutex<limited_cache::LimitedCache<Vec<u8>, Vec<u8>>>,
}
impl ServerSessionMemoryCache {
/// Make a new ServerSessionMemoryCache. `size` is the maximum
/// number of stored sessions, and may be rounded-up for
/// efficiency.
#[cfg(feature = "std")]
pub fn new(size: usize) -> Arc<Self> {
Arc::new(Self {
cache: Mutex::new(limited_cache::LimitedCache::new(size)),
})
}
/// Make a new ServerSessionMemoryCache. `size` is the maximum
/// number of stored sessions, and may be rounded-up for
/// efficiency.
#[cfg(not(feature = "std"))]
pub fn new<M: crate::lock::MakeMutex>(size: usize) -> Arc<Self> {
Arc::new(Self {
cache: Mutex::new::<M>(limited_cache::LimitedCache::new(size)),
})
}
}
impl server::StoresServerSessions for ServerSessionMemoryCache {
fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool {
self.cache
.lock()
.unwrap()
.insert(key, value);
true
}
fn get(&self, key: &[u8]) -> Option<Vec<u8>> {
self.cache
.lock()
.unwrap()
.get(key)
.cloned()
}
fn take(&self, key: &[u8]) -> Option<Vec<u8>> {
self.cache.lock().unwrap().remove(key)
}
fn can_cache(&self) -> bool {
true
}
}
impl Debug for ServerSessionMemoryCache {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ServerSessionMemoryCache")
.finish()
}
}
#[cfg(test)]
mod tests {
use std::vec;
use super::*;
use crate::server::StoresServerSessions;
#[test]
fn test_serversessionmemorycache_accepts_put() {
let c = ServerSessionMemoryCache::new(4);
assert!(c.put(vec![0x01], vec![0x02]));
}
#[test]
fn test_serversessionmemorycache_persists_put() {
let c = ServerSessionMemoryCache::new(4);
assert!(c.put(vec![0x01], vec![0x02]));
assert_eq!(c.get(&[0x01]), Some(vec![0x02]));
assert_eq!(c.get(&[0x01]), Some(vec![0x02]));
}
#[test]
fn test_serversessionmemorycache_overwrites_put() {
let c = ServerSessionMemoryCache::new(4);
assert!(c.put(vec![0x01], vec![0x02]));
assert!(c.put(vec![0x01], vec![0x04]));
assert_eq!(c.get(&[0x01]), Some(vec![0x04]));
}
#[test]
fn test_serversessionmemorycache_drops_to_maintain_size_invariant() {
let c = ServerSessionMemoryCache::new(2);
assert!(c.put(vec![0x01], vec![0x02]));
assert!(c.put(vec![0x03], vec![0x04]));
assert!(c.put(vec![0x05], vec![0x06]));
assert!(c.put(vec![0x07], vec![0x08]));
assert!(c.put(vec![0x09], vec![0x0a]));
let count = c.get(&[0x01]).iter().count()
+ c.get(&[0x03]).iter().count()
+ c.get(&[0x05]).iter().count()
+ c.get(&[0x07]).iter().count()
+ c.get(&[0x09]).iter().count();
assert!(count < 5);
}
}
}
#[cfg(any(feature = "std", feature = "hashbrown"))]
pub use cache::ServerSessionMemoryCache;
/// Something which never produces tickets.
#[derive(Debug)]
pub(super) struct NeverProducesTickets {}
impl server::ProducesTickets for NeverProducesTickets {
fn enabled(&self) -> bool {
false
}
fn lifetime(&self) -> u32 {
0
}
fn encrypt(&self, _bytes: &[u8]) -> Option<Vec<u8>> {
None
}
fn decrypt(&self, _bytes: &[u8]) -> Option<Vec<u8>> {
None
}
}
/// An exemplar `ResolvesServerCert` implementation that always resolves to a single
/// [RFC 7250] raw public key.
///
/// [RFC 7250]: https://tools.ietf.org/html/rfc7250
#[derive(Clone, Debug)]
pub struct AlwaysResolvesServerRawPublicKeys(Arc<sign::CertifiedKey>);
impl AlwaysResolvesServerRawPublicKeys {
/// Create a new `AlwaysResolvesServerRawPublicKeys` instance.
pub fn new(certified_key: Arc<sign::CertifiedKey>) -> Self {
Self(certified_key)
}
}
impl server::ResolvesServerCert for AlwaysResolvesServerRawPublicKeys {
fn resolve(&self, _client_hello: ClientHello<'_>) -> Option<Arc<sign::CertifiedKey>> {
Some(self.0.clone())
}
fn only_raw_public_keys(&self) -> bool {
true
}
}
#[cfg(any(feature = "std", feature = "hashbrown"))]
mod sni_resolver {
use alloc::string::{String, ToString};
use core::fmt::Debug;
use pki_types::{DnsName, ServerName};
use crate::error::Error;
use crate::hash_map::HashMap;
use crate::server::ClientHello;
use crate::sync::Arc;
use crate::webpki::{ParsedCertificate, verify_server_name};
use crate::{server, sign};
/// Something that resolves do different cert chains/keys based
/// on client-supplied server name (via SNI).
#[derive(Debug)]
pub struct ResolvesServerCertUsingSni {
by_name: HashMap<String, Arc<sign::CertifiedKey>>,
}
impl ResolvesServerCertUsingSni {
/// Create a new and empty (i.e., knows no certificates) resolver.
pub fn new() -> Self {
Self {
by_name: HashMap::new(),
}
}
/// Add a new `sign::CertifiedKey` to be used for the given SNI `name`.
///
/// This function fails if `name` is not a valid DNS name, or if
/// it's not valid for the supplied certificate, or if the certificate
/// chain is syntactically faulty.
pub fn add(&mut self, name: &str, ck: sign::CertifiedKey) -> Result<(), Error> {
let server_name = {
let checked_name = DnsName::try_from(name)
.map_err(|_| Error::General("Bad DNS name".into()))
.map(|name| name.to_lowercase_owned())?;
ServerName::DnsName(checked_name)
};
// Check the certificate chain for validity:
// - it should be non-empty list
// - the first certificate should be parsable as a x509v3,
// - the first certificate should quote the given server name
// (if provided)
//
// These checks are not security-sensitive. They are the
// *server* attempting to detect accidental misconfiguration.
ck.end_entity_cert()
.and_then(ParsedCertificate::try_from)
.and_then(|cert| verify_server_name(&cert, &server_name))?;
if let ServerName::DnsName(name) = server_name {
self.by_name
.insert(name.as_ref().to_string(), Arc::new(ck));
}
Ok(())
}
}
impl server::ResolvesServerCert for ResolvesServerCertUsingSni {
fn resolve(&self, client_hello: ClientHello<'_>) -> Option<Arc<sign::CertifiedKey>> {
if let Some(name) = client_hello.server_name() {
self.by_name.get(name).cloned()
} else {
// This kind of resolver requires SNI
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::server::ResolvesServerCert;
#[test]
fn test_resolvesservercertusingsni_requires_sni() {
let rscsni = ResolvesServerCertUsingSni::new();
assert!(
rscsni
.resolve(ClientHello {
server_name: &None,
signature_schemes: &[],
alpn: None,
server_cert_types: None,
client_cert_types: None,
cipher_suites: &[],
certificate_authorities: None,
named_groups: None,
})
.is_none()
);
}
#[test]
fn test_resolvesservercertusingsni_handles_unknown_name() {
let rscsni = ResolvesServerCertUsingSni::new();
let name = DnsName::try_from("hello.com")
.unwrap()
.to_owned();
assert!(
rscsni
.resolve(ClientHello {
server_name: &Some(name),
signature_schemes: &[],
alpn: None,
server_cert_types: None,
client_cert_types: None,
cipher_suites: &[],
certificate_authorities: None,
named_groups: None,
})
.is_none()
);
}
}
}
#[cfg(any(feature = "std", feature = "hashbrown"))]
pub use sni_resolver::ResolvesServerCertUsingSni;
#[cfg(test)]
mod tests {
use std::vec;
use super::*;
use crate::server::{ProducesTickets, StoresServerSessions};
#[test]
fn test_noserversessionstorage_drops_put() {
let c = NoServerSessionStorage {};
assert!(!c.put(vec![0x01], vec![0x02]));
}
#[test]
fn test_noserversessionstorage_denies_gets() {
let c = NoServerSessionStorage {};
c.put(vec![0x01], vec![0x02]);
assert_eq!(c.get(&[]), None);
assert_eq!(c.get(&[0x01]), None);
assert_eq!(c.get(&[0x02]), None);
}
#[test]
fn test_noserversessionstorage_denies_takes() {
let c = NoServerSessionStorage {};
assert_eq!(c.take(&[]), None);
assert_eq!(c.take(&[0x01]), None);
assert_eq!(c.take(&[0x02]), None);
}
#[test]
fn test_neverproducestickets_does_nothing() {
let npt = NeverProducesTickets {};
assert!(!npt.enabled());
assert_eq!(0, npt.lifetime());
assert_eq!(None, npt.encrypt(&[]));
assert_eq!(None, npt.decrypt(&[]));
}
}
+785
View File
@@ -0,0 +1,785 @@
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::vec::Vec;
use pki_types::DnsName;
use super::server_conn::ServerConnectionData;
#[cfg(feature = "tls12")]
use super::tls12;
use crate::common_state::{KxState, Protocol, State};
use crate::conn::ConnectionRandoms;
use crate::crypto::SupportedKxGroup;
use crate::enums::{
AlertDescription, CertificateType, CipherSuite, HandshakeType, ProtocolVersion,
SignatureAlgorithm, SignatureScheme,
};
use crate::error::{Error, PeerIncompatible, PeerMisbehaved};
use crate::hash_hs::{HandshakeHash, HandshakeHashBuffer};
use crate::log::{debug, trace};
use crate::msgs::enums::{Compression, ExtensionType, NamedGroup};
#[cfg(feature = "tls12")]
use crate::msgs::handshake::SessionId;
use crate::msgs::handshake::{
ClientHelloPayload, HandshakePayload, KeyExchangeAlgorithm, ProtocolName, Random,
ServerExtensions, ServerExtensionsInput, ServerNamePayload, SingleProtocolName,
TransportParameters,
};
use crate::msgs::message::{Message, MessagePayload};
use crate::msgs::persist;
use crate::server::common::ActiveCertifiedKey;
use crate::server::{ClientHello, ServerConfig, tls13};
use crate::sync::Arc;
use crate::{SupportedCipherSuite, suites};
pub(super) type NextState<'a> = Box<dyn State<ServerConnectionData> + 'a>;
pub(super) type NextStateOrError<'a> = Result<NextState<'a>, Error>;
pub(super) type ServerContext<'a> = crate::common_state::Context<'a, ServerConnectionData>;
pub(super) fn can_resume(
suite: SupportedCipherSuite,
sni: &Option<DnsName<'_>>,
using_ems: bool,
resumedata: &persist::ServerSessionValue,
) -> bool {
// The RFCs underspecify what happens if we try to resume to
// an unoffered/varying suite. We merely don't resume in weird cases.
//
// RFC 6066 says "A server that implements this extension MUST NOT accept
// the request to resume the session if the server_name extension contains
// a different name. Instead, it proceeds with a full handshake to
// establish a new session."
//
// RFC 8446: "The server MUST ensure that it selects
// a compatible PSK (if any) and cipher suite."
resumedata.cipher_suite == suite.suite()
&& (resumedata.extended_ms == using_ems || (resumedata.extended_ms && !using_ems))
&& &resumedata.sni == sni
}
#[derive(Default)]
pub(super) struct ExtensionProcessing {
// extensions to reply with
pub(super) extensions: Box<ServerExtensions<'static>>,
#[cfg(feature = "tls12")]
pub(super) send_ticket: bool,
}
impl ExtensionProcessing {
pub(super) fn new(extra_exts: ServerExtensionsInput<'static>) -> Self {
let ServerExtensionsInput {
transport_parameters,
} = extra_exts;
let mut extensions = Box::new(ServerExtensions::default());
match transport_parameters {
Some(TransportParameters::Quic(v)) => extensions.transport_parameters = Some(v),
Some(TransportParameters::QuicDraft(v)) => {
extensions.transport_parameters_draft = Some(v)
}
None => {}
}
Self {
extensions,
#[cfg(feature = "tls12")]
send_ticket: false,
}
}
pub(super) fn process_common(
&mut self,
config: &ServerConfig,
cx: &mut ServerContext<'_>,
ocsp_response: &mut Option<&[u8]>,
hello: &ClientHelloPayload,
resumedata: Option<&persist::ServerSessionValue>,
) -> Result<(), Error> {
// ALPN
let our_protocols = &config.alpn_protocols;
if let Some(their_protocols) = &hello.protocols {
cx.common.alpn_protocol = our_protocols
.iter()
.find(|ours| {
their_protocols
.iter()
.any(|theirs| theirs.as_ref() == ours.as_slice())
})
.map(|bytes| ProtocolName::from(bytes.clone()));
if let Some(selected_protocol) = &cx.common.alpn_protocol {
debug!("Chosen ALPN protocol {selected_protocol:?}");
self.extensions.selected_protocol =
Some(SingleProtocolName::new(selected_protocol.clone()));
} else if !our_protocols.is_empty() {
return Err(cx.common.send_fatal_alert(
AlertDescription::NoApplicationProtocol,
Error::NoApplicationProtocol,
));
}
}
if cx.common.is_quic() {
// QUIC has strict ALPN, unlike TLS's more backwards-compatible behavior. RFC 9001
// says: "The server MUST treat the inability to select a compatible application
// protocol as a connection error of type 0x0178". We judge that ALPN was desired
// (rather than some out-of-band protocol negotiation mechanism) if and only if any ALPN
// protocols were configured locally or offered by the client. This helps prevent
// successful establishment of connections between peers that can't understand
// each other.
if cx.common.alpn_protocol.is_none()
&& (!our_protocols.is_empty() || hello.protocols.is_some())
{
return Err(cx.common.send_fatal_alert(
AlertDescription::NoApplicationProtocol,
Error::NoApplicationProtocol,
));
}
let transport_params = hello
.transport_parameters
.as_ref()
.or(hello
.transport_parameters_draft
.as_ref());
match transport_params {
Some(params) => cx.common.quic.params = Some(params.to_owned().into_vec()),
None => {
return Err(cx
.common
.missing_extension(PeerMisbehaved::MissingQuicTransportParameters));
}
}
}
let for_resume = resumedata.is_some();
// SNI
if let (false, Some(ServerNamePayload::SingleDnsName(_))) = (for_resume, &hello.server_name)
{
self.extensions.server_name_ack = Some(());
}
// Send status_request response if we have one. This is not allowed
// if we're resuming, and is only triggered if we have an OCSP response
// to send.
if !for_resume
&& hello
.certificate_status_request
.is_some()
{
if ocsp_response.is_some() && !cx.common.is_tls13() {
// Only TLS1.2 sends confirmation in ServerHello
self.extensions
.certificate_status_request_ack = Some(());
}
} else {
// Throw away any OCSP response so we don't try to send it later.
ocsp_response.take();
}
self.validate_server_cert_type_extension(hello, config, cx)?;
self.validate_client_cert_type_extension(hello, config, cx)?;
Ok(())
}
#[cfg(feature = "tls12")]
pub(super) fn process_tls12(
&mut self,
config: &ServerConfig,
hello: &ClientHelloPayload,
using_ems: bool,
) {
// Renegotiation.
// (We don't do reneg at all, but would support the secure version if we did.)
use crate::msgs::base::PayloadU8;
let secure_reneg_offered = hello.renegotiation_info.is_some()
|| hello
.cipher_suites
.contains(&CipherSuite::TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
if secure_reneg_offered {
self.extensions.renegotiation_info = Some(PayloadU8::new(Vec::new()));
}
// Tickets:
// If we get any SessionTicket extension and have tickets enabled,
// we send an ack.
if hello.session_ticket.is_some() && config.ticketer.enabled() {
self.send_ticket = true;
self.extensions.session_ticket_ack = Some(());
}
// Confirm use of EMS if offered.
if using_ems {
self.extensions
.extended_master_secret_ack = Some(());
}
}
fn validate_server_cert_type_extension(
&mut self,
hello: &ClientHelloPayload,
config: &ServerConfig,
cx: &mut ServerContext<'_>,
) -> Result<(), Error> {
let client_supports = hello
.server_certificate_types
.as_deref()
.unwrap_or_default();
self.process_cert_type_extension(
client_supports,
config
.cert_resolver
.only_raw_public_keys(),
ExtensionType::ServerCertificateType,
cx,
)
}
fn validate_client_cert_type_extension(
&mut self,
hello: &ClientHelloPayload,
config: &ServerConfig,
cx: &mut ServerContext<'_>,
) -> Result<(), Error> {
let client_supports = hello
.client_certificate_types
.as_deref()
.unwrap_or_default();
self.process_cert_type_extension(
client_supports,
config
.verifier
.requires_raw_public_keys(),
ExtensionType::ClientCertificateType,
cx,
)
}
fn process_cert_type_extension(
&mut self,
client_supports: &[CertificateType],
requires_raw_keys: bool,
extension_type: ExtensionType,
cx: &mut ServerContext<'_>,
) -> Result<(), Error> {
debug_assert!(
extension_type == ExtensionType::ClientCertificateType
|| extension_type == ExtensionType::ServerCertificateType
);
let raw_key_negotation_result = match (
requires_raw_keys,
client_supports.contains(&CertificateType::RawPublicKey),
client_supports.contains(&CertificateType::X509),
) {
(true, true, _) => Ok((extension_type, CertificateType::RawPublicKey)),
(false, _, true) => Ok((extension_type, CertificateType::X509)),
(false, true, false) => Err(Error::PeerIncompatible(
PeerIncompatible::IncorrectCertificateTypeExtension,
)),
(true, false, _) => Err(Error::PeerIncompatible(
PeerIncompatible::IncorrectCertificateTypeExtension,
)),
(false, false, false) => return Ok(()),
};
match raw_key_negotation_result {
Ok((ExtensionType::ClientCertificateType, cert_type)) => {
self.extensions.client_certificate_type = Some(cert_type);
}
Ok((ExtensionType::ServerCertificateType, cert_type)) => {
self.extensions.server_certificate_type = Some(cert_type);
}
Err(err) => {
return Err(cx
.common
.send_fatal_alert(AlertDescription::HandshakeFailure, err));
}
Ok((_, _)) => unreachable!(),
}
Ok(())
}
}
pub(super) struct ExpectClientHello {
pub(super) config: Arc<ServerConfig>,
pub(super) extra_exts: ServerExtensionsInput<'static>,
pub(super) transcript: HandshakeHashOrBuffer,
#[cfg(feature = "tls12")]
pub(super) session_id: SessionId,
#[cfg(feature = "tls12")]
pub(super) using_ems: bool,
pub(super) previous_hello: Option<PreviousClientHello>,
pub(super) send_tickets: usize,
}
impl ExpectClientHello {
pub(super) fn new(
config: Arc<ServerConfig>,
extra_exts: ServerExtensionsInput<'static>,
) -> Self {
let mut transcript_buffer = HandshakeHashBuffer::new();
if config.verifier.offer_client_auth() {
transcript_buffer.set_client_auth_enabled();
}
Self {
config,
extra_exts,
transcript: HandshakeHashOrBuffer::Buffer(transcript_buffer),
#[cfg(feature = "tls12")]
session_id: SessionId::empty(),
#[cfg(feature = "tls12")]
using_ems: false,
previous_hello: None,
send_tickets: 0,
}
}
/// Continues handling of a `ClientHello` message once config and certificate are available.
pub(super) fn with_certified_key(
self,
mut sig_schemes: Vec<SignatureScheme>,
client_hello: &ClientHelloPayload,
m: &Message<'_>,
cx: &mut ServerContext<'_>,
) -> NextStateOrError<'static> {
let tls13_enabled = self
.config
.supports_version(ProtocolVersion::TLSv1_3, cx.common.protocol);
let tls12_enabled = self
.config
.supports_version(ProtocolVersion::TLSv1_2, cx.common.protocol)
&& !self.previous_hello.is_some();
// Are we doing TLS1.3?
let version = if let Some(versions) = &client_hello.supported_versions {
if versions.tls13 && tls13_enabled {
ProtocolVersion::TLSv1_3
} else if !versions.tls12 || !tls12_enabled {
return Err(cx.common.send_fatal_alert(
AlertDescription::ProtocolVersion,
PeerIncompatible::Tls12NotOfferedOrEnabled,
));
} else if cx.common.is_quic() {
return Err(cx.common.send_fatal_alert(
AlertDescription::ProtocolVersion,
PeerIncompatible::Tls13RequiredForQuic,
));
} else {
ProtocolVersion::TLSv1_2
}
} else if u16::from(client_hello.client_version) < u16::from(ProtocolVersion::TLSv1_2) {
return Err(cx.common.send_fatal_alert(
AlertDescription::ProtocolVersion,
PeerIncompatible::Tls12NotOffered,
));
} else if cx.common.is_quic() {
return Err(cx.common.send_fatal_alert(
AlertDescription::ProtocolVersion,
PeerIncompatible::Tls13RequiredForQuic,
));
} else if !tls12_enabled && tls13_enabled {
return Err(cx.common.send_fatal_alert(
AlertDescription::ProtocolVersion,
PeerIncompatible::SupportedVersionsExtensionRequired,
));
} else {
ProtocolVersion::TLSv1_2
};
cx.common.negotiated_version = Some(version);
// We communicate to the upper layer what kind of key they should choose
// via the sigschemes value. Clients tend to treat this extension
// orthogonally to offered ciphersuites (even though, in TLS1.2 it is not).
// So: reduce the offered sigschemes to those compatible with the
// intersection of ciphersuites.
let client_suites = self
.config
.provider
.cipher_suites
.iter()
.copied()
.filter(|scs| {
client_hello
.cipher_suites
.contains(&scs.suite())
})
.collect::<Vec<_>>();
sig_schemes
.retain(|scheme| suites::compatible_sigscheme_for_suites(*scheme, &client_suites));
// We adhere to the TLS 1.2 RFC by not exposing this to the cert resolver if TLS version is 1.2
let certificate_authorities = match version {
ProtocolVersion::TLSv1_2 => None,
_ => client_hello
.certificate_authority_names
.as_deref(),
};
// Choose a certificate.
let certkey = {
let client_hello = ClientHello {
server_name: &cx.data.sni,
signature_schemes: &sig_schemes,
alpn: client_hello.protocols.as_ref(),
client_cert_types: client_hello
.client_certificate_types
.as_deref(),
server_cert_types: client_hello
.server_certificate_types
.as_deref(),
cipher_suites: &client_hello.cipher_suites,
certificate_authorities,
named_groups: client_hello.named_groups.as_deref(),
};
trace!("Resolving server certificate: {client_hello:#?}");
let certkey = self
.config
.cert_resolver
.resolve(client_hello);
certkey.ok_or_else(|| {
cx.common.send_fatal_alert(
AlertDescription::AccessDenied,
Error::General("no server certificate chain resolved".to_owned()),
)
})?
};
let certkey = ActiveCertifiedKey::from_certified_key(&certkey);
let (suite, skxg) = self
.choose_suite_and_kx_group(
version,
certkey.get_key().algorithm(),
cx.common.protocol,
client_hello
.named_groups
.as_deref()
.unwrap_or_default(),
&client_hello.cipher_suites,
)
.map_err(|incompat| {
cx.common
.send_fatal_alert(AlertDescription::HandshakeFailure, incompat)
})?;
// RFC 9846 section 4.2.4: the server must negotiate the same cipher suite it
// named in its HelloRetryRequest
if let Some(PreviousClientHello {
suite: before_retry,
..
}) = self.previous_hello
{
if before_retry != suite.suite() {
return Err(cx.common.send_fatal_alert(
AlertDescription::IllegalParameter,
PeerMisbehaved::CipherSuiteDifferedOnRetry,
));
}
}
debug!("decided upon suite {suite:?}");
cx.common.suite = Some(suite);
cx.common.kx_state = KxState::Start(skxg);
// Start handshake hash.
let starting_hash = suite.hash_provider();
let transcript = match self.transcript {
HandshakeHashOrBuffer::Buffer(inner) => inner.start_hash(starting_hash),
HandshakeHashOrBuffer::Hash(inner)
if inner.algorithm() == starting_hash.algorithm() =>
{
inner
}
_ => {
return Err(cx.common.send_fatal_alert(
AlertDescription::IllegalParameter,
PeerMisbehaved::HandshakeHashVariedAfterRetry,
));
}
};
// Save their Random.
let randoms = ConnectionRandoms::new(
client_hello.random,
Random::new(self.config.provider.secure_random)?,
);
match suite {
SupportedCipherSuite::Tls13(suite) => tls13::CompleteClientHelloHandling {
config: self.config,
transcript,
suite,
randoms,
previous_hello: self.previous_hello,
send_tickets: self.send_tickets,
extra_exts: self.extra_exts,
}
.handle_client_hello(cx, certkey, m, client_hello, skxg, sig_schemes),
#[cfg(feature = "tls12")]
SupportedCipherSuite::Tls12(suite) => tls12::CompleteClientHelloHandling {
config: self.config,
transcript,
session_id: self.session_id,
suite,
using_ems: self.using_ems,
randoms,
send_ticket: self.send_tickets > 0,
extra_exts: self.extra_exts,
}
.handle_client_hello(
cx,
certkey,
m,
client_hello,
skxg,
sig_schemes,
tls13_enabled,
),
}
}
fn choose_suite_and_kx_group(
&self,
selected_version: ProtocolVersion,
sig_key_algorithm: SignatureAlgorithm,
protocol: Protocol,
client_groups: &[NamedGroup],
client_suites: &[CipherSuite],
) -> Result<(SupportedCipherSuite, &'static dyn SupportedKxGroup), PeerIncompatible> {
// Determine which `KeyExchangeAlgorithm`s are theoretically possible, based
// on the offered and supported groups.
let mut ecdhe_possible = false;
let mut ffdhe_possible = false;
let mut ffdhe_offered = false;
let mut supported_groups = Vec::with_capacity(client_groups.len());
for offered_group in client_groups {
let supported = self
.config
.provider
.kx_groups
.iter()
.find(|skxg| {
skxg.usable_for_version(selected_version) && skxg.name() == *offered_group
});
match offered_group.key_exchange_algorithm() {
KeyExchangeAlgorithm::DHE => {
ffdhe_possible |= supported.is_some();
ffdhe_offered = true;
}
KeyExchangeAlgorithm::ECDHE => {
ecdhe_possible |= supported.is_some();
}
}
supported_groups.push(supported);
}
let first_supported_dhe_kxg = if selected_version == ProtocolVersion::TLSv1_2 {
// https://datatracker.ietf.org/doc/html/rfc7919#section-4 (paragraph 2)
let first_supported_dhe_kxg = self
.config
.provider
.kx_groups
.iter()
.find(|skxg| skxg.name().key_exchange_algorithm() == KeyExchangeAlgorithm::DHE);
ffdhe_possible |= !ffdhe_offered && first_supported_dhe_kxg.is_some();
first_supported_dhe_kxg
} else {
// In TLS1.3, the server may only directly negotiate a group.
None
};
if !ecdhe_possible && !ffdhe_possible {
return Err(PeerIncompatible::NoKxGroupsInCommon);
}
let mut suitable_suites_iter = self
.config
.provider
.cipher_suites
.iter()
.filter(|suite| {
// Reduce our supported ciphersuites by the certified key's algorithm.
suite.usable_for_signature_algorithm(sig_key_algorithm)
// And version
&& suite.version().version == selected_version
// And protocol
&& suite.usable_for_protocol(protocol)
// And support one of key exchange groups
&& (ecdhe_possible && suite.usable_for_kx_algorithm(KeyExchangeAlgorithm::ECDHE)
|| ffdhe_possible && suite.usable_for_kx_algorithm(KeyExchangeAlgorithm::DHE))
});
// RFC 7919 (https://datatracker.ietf.org/doc/html/rfc7919#section-4) requires us to send
// the InsufficientSecurity alert in case we don't recognize client's FFDHE groups (i.e.,
// `suitable_suites` becomes empty). But that does not make a lot of sense (e.g., client
// proposes FFDHE4096 and we only support FFDHE2048), so we ignore that requirement here,
// and continue to send HandshakeFailure.
let suite = if self.config.ignore_client_order {
suitable_suites_iter.find(|suite| client_suites.contains(&suite.suite()))
} else {
let suitable_suites = suitable_suites_iter.collect::<Vec<_>>();
client_suites
.iter()
.find_map(|client_suite| {
suitable_suites
.iter()
.find(|x| *client_suite == x.suite())
})
.copied()
}
.ok_or(PeerIncompatible::NoCipherSuitesInCommon)?;
// Finally, choose a key exchange group that is compatible with the selected cipher
// suite.
let maybe_skxg = supported_groups
.iter()
.find_map(|maybe_skxg| match maybe_skxg {
Some(skxg) => suite
.usable_for_kx_algorithm(skxg.name().key_exchange_algorithm())
.then_some(*skxg),
None => None,
});
if selected_version == ProtocolVersion::TLSv1_3 {
// This unwrap is structurally guaranteed by the early return for `!ffdhe_possible && !ecdhe_possible`
return Ok((*suite, *maybe_skxg.unwrap()));
}
// For TLS1.2, the server can unilaterally choose a DHE group if it has one and
// there was no better option.
match maybe_skxg {
Some(skxg) => Ok((*suite, *skxg)),
None if suite.usable_for_kx_algorithm(KeyExchangeAlgorithm::DHE) => {
// If kx for the selected cipher suite is DHE and no DHE groups are specified in the extension,
// the server is free to choose DHE params, we choose the first DHE kx group of the provider.
if let Some(server_selected_ffdhe_skxg) = first_supported_dhe_kxg {
Ok((*suite, *server_selected_ffdhe_skxg))
} else {
Err(PeerIncompatible::NoKxGroupsInCommon)
}
}
None => Err(PeerIncompatible::NoKxGroupsInCommon),
}
}
}
pub(super) struct PreviousClientHello {
pub(super) offered_psk: bool,
pub(super) suite: CipherSuite,
}
impl State<ServerConnectionData> for ExpectClientHello {
fn handle<'m>(
self: Box<Self>,
cx: &mut ServerContext<'_>,
m: Message<'m>,
) -> NextStateOrError<'m>
where
Self: 'm,
{
let (client_hello, sig_schemes) =
process_client_hello(&m, self.previous_hello.is_some(), cx)?;
self.with_certified_key(sig_schemes, client_hello, &m, cx)
}
fn into_owned(self: Box<Self>) -> NextState<'static> {
self
}
}
/// Configuration-independent validation of a `ClientHello` message.
///
/// This represents the first part of the `ClientHello` handling, where we do all validation that
/// doesn't depend on a `ServerConfig` being available and extract everything needed to build a
/// [`ClientHello`] value for a [`ResolvesServerCert`].
///
/// Note that this will modify `data.sni` even if config or certificate resolution fail.
///
/// [`ResolvesServerCert`]: crate::server::ResolvesServerCert
pub(super) fn process_client_hello<'m>(
m: &'m Message<'m>,
done_retry: bool,
cx: &mut ServerContext<'_>,
) -> Result<(&'m ClientHelloPayload, Vec<SignatureScheme>), Error> {
let client_hello =
require_handshake_msg!(m, HandshakeType::ClientHello, HandshakePayload::ClientHello)?;
trace!("we got a clienthello {client_hello:?}");
if !client_hello
.compression_methods
.contains(&Compression::Null)
{
return Err(cx.common.send_fatal_alert(
AlertDescription::IllegalParameter,
PeerIncompatible::NullCompressionRequired,
));
}
// No handshake messages should follow this one in this flight.
cx.common.check_aligned_handshake()?;
// Extract and validate the SNI DNS name, if any, before giving it to
// the cert resolver. In particular, if it is invalid then we should
// send an Illegal Parameter alert instead of the Internal Error alert
// (or whatever) that we'd send if this were checked later or in a
// different way.
//
// [RFC6066][] specifies that literal IP addresses are illegal in
// `ServerName`s with a `name_type` of `host_name`.
//
// Some clients incorrectly send such extensions: we choose to
// successfully parse these (into `ServerNamePayload::IpAddress`)
// but then act like the client sent no `server_name` extension.
//
// [RFC6066]: https://datatracker.ietf.org/doc/html/rfc6066#section-3
let sni = match &client_hello.server_name {
Some(ServerNamePayload::SingleDnsName(dns_name)) => Some(dns_name.to_lowercase_owned()),
Some(ServerNamePayload::IpAddress) => None,
Some(ServerNamePayload::Invalid) => {
return Err(cx.common.send_fatal_alert(
AlertDescription::IllegalParameter,
PeerMisbehaved::ServerNameMustContainOneHostName,
));
}
None => None,
};
// save only the first SNI
if let (Some(sni), false) = (&sni, done_retry) {
// Save the SNI into the session.
// The SNI hostname is immutable once set.
assert!(cx.data.sni.is_none());
cx.data.sni = Some(sni.clone());
} else if cx.data.sni != sni {
return Err(PeerMisbehaved::ServerNameDifferedOnRetry.into());
}
let sig_schemes = client_hello
.signature_schemes
.as_ref()
.ok_or_else(|| {
cx.common.send_fatal_alert(
AlertDescription::HandshakeFailure,
PeerIncompatible::SignatureAlgorithmsExtensionRequired,
)
})?;
Ok((client_hello, sig_schemes.to_owned()))
}
pub(crate) enum HandshakeHashOrBuffer {
Buffer(HandshakeHashBuffer),
Hash(HandshakeHash),
}
File diff suppressed because it is too large Load Diff
+496
View File
@@ -0,0 +1,496 @@
use alloc::boxed::Box;
use alloc::vec;
use super::ServerConnectionData;
use crate::common_state::Context;
use crate::enums::{CipherSuite, SignatureScheme};
use crate::msgs::base::PayloadU16;
use crate::msgs::enums::{Compression, NamedGroup};
use crate::msgs::handshake::{
ClientExtensions, ClientHelloPayload, HandshakeMessagePayload, HandshakePayload, KeyShareEntry,
Random, ServerNamePayload, SessionId, SupportedProtocolVersions,
};
use crate::msgs::message::{Message, MessagePayload};
use crate::{CommonState, Error, PeerIncompatible, PeerMisbehaved, ProtocolVersion, Side};
#[test]
fn null_compression_required() {
assert_eq!(
test_process_client_hello(ClientHelloPayload {
compression_methods: vec![],
..minimal_client_hello()
}),
Err(PeerIncompatible::NullCompressionRequired.into()),
);
}
#[test]
fn server_ignores_sni_with_ip_address() {
let mut ch = minimal_client_hello();
ch.extensions.server_name = Some(ServerNamePayload::IpAddress);
std::println!("{:?}", ch.extensions);
assert_eq!(test_process_client_hello(ch), Ok(()));
}
#[test]
fn server_rejects_sni_with_illegal_dns_name() {
let mut ch = minimal_client_hello();
ch.extensions.server_name = Some(ServerNamePayload::Invalid);
std::println!("{:?}", ch.extensions);
assert_eq!(
test_process_client_hello(ch),
Err(PeerMisbehaved::ServerNameMustContainOneHostName.into())
);
}
fn test_process_client_hello(hello: ClientHelloPayload) -> Result<(), Error> {
let m = Message {
version: ProtocolVersion::TLSv1_2,
payload: MessagePayload::handshake(HandshakeMessagePayload(HandshakePayload::ClientHello(
hello,
))),
};
super::hs::process_client_hello(
&m,
false,
&mut Context {
common: &mut CommonState::new(Side::Server),
data: &mut ServerConnectionData::default(),
sendable_plaintext: None,
},
)
.map(|_| ())
}
#[macro_rules_attribute::apply(test_for_each_provider)]
mod tests {
use alloc::vec::Vec;
use super::super::*;
use crate::common_state::KxState;
use crate::crypto::{
ActiveKeyExchange, CryptoProvider, KeyExchangeAlgorithm, SupportedKxGroup,
};
use crate::enums::CertificateType;
use crate::msgs::handshake::{PresharedKeyIdentity, PresharedKeyOffer, PskKeyExchangeModes};
use crate::pki_types::pem::PemObject;
use crate::pki_types::{CertificateDer, PrivateKeyDer};
use crate::server::{AlwaysResolvesServerRawPublicKeys, ServerConfig, ServerConnection};
use crate::sign::CertifiedKey;
use crate::sync::Arc;
use crate::{
CipherSuiteCommon, SupportedCipherSuite, Tls12CipherSuite, Tls13CipherSuite, version,
};
#[cfg(feature = "tls12")]
#[test]
fn test_server_rejects_no_extended_master_secret_extension_when_require_ems_or_fips() {
let provider = super::provider::default_provider();
let mut config = ServerConfig::builder_with_provider(provider.into())
.with_protocol_versions(&[&version::TLS12])
.unwrap()
.with_no_client_auth()
.with_single_cert(server_cert(), server_key())
.unwrap();
if config.provider.fips() {
assert!(config.require_ems);
} else {
config.require_ems = true;
}
let mut conn = ServerConnection::new(config.into()).unwrap();
let mut ch = minimal_client_hello();
ch.extensions
.extended_master_secret_request
.take();
let ch = Message {
version: ProtocolVersion::TLSv1_3,
payload: MessagePayload::handshake(HandshakeMessagePayload(
HandshakePayload::ClientHello(ch),
)),
};
conn.read_tls(&mut ch.into_wire_bytes().as_slice())
.unwrap();
assert_eq!(
conn.process_new_packets(),
Err(Error::PeerIncompatible(
PeerIncompatible::ExtendedMasterSecretExtensionRequired
))
);
}
#[cfg(feature = "tls12")]
#[test]
fn server_picks_ffdhe_group_when_clienthello_has_no_ffdhe_group_in_groups_ext() {
let config = ServerConfig::builder_with_provider(ffdhe_provider().into())
.with_protocol_versions(&[&version::TLS12])
.unwrap()
.with_no_client_auth()
.with_single_cert(server_cert(), server_key())
.unwrap();
let mut ch = minimal_client_hello();
ch.cipher_suites
.push(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256.suite());
server_chooses_ffdhe_group_for_client_hello(
ServerConnection::new(config.into()).unwrap(),
ch,
);
}
#[cfg(feature = "tls12")]
#[test]
fn server_picks_ffdhe_group_when_clienthello_has_no_groups_ext() {
let config = ServerConfig::builder_with_provider(ffdhe_provider().into())
.with_protocol_versions(&[&version::TLS12])
.unwrap()
.with_no_client_auth()
.with_single_cert(server_cert(), server_key())
.unwrap();
let mut ch = minimal_client_hello();
ch.cipher_suites
.push(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256.suite());
ch.extensions.named_groups.take();
server_chooses_ffdhe_group_for_client_hello(
ServerConnection::new(config.into()).unwrap(),
ch,
);
}
#[cfg(feature = "tls12")]
#[test]
fn server_accepts_client_with_no_ecpoints_extension_and_only_ffdhe_cipher_suites() {
let config = ServerConfig::builder_with_provider(ffdhe_provider().into())
.with_protocol_versions(&[&version::TLS12])
.unwrap()
.with_no_client_auth()
.with_single_cert(server_cert(), server_key())
.unwrap();
let mut ch = minimal_client_hello();
ch.cipher_suites
.push(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256.suite());
ch.extensions.ec_point_formats.take();
server_chooses_ffdhe_group_for_client_hello(
ServerConnection::new(config.into()).unwrap(),
ch,
);
}
fn server_chooses_ffdhe_group_for_client_hello(
mut conn: ServerConnection,
client_hello: ClientHelloPayload,
) {
let ch = Message {
version: ProtocolVersion::TLSv1_3,
payload: MessagePayload::handshake(HandshakeMessagePayload(
HandshakePayload::ClientHello(client_hello),
)),
};
conn.read_tls(&mut ch.into_wire_bytes().as_slice())
.unwrap();
conn.process_new_packets().unwrap();
let KxState::Start(skxg) = &conn.kx_state else {
panic!("unexpected kx_state");
};
assert_eq!(skxg.name(), FAKE_FFDHE_GROUP.name());
}
#[test]
fn test_server_requiring_rpk_client_rejects_x509_client() {
let mut ch = minimal_client_hello();
ch.extensions.client_certificate_types = Some(vec![CertificateType::X509]);
let ch = Message {
version: ProtocolVersion::TLSv1_3,
payload: MessagePayload::handshake(HandshakeMessagePayload(
HandshakePayload::ClientHello(ch),
)),
};
let mut conn = ServerConnection::new(server_config_for_rpk().into()).unwrap();
conn.read_tls(&mut ch.into_wire_bytes().as_slice())
.unwrap();
assert_eq!(
conn.process_new_packets().unwrap_err(),
PeerIncompatible::IncorrectCertificateTypeExtension.into(),
);
}
#[test]
fn test_rpk_only_server_rejects_x509_only_client() {
let mut ch = minimal_client_hello();
ch.extensions.server_certificate_types = Some(vec![CertificateType::X509]);
let ch = Message {
version: ProtocolVersion::TLSv1_3,
payload: MessagePayload::handshake(HandshakeMessagePayload(
HandshakePayload::ClientHello(ch),
)),
};
let mut conn = ServerConnection::new(server_config_for_rpk().into()).unwrap();
conn.read_tls(&mut ch.into_wire_bytes().as_slice())
.unwrap();
assert_eq!(
conn.process_new_packets().unwrap_err(),
PeerIncompatible::IncorrectCertificateTypeExtension.into(),
);
}
#[test]
fn second_client_hello_cannot_withdraw_psk_offer() {
// Per RFC 9846 section 4.2.2, dropping a PreSharedKey offer is not one of the
// changes a client may make after a HelloRetryRequest.
let config =
ServerConfig::builder_with_provider(super::provider::default_provider().into())
.with_protocol_versions(&[&version::TLS13])
.unwrap()
.with_no_client_auth()
.with_single_cert(server_cert(), server_key())
.unwrap();
let mut conn = ServerConnection::new(config.into()).unwrap();
let encode = |hello| {
Message {
version: ProtocolVersion::TLSv1_3,
payload: MessagePayload::handshake(HandshakeMessagePayload(
HandshakePayload::ClientHello(hello),
)),
}
.into_wire_bytes()
};
// this hello offers a PSK, but no key share for a group we support, so
// it draws a HelloRetryRequest.
let mut first = minimal_client_hello();
first.extensions.key_shares = Some(vec![]);
first.extensions.preshared_key_modes = Some(PskKeyExchangeModes {
psk_dhe: true,
psk: false,
});
first.extensions.preshared_key_offer = Some(PresharedKeyOffer::new(
PresharedKeyIdentity::new(vec![0u8; 16], 0),
vec![0u8; 32],
));
conn.read_tls(&mut encode(first).as_slice())
.unwrap();
conn.process_new_packets().unwrap();
// the second hello follows the retry, but drops the PSK offer entirely.
let mut second = minimal_client_hello();
second.extensions.preshared_key_modes = Some(PskKeyExchangeModes {
psk_dhe: true,
psk: false,
});
conn.read_tls(&mut encode(second).as_slice())
.unwrap();
assert_eq!(
conn.process_new_packets().unwrap_err(),
PeerMisbehaved::MissingPskExtensionInSecondClientHello.into(),
);
}
#[test]
fn second_client_hello_cannot_change_cipher_suite() {
// RFC 9846 section 4.2.4 requires the server to negotiate the same cipher suite it
// named in its HelloRetryRequest, and section 4.2.2 does not let the client vary its
// offer, so a second hello that withdraws the retried suite cannot be honoured.
let provider = CryptoProvider {
cipher_suites: vec![
super::provider::cipher_suite::TLS13_AES_128_GCM_SHA256,
TLS13_AES_128_GCM_SHA256_ALT,
],
..super::provider::default_provider()
};
let config = ServerConfig::builder_with_provider(provider.into())
.with_protocol_versions(&[&version::TLS13])
.unwrap()
.with_no_client_auth()
.with_single_cert(server_cert(), server_key())
.unwrap();
let mut conn = ServerConnection::new(config.into()).unwrap();
let encode = |hello| {
Message {
version: ProtocolVersion::TLSv1_3,
payload: MessagePayload::handshake(HandshakeMessagePayload(
HandshakePayload::ClientHello(hello),
)),
}
.into_wire_bytes()
};
// this hello has no key share for a group we support, so it draws a
// HelloRetryRequest naming `TLS13_AES_128_GCM_SHA256`.
let mut first = minimal_client_hello();
first.cipher_suites = vec![CipherSuite::TLS13_AES_128_GCM_SHA256];
first.extensions.key_shares = Some(vec![]);
conn.read_tls(&mut encode(first).as_slice())
.unwrap();
conn.process_new_packets().unwrap();
// the second hello follows the retry, but offers only a different suite. It shares
// the retried suite's hash, so the transcript stays valid and nothing else objects.
let mut second = minimal_client_hello();
second.cipher_suites = vec![TLS13_AES_128_GCM_SHA256_ALT.suite()];
conn.read_tls(&mut encode(second).as_slice())
.unwrap();
assert_eq!(
conn.process_new_packets().unwrap_err(),
PeerMisbehaved::CipherSuiteDifferedOnRetry.into(),
);
}
static TLS13_AES_128_GCM_SHA256_ALT: SupportedCipherSuite =
SupportedCipherSuite::Tls13(&TLS13_AES_128_GCM_SHA256_ALT_INNER);
/// Differs from `TLS13_AES_128_GCM_SHA256` only in its code point: same hash, same everything else.
static TLS13_AES_128_GCM_SHA256_ALT_INNER: Tls13CipherSuite =
match &super::provider::cipher_suite::TLS13_AES_128_GCM_SHA256 {
SupportedCipherSuite::Tls13(provider) => Tls13CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::Unknown(0xff14),
..provider.common
},
..**provider
},
_ => unreachable!(),
};
fn server_config_for_rpk() -> ServerConfig {
let x25519_provider = CryptoProvider {
kx_groups: vec![super::provider::kx_group::X25519],
..super::provider::default_provider()
};
ServerConfig::builder_with_provider(x25519_provider.into())
.with_protocol_versions(&[&version::TLS13])
.unwrap()
.with_no_client_auth()
.with_cert_resolver(Arc::new(AlwaysResolvesServerRawPublicKeys::new(Arc::new(
server_certified_key(),
))))
}
fn server_certified_key() -> CertifiedKey {
let key = super::provider::default_provider()
.key_provider
.load_private_key(server_key())
.unwrap();
let public_key_as_cert = vec![CertificateDer::from(
key.public_key()
.unwrap()
.as_ref()
.to_vec(),
)];
CertifiedKey::new(public_key_as_cert, key)
}
fn server_key() -> PrivateKeyDer<'static> {
PrivateKeyDer::from_pem_reader(
&mut include_bytes!("../../../test-ca/rsa-2048/end.key").as_slice(),
)
.unwrap()
}
fn server_cert() -> Vec<CertificateDer<'static>> {
vec![
CertificateDer::from(&include_bytes!("../../../test-ca/rsa-2048/end.der")[..]),
CertificateDer::from(&include_bytes!("../../../test-ca/rsa-2048/inter.der")[..]),
]
}
fn ffdhe_provider() -> CryptoProvider {
CryptoProvider {
kx_groups: vec![FAKE_FFDHE_GROUP],
cipher_suites: vec![TLS_DHE_RSA_WITH_AES_128_GCM_SHA256],
..super::provider::default_provider()
}
}
static FAKE_FFDHE_GROUP: &'static dyn SupportedKxGroup = &FakeFfdheGroup;
#[derive(Debug)]
struct FakeFfdheGroup;
impl SupportedKxGroup for FakeFfdheGroup {
fn name(&self) -> NamedGroup {
NamedGroup::FFDHE2048
}
fn start(&self) -> Result<Box<dyn ActiveKeyExchange>, Error> {
Ok(Box::new(ActiveFakeFfdhe))
}
}
#[derive(Debug)]
struct ActiveFakeFfdhe;
impl ActiveKeyExchange for ActiveFakeFfdhe {
#[cfg_attr(coverage_nightly, coverage(off))]
fn complete(
self: Box<Self>,
_peer_pub_key: &[u8],
) -> Result<crate::crypto::SharedSecret, Error> {
todo!()
}
fn pub_key(&self) -> &[u8] {
b"ActiveFakeFfdhe pub key"
}
fn group(&self) -> NamedGroup {
NamedGroup::FFDHE2048
}
}
static TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
SupportedCipherSuite::Tls12(&TLS12_DHE_RSA_WITH_AES_128_GCM_SHA256);
static TLS12_DHE_RSA_WITH_AES_128_GCM_SHA256: Tls12CipherSuite =
match &super::provider::cipher_suite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 {
SupportedCipherSuite::Tls12(provider) => Tls12CipherSuite {
common: CipherSuiteCommon {
suite: CipherSuite::TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
..provider.common
},
kx: KeyExchangeAlgorithm::DHE,
..**provider
},
_ => unreachable!(),
};
}
fn minimal_client_hello() -> ClientHelloPayload {
ClientHelloPayload {
client_version: ProtocolVersion::TLSv1_3,
random: Random::from([0u8; 32]),
session_id: SessionId::empty(),
cipher_suites: vec![
CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite::TLS13_AES_128_GCM_SHA256,
],
compression_methods: vec![Compression::Null],
extensions: Box::new(ClientExtensions {
signature_schemes: Some(vec![SignatureScheme::RSA_PSS_SHA256]),
named_groups: Some(vec![NamedGroup::X25519, NamedGroup::secp256r1]),
supported_versions: Some(SupportedProtocolVersions {
tls12: true,
tls13: true,
}),
key_shares: Some(vec![KeyShareEntry {
group: NamedGroup::X25519,
payload: PayloadU16::new(vec![0xab; 32]),
}]),
extended_master_secret_request: Some(()),
..ClientExtensions::default()
}),
}
}
+1004
View File
File diff suppressed because it is too large Load Diff
+1582
View File
File diff suppressed because it is too large Load Diff