use super::flight2::*;
use super::*;
use crate::compression_methods::CompressionMethodId;
use crate::config::*;
use crate::conn::*;
use crate::crypto::certificates_signed_within;
use crate::extension::*;
use crate::handshake::handshake_message_client_hello::HandshakeMessageClientHello;
use crate::handshake::*;
use crate::signature_hash_algorithm::{
default_remote_signature_schemes, select_common_signature_scheme,
};
use crate::*;
use shared::error::Error;
use log::debug;
use std::fmt;
#[derive(Debug, PartialEq)]
pub(crate) struct Flight0;
impl fmt::Display for Flight0 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Flight 0")
}
}
impl Flight for Flight0 {
fn parse(
&self,
state: &mut State,
cache: &HandshakeCache,
cfg: &HandshakeConfig,
) -> Result<Box<dyn Flight>, (Option<Alert>, Option<Error>)> {
let (seq, msgs) = match cache.full_pull_map(
0,
&[HandshakeCachePullRule {
typ: HandshakeType::ClientHello,
epoch: cfg.initial_epoch,
is_client: true,
optional: false,
}],
) {
Ok((seq, msgs)) => (seq, msgs),
Err(_) => return Err((None, None)),
};
state.handshake_recv_sequence = seq;
if let Some(message) = msgs.get(&HandshakeType::ClientHello) {
let client_hello = match message {
HandshakeMessage::ClientHello(client_hello) => client_hello,
_ => {
return Err((
Some(Alert {
alert_level: AlertLevel::Fatal,
alert_description: AlertDescription::InternalError,
}),
None,
));
}
};
if !client_hello.version.is_dtls1_2_or_later() {
return Err((
Some(Alert {
alert_level: AlertLevel::Fatal,
alert_description: AlertDescription::ProtocolVersion,
}),
Some(Error::ErrUnsupportedProtocolVersion),
));
}
Ok(Box::new(Flight2 {}))
} else {
Err((
Some(Alert {
alert_level: AlertLevel::Fatal,
alert_description: AlertDescription::InternalError,
}),
None,
))
}
}
fn generate(
&self,
state: &mut State,
_cache: &HandshakeCache,
cfg: &HandshakeConfig,
) -> Result<Vec<Packet>, (Option<Alert>, Option<Error>)> {
state.cookie = vec![0; COOKIE_LENGTH];
if let Err(error) = cfg.provider().random().fill(state.cookie.as_mut_slice()) {
return Err((None, Some(Error::Crypto(error.to_string()))));
}
state.local_epoch = 0;
state.remote_epoch = 0;
state.named_curve = DEFAULT_NAMED_CURVE;
if cfg.local_psk_callback.is_none() {
state.named_curve = cfg.local_named_curves[0];
}
if let Err(error) = state.local_random.populate(cfg.provider().random()) {
return Err((None, Some(error)));
}
Ok(vec![])
}
}
fn fatal(description: AlertDescription, err: Error) -> (Option<Alert>, Option<Error>) {
(
Some(Alert {
alert_level: AlertLevel::Fatal,
alert_description: description,
}),
Some(err),
)
}
pub(crate) fn negotiate_client_hello(
state: &mut State,
client_hello: &HandshakeMessageClientHello,
cfg: &HandshakeConfig,
) -> Result<(), (Option<Alert>, Option<Error>)> {
state.named_curve = DEFAULT_NAMED_CURVE;
if cfg.local_psk_callback.is_none()
&& let Some(curve) = cfg.local_named_curves.first()
{
state.named_curve = *curve;
}
state.cipher_suite = None;
state.srtp_protection_profile = SrtpProtectionProfile::Unsupported;
state.application_protocol = None;
state.extended_master_secret = false;
state.secure_renegotiation = false;
state.remote_offered_point_formats = false;
state.local_signature_scheme = None;
state.server_name.clear();
state.remote_connection_id = None;
state.remote_random = client_hello.random.clone();
if !client_hello
.compression_methods
.ids
.contains(&CompressionMethodId::Null)
{
return Err(fatal(
AlertDescription::IllegalParameter,
Error::ErrNoNullCompressionMethod,
));
}
let mut client_curves = None;
let mut client_signature_schemes = None;
let mut client_use_srtp = None;
for extension in &client_hello.extensions {
match extension {
Extension::SupportedEllipticCurves(e) => client_curves = Some(&e.elliptic_curves),
Extension::SupportedPointFormats(_) => state.remote_offered_point_formats = true,
Extension::SupportedSignatureAlgorithms(e) => {
client_signature_schemes = Some(e.signature_hash_algorithms.clone())
}
Extension::UseSrtp(e) => client_use_srtp = Some(e),
Extension::UseExtendedMasterSecret(_)
if cfg.extended_master_secret != ExtendedMasterSecretType::Disable =>
{
state.extended_master_secret = true;
}
Extension::ServerName(e) => {
state.server_name.clone_from(&e.server_name); }
extension if extension.as_connection_id().is_some() => {
match extension.as_connection_id() {
Some(Ok(connection_id)) if cfg.connection_id.is_some() => {
state.remote_connection_id = Some(connection_id.to_vec());
}
Some(Err(error)) => {
return Err(fatal(AlertDescription::DecodeError, error));
}
_ => {}
}
}
extension if extension.as_alpn().is_some() => match extension.as_alpn() {
Some(Ok(offered)) => match cfg.select_alpn(&offered) {
Some(Ok(protocol)) => state.application_protocol = Some(protocol),
Some(Err(error)) => {
return Err(fatal(AlertDescription::NoApplicationProtocol, error));
}
None => {}
},
Some(Err(error)) => return Err(fatal(AlertDescription::DecodeError, error)),
None => {}
},
Extension::RenegotiationInfo(e) => {
if !e.renegotiated_connection.is_empty() {
return Err(fatal(
AlertDescription::HandshakeFailure,
Error::ErrRenegotiationInfoNotEmpty,
));
}
state.secure_renegotiation = true;
}
_ => {}
}
}
if client_hello
.cipher_suites
.contains(&CipherSuiteId::Tls_Empty_Renegotiation_Info_Scsv)
{
state.secure_renegotiation = true;
}
state.remote_signature_schemes =
client_signature_schemes.unwrap_or_else(default_remote_signature_schemes);
let curve = match client_curves {
None => cfg.local_named_curves.first().copied(),
Some(curves) => curves
.iter()
.find(|curve| cfg.local_named_curves.contains(curve))
.copied(),
};
let signature_scheme = cfg
.get_certificate(&cfg.server_name)
.ok()
.filter(|certificate| {
certificates_signed_within(&certificate.certificate, &state.remote_signature_schemes)
})
.and_then(|certificate| {
select_common_signature_scheme(
&cfg.local_signature_schemes,
&state.remote_signature_schemes,
&certificate.private_key,
)
.ok()
});
let mut common_suite = false;
for id in &client_hello.cipher_suites {
if !cfg.local_cipher_suites.contains(id) {
continue;
}
let Ok(cipher_suite) = cipher_suite_for_id(*id) else {
continue;
};
common_suite = true;
if !cipher_suite.is_psk() {
let (Some(curve), Some(signature_scheme)) = (curve, signature_scheme) else {
continue;
};
state.named_curve = curve;
state.local_signature_scheme = Some(signature_scheme);
}
debug!(
"[handshake:{}] use cipher suite: {}",
srv_cli_str(state.is_client),
cipher_suite.to_string()
);
state.cipher_suite = Some(cipher_suite);
break;
}
if state.cipher_suite.is_none() {
let err = if !common_suite {
Error::ErrCipherSuiteNoIntersection
} else if curve.is_none() {
Error::ErrNoSupportedEllipticCurves
} else {
Error::ErrNoAvailableSignatureSchemes
};
return Err(fatal(AlertDescription::HandshakeFailure, err));
}
if let Some(use_srtp) = client_use_srtp
&& !cfg.local_srtp_protection_profiles.is_empty()
{
match find_matching_srtp_profile(
&use_srtp.protection_profiles,
&cfg.local_srtp_protection_profiles,
) {
Ok(profile) => state.srtp_protection_profile = profile,
Err(_) if cfg.use_srtp_required => {
return Err(fatal(
AlertDescription::InsufficientSecurity,
Error::ErrServerNoMatchingSrtpProfile,
));
}
Err(_) => {}
}
}
if cfg.extended_master_secret == ExtendedMasterSecretType::Require
&& !state.extended_master_secret
{
return Err(fatal(
AlertDescription::HandshakeFailure,
Error::ErrServerRequiredButNoClientEms,
));
}
Ok(())
}
pub(crate) fn ensure_local_keypair(
state: &mut State,
cfg: &HandshakeConfig,
) -> Result<(), (Option<Alert>, Option<Error>)> {
let keypair_matches_curve = state
.local_keypair
.as_ref()
.is_some_and(|keypair| keypair.curve == state.named_curve);
if !keypair_matches_curve {
state.local_keypair = match state
.named_curve
.generate_keypair_with_crypto(cfg.provider().crypto())
{
Ok(local_keypar) => Some(local_keypar),
Err(err) => {
return Err((
Some(Alert {
alert_level: AlertLevel::Fatal,
alert_description: AlertDescription::IllegalParameter,
}),
Some(err),
));
}
};
}
Ok(())
}