use super::flight3::*;
use super::*;
use crate::cipher_suite::CipherSuiteId;
use crate::compression_methods::*;
use crate::config::*;
use crate::conn::*;
use crate::content::*;
use crate::extension::extension_server_name::*;
use crate::extension::extension_supported_elliptic_curves::*;
use crate::extension::extension_supported_point_formats::*;
use crate::extension::extension_supported_signature_algorithms::*;
use crate::extension::extension_use_extended_master_secret::*;
use crate::extension::extension_use_srtp::*;
use crate::extension::*;
use crate::handshake::handshake_message_client_hello::*;
use crate::handshake::*;
use crate::record_layer::record_layer_header::*;
use crate::record_layer::*;
use shared::error::Error;
use crate::extension::renegotiation_info::ExtensionRenegotiationInfo;
use std::fmt;
#[derive(Debug, PartialEq)]
pub(crate) struct Flight1;
impl fmt::Display for Flight1 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Flight 1")
}
}
impl Flight for Flight1 {
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(
state.handshake_recv_sequence,
&[
HandshakeCachePullRule {
typ: HandshakeType::HelloVerifyRequest,
epoch: cfg.initial_epoch,
is_client: false,
optional: true,
},
HandshakeCachePullRule {
typ: HandshakeType::ServerHello,
epoch: cfg.initial_epoch,
is_client: false,
optional: true,
},
],
) {
Ok((seq, msgs)) => (seq, msgs),
Err(_) => return Err((None, None)),
};
if msgs.contains_key(&HandshakeType::ServerHello) {
let flight3 = Flight3 {};
return flight3.parse( state, cache, cfg);
}
if let Some(message) = msgs.get(&HandshakeType::HelloVerifyRequest) {
let h = match message {
HandshakeMessage::HelloVerifyRequest(h) => h,
_ => {
return Err((
Some(Alert {
alert_level: AlertLevel::Fatal,
alert_description: AlertDescription::InternalError,
}),
None,
));
}
};
if h.version != PROTOCOL_VERSION1_0 && h.version != PROTOCOL_VERSION1_2 {
return Err((
Some(Alert {
alert_level: AlertLevel::Fatal,
alert_description: AlertDescription::ProtocolVersion,
}),
Some(Error::ErrUnsupportedProtocolVersion),
));
}
state.cookie.clone_from(&h.cookie);
state.handshake_recv_sequence = seq;
Ok(Box::new(Flight3 {}))
} else {
Err((None, None))
}
}
fn generate(
&self,
state: &mut State,
_cache: &HandshakeCache,
cfg: &HandshakeConfig,
) -> Result<Vec<Packet>, (Option<Alert>, Option<Error>)> {
state.local_epoch = 0;
state.remote_epoch = 0;
state.named_curve = DEFAULT_NAMED_CURVE;
state.cookie = vec![];
if let Err(error) = state.local_random.populate(cfg.provider().random()) {
return Err((None, Some(error)));
}
state.tls13_offer = None;
if cfg.supports_dtls13() {
match crate::dtls13::hello::ClientOffer::new(
cfg,
state.clock,
&std::mem::take(&mut state.early_data),
) {
Ok(offer) => state.tls13_offer = Some(offer),
Err(error) => return Err((None, Some(error))),
}
}
state.connection_id_offer = match &state.tls13_offer {
Some(offer) => offer.connection_id.clone(),
None => cfg.connection_id_offer(),
};
state.local_connection_id = None;
state.remote_connection_id = None;
if let Err(error) = crate::resumption::client_offer(state, cfg) {
return Err((None, Some(error)));
}
let extensions = client_hello_extensions(
cfg,
state.tls13_offer.as_ref(),
state.connection_id_offer.as_deref(),
state.session_ticket_offer.as_deref(),
);
let mut client_hello = HandshakeMessageClientHello {
version: PROTOCOL_VERSION1_2,
random: state.local_random.clone(),
session_id: state.session_id.clone(),
cookie: state.cookie.clone(),
cipher_suites: client_hello_cipher_suites(cfg),
compression_methods: default_compression_methods(),
extensions,
};
if let Err(error) = bind_client_hello(cfg, state.tls13_offer.as_ref(), &mut client_hello) {
return Err((None, Some(error)));
}
state.early_datagrams.clear();
state.early_data_accepted = None;
if let Some(offer) = &state.tls13_offer
&& let (Some(data), Some(psk)) = (&offer.early_data, offer.psks.first())
{
let mut body = vec![];
let record = client_hello.marshal(&mut body).and_then(|()| {
crate::dtls13::psk::early_data_record(cfg.provider().crypto(), psk, &body, data)
});
match record {
Ok(record) => {
state
.early_datagrams
.push(bytes::BytesMut::from(&record[..]));
state.early_data_accepted = Some(false);
}
Err(error) => return Err((None, Some(error))),
}
}
Ok(vec![Packet {
record: RecordLayer::new(
PROTOCOL_VERSION1_2,
0,
Content::Handshake(Handshake::new(HandshakeMessage::ClientHello(client_hello))),
),
should_encrypt: false,
reset_local_sequence_number: false,
}])
}
}
pub(crate) fn client_hello_extensions(
cfg: &HandshakeConfig,
tls13_offer: Option<&crate::dtls13::hello::ClientOffer>,
connection_id: Option<&[u8]>,
session_ticket: Option<&[u8]>,
) -> Vec<Extension> {
let mut extensions = vec![
Extension::SupportedSignatureAlgorithms(ExtensionSupportedSignatureAlgorithms {
signature_hash_algorithms: cfg.local_signature_schemes.clone(),
}),
Extension::RenegotiationInfo(ExtensionRenegotiationInfo::default()),
];
if cfg.local_psk_callback.is_none() {
extensions.extend_from_slice(&[
Extension::SupportedEllipticCurves(ExtensionSupportedEllipticCurves {
elliptic_curves: if tls13_offer.is_some() {
cfg.local_tls13_groups.clone()
} else {
cfg.local_named_curves.clone()
},
}),
Extension::SupportedPointFormats(ExtensionSupportedPointFormats {
point_formats: vec![ELLIPTIC_CURVE_POINT_FORMAT_UNCOMPRESSED],
}),
]);
}
if !cfg.local_srtp_protection_profiles.is_empty() {
extensions.push(Extension::UseSrtp(ExtensionUseSrtp {
protection_profiles: cfg.local_srtp_protection_profiles.clone(),
mki: vec![],
}));
}
if cfg.extended_master_secret == ExtendedMasterSecretType::Request
|| cfg.extended_master_secret == ExtendedMasterSecretType::Require
{
extensions.push(Extension::UseExtendedMasterSecret(
ExtensionUseExtendedMasterSecret { supported: true },
));
}
if let Some(host_name) = sni_host_name(&cfg.server_name) {
extensions.push(Extension::ServerName(ExtensionServerName {
server_name: host_name.to_owned(),
}));
}
if !cfg.alpn_protocols.is_empty() {
extensions.push(Extension::alpn(&cfg.alpn_protocols));
}
if let Some(session_ticket) = session_ticket {
extensions.push(crate::resumption::session_ticket_extension(session_ticket));
}
if let Some(offer) = tls13_offer {
extensions.extend(offer.extensions(cfg));
} else if let Some(connection_id) = connection_id {
extensions.push(Extension::connection_id(connection_id));
}
extensions
}
pub(crate) fn bind_client_hello(
cfg: &HandshakeConfig,
offer: Option<&crate::dtls13::hello::ClientOffer>,
client_hello: &mut HandshakeMessageClientHello,
) -> shared::error::Result<()> {
let Some(offer) = offer.filter(|offer| !offer.psks.is_empty()) else {
return Ok(());
};
let mut body = vec![];
client_hello.marshal(&mut body)?;
offer.bind(cfg, &mut body)?;
let length = crate::dtls13::psk::binders_len(&offer.psks);
let binders = &body[body.len() - length..];
match client_hello.extensions.last_mut() {
Some(Extension::Unknown {
extension_type: crate::dtls13::messages::EXT_PRE_SHARED_KEY,
data,
}) if data.len() >= length => {
let at = data.len() - length;
data[at..].copy_from_slice(binders);
Ok(())
}
_ => Err(Error::ErrInvalidExtensionType),
}
}
pub(crate) fn client_hello_cipher_suites(cfg: &HandshakeConfig) -> Vec<CipherSuiteId> {
let mut suites = cfg.local_tls13_cipher_suites.clone();
if cfg.supports_dtls12() || suites.is_empty() {
suites.extend_from_slice(&cfg.local_cipher_suites);
}
suites
}
pub(crate) fn sni_host_name(server_name: &str) -> Option<&str> {
let host_name = server_name.strip_suffix('.').unwrap_or(server_name);
let is_address = host_name.parse::<std::net::IpAddr>().is_ok()
|| host_name
.strip_prefix('[')
.and_then(|rest| rest.strip_suffix(']'))
.is_some_and(|inner| inner.parse::<std::net::Ipv6Addr>().is_ok());
(!host_name.is_empty() && !is_address).then_some(host_name)
}