use super::*;
fn client_hello_record(
cookie: Vec<u8>,
sequence_number: u64,
send_renegotiation_info: bool,
) -> Result<Vec<u8>> {
use crate::cipher_suite::CipherSuiteId;
use crate::compression_methods::default_compression_methods;
use crate::extension::Extension;
use crate::extension::renegotiation_info::ExtensionRenegotiationInfo;
use crate::handshake::handshake_message_client_hello::HandshakeMessageClientHello;
use crate::handshake::handshake_random::HandshakeRandom;
let mut extensions = vec![
Extension::SupportedSignatureAlgorithms(
crate::extension::extension_supported_signature_algorithms::ExtensionSupportedSignatureAlgorithms {
signature_hash_algorithms:
crate::signature_hash_algorithm::default_signature_schemes(),
},
),
Extension::SupportedEllipticCurves(
crate::extension::extension_supported_elliptic_curves::ExtensionSupportedEllipticCurves {
elliptic_curves: vec![NamedCurve::X25519],
},
),
];
if send_renegotiation_info {
extensions.push(Extension::RenegotiationInfo(ExtensionRenegotiationInfo {
renegotiated_connection: vec![],
}));
}
let mut h = Handshake::new(HandshakeMessage::ClientHello(HandshakeMessageClientHello {
session_id: vec![],
version: PROTOCOL_VERSION1_2,
random: HandshakeRandom::default(),
cookie,
cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256],
compression_methods: default_compression_methods(),
extensions,
}));
h.handshake_header.message_sequence = sequence_number as u16;
let mut record = RecordLayer::new(PROTOCOL_VERSION1_2, 0, Content::Handshake(h));
record.record_layer_header.sequence_number = sequence_number;
let mut packet = vec![];
record.marshal(&mut packet)?;
Ok(packet)
}
fn first_record(datagram: &[u8]) -> Result<RecordLayer> {
let records = unpack_datagram(datagram)?;
let mut reader = records[0].as_slice();
RecordLayer::unmarshal(&mut reader)
}
#[test]
fn test_renegotation_info() -> Result<()> {
use crate::cipher_suite::CipherSuiteId;
use crate::config::ConfigBuilder;
use crate::crypto::Certificate;
use crate::extension::Extension;
let provider = crypto::default_provider().map_err(|err| Error::Crypto(err.to_string()))?;
let config = Arc::new(
ConfigBuilder::default()
.with_crypto_provider(provider.clone())
.with_cipher_suites(vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256])
.with_certificates(vec![Certificate::generate_self_signed(
vec!["localhost".to_owned()],
provider.crypto(),
)?])
.build(false, None)?,
);
let now = Instant::now();
let tests = vec![
("Include RenegotiationInfo", true),
("No RenegotiationInfo", false),
];
for (name, send_renegotiation_info) in tests {
let mut server = DTLSConn::new(config.clone(), false, None);
server.read(&client_hello_record(vec![], 0, send_renegotiation_info)?)?;
server.handshake(now)?;
let response = server
.outgoing_raw_packet()
.expect("the server answers a cookieless ClientHello");
let hello_verify_request = match first_record(&response)?.content {
Content::Handshake(h) => match h.handshake_message {
HandshakeMessage::HelloVerifyRequest(hvr) => hvr,
_ => {
panic!("unexpected handshake message");
}
},
_ => {
panic!("unexpected content");
}
};
server.read(&client_hello_record(
hello_verify_request.cookie.clone(),
1,
send_renegotiation_info,
)?)?;
server.handshake(now)?;
let response = server
.outgoing_raw_packet()
.expect("the server answers the ClientHello with its cookie");
let server_hello = match first_record(&response)?.content {
Content::Handshake(h) => match h.handshake_message {
HandshakeMessage::ServerHello(sh) => sh,
_ => {
panic!("unexpected handshake message");
}
},
_ => {
panic!("unexpected content");
}
};
let got_negotation_info = server_hello
.extensions
.iter()
.any(|v| matches!(v, Extension::RenegotiationInfo(_)));
assert_eq!(
got_negotation_info, send_renegotiation_info,
"{name}: RenegotiationInfo in ServerHello"
);
}
Ok(())
}
#[test]
fn test_read_does_not_enqueue_after_handshake_completed() {
let config = Arc::new(HandshakeConfig::new(
crypto::default_provider().expect("a built-in crypto provider is enabled for tests"),
));
let mut conn = DTLSConn::new(config, false, None);
conn.set_handshake_completed();
assert!(conn.is_handshake_completed());
assert!(conn.incoming_encrypted_packets.is_empty());
let datagram = vec![
0x16, 0xfe, 0xfd, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, ];
let _ = conn.read(&datagram);
assert!(
conn.incoming_encrypted_packets.is_empty(),
"After handshake completion, future-epoch packets must be discarded, not queued"
);
}
#[test]
fn test_read_enqueues_during_handshake() {
let config = Arc::new(HandshakeConfig::new(
crypto::default_provider().expect("a built-in crypto provider is enabled for tests"),
));
let mut conn = DTLSConn::new(config, false, None);
assert!(!conn.is_handshake_completed());
assert!(conn.incoming_encrypted_packets.is_empty());
let datagram = vec![
0x16, 0xfe, 0xfd, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, ];
let _ = conn.read(&datagram);
assert_eq!(
conn.incoming_encrypted_packets.len(),
1,
"During handshake, future-epoch packets must be queued for later processing"
);
}
#[test]
fn test_handle_incoming_queued_packets_drains_when_cipher_ready() {
use crate::cipher_suite::CipherSuite;
use crate::cipher_suite::cipher_suite_aes_128_gcm_sha256::CipherSuiteAes128GcmSha256;
let config = Arc::new(HandshakeConfig::new(
crypto::default_provider().expect("a built-in crypto provider is enabled for tests"),
));
let mut conn = DTLSConn::new(config, false, None);
assert!(!conn.is_handshake_completed());
let pkt = vec![
0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, ];
conn.incoming_encrypted_packets.push_back(pkt.clone());
assert_eq!(conn.incoming_encrypted_packets.len(), 1);
conn.handle_incoming_queued_packets().unwrap();
assert_eq!(
conn.incoming_encrypted_packets.len(),
1,
"Queue must not be drained when cipher suite is not yet initialized"
);
let mut cs = Box::new(CipherSuiteAes128GcmSha256::new(false));
let _ = cs.init(
crypto::default_provider().unwrap(),
&[0u8; 48],
&[0u8; 32],
&[0u8; 32],
false,
);
assert!(cs.is_initialized());
conn.state.cipher_suite = Some(cs);
conn.handle_incoming_queued_packets().unwrap();
assert!(
conn.incoming_encrypted_packets.is_empty(),
"Queue must be drained once the cipher suite is initialized"
);
}
#[test]
fn test_handle_incoming_queued_packets_sets_handshake_rx() {
use crate::cipher_suite::CipherSuite;
use crate::cipher_suite::cipher_suite_aes_128_gcm_sha256::CipherSuiteAes128GcmSha256;
let config = Arc::new(HandshakeConfig::new(
crypto::default_provider().expect("a built-in crypto provider is enabled for tests"),
));
let mut conn = DTLSConn::new(config, false, None);
let mut cs = Box::new(CipherSuiteAes128GcmSha256::new(false));
let _ = cs.init(
crypto::default_provider().unwrap(),
&[0u8; 48],
&[0u8; 32],
&[0u8; 32],
false,
);
conn.state.cipher_suite = Some(cs);
conn.state.remote_epoch = 0;
conn.handshake_rx = None;
let pkt = vec![
0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, ];
conn.incoming_encrypted_packets.push_back(pkt);
conn.handle_incoming_queued_packets().unwrap();
assert!(
conn.incoming_encrypted_packets.is_empty(),
"Queue must be fully drained by handle_incoming_queued_packets"
);
}
fn setup_dtls_conn_server_handshake_in_progress() -> DTLSConn {
let handshake_config = Arc::new(HandshakeConfig::new(
crypto::default_provider().expect("a built-in crypto provider is enabled for tests"),
));
DTLSConn::new(handshake_config, false, None)
}
#[test]
fn test_queued_packets_drained_when_cipher_ready() {
use crate::cipher_suite::CipherSuite;
use crate::cipher_suite::cipher_suite_aes_128_gcm_sha256::CipherSuiteAes128GcmSha256;
let mut conn = setup_dtls_conn_server_handshake_in_progress();
assert!(!conn.is_handshake_completed());
let fake_epoch1_packet: Vec<u8> = vec![
0x16, 0xfe, 0xfd, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, ];
conn.incoming_encrypted_packets
.push_back(fake_epoch1_packet);
conn.handle_incoming_queued_packets().unwrap();
assert_eq!(conn.incoming_encrypted_packets.len(), 1);
let mut cs = Box::new(CipherSuiteAes128GcmSha256::new(false));
let _ = cs.init(
crypto::default_provider().unwrap(),
&[0u8; 48],
&[0u8; 32],
&[0u8; 32],
false,
);
conn.state.cipher_suite = Some(cs);
conn.state.remote_epoch = 1;
conn.handle_incoming_queued_packets().unwrap();
assert!(
conn.incoming_encrypted_packets.is_empty(),
"After fix: queued packets must be drained once cipher suite is initialized"
);
}
#[test]
fn test_handshake_rx_set_after_queue_processing() {
use crate::cipher_suite::CipherSuite;
use crate::cipher_suite::cipher_suite_aes_128_gcm_sha256::CipherSuiteAes128GcmSha256;
let mut conn = setup_dtls_conn_server_handshake_in_progress();
let mut cs = Box::new(CipherSuiteAes128GcmSha256::new(false));
let _ = cs.init(
crypto::default_provider().unwrap(),
&[0u8; 48],
&[0u8; 32],
&[0u8; 32],
false,
);
conn.state.cipher_suite = Some(cs);
assert!(conn.handshake_rx.is_none());
let fake_handshake_packet: Vec<u8> = vec![
0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xfe, 0xfd, 0x00, 0x00, ];
conn.incoming_encrypted_packets
.push_back(fake_handshake_packet);
conn.handle_incoming_queued_packets().unwrap();
assert!(
conn.handshake_rx.is_some(),
"After fix: handshake_rx must be set when a queued packet yields hs=true"
);
}
#[test]
fn test_old_epoch_alert_honoured_until_handshake_completes() {
let fatal_alert: Vec<u8> = vec![
0x15, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x02, 0x02, 0x28, ];
let mut conn = setup_dtls_conn_server_handshake_in_progress();
conn.state.remote_epoch = 1; assert!(!conn.is_handshake_completed());
assert!(
matches!(conn.read(&fatal_alert), Err(Error::ErrAlertFatalOrClose)),
"an old-epoch alert must be accepted until the handshake completes"
);
let mut conn = setup_dtls_conn_server_handshake_in_progress();
conn.state.remote_epoch = 1;
conn.set_handshake_completed();
assert!(
conn.read(&fatal_alert).is_ok(),
"an old-epoch alert must be discarded once the handshake has completed"
);
assert!(
conn.outgoing_packets.is_empty(),
"a discarded alert was answered"
);
}
#[test]
fn test_early_encrypted_queue_is_bounded() {
let config = Arc::new(HandshakeConfig::new(
crypto::default_provider().expect("a built-in crypto provider is enabled for tests"),
));
let mut conn = DTLSConn::new(config, false, None);
for sequence in 0..(MAX_EARLY_ENCRYPTED_PACKETS as u8 + 50) {
let datagram = vec![
0x16, 0xfe, 0xfd, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, sequence, 0x00, 0x01, 0x00, ];
let _ = conn.read(&datagram);
}
assert_eq!(
conn.incoming_encrypted_packets.len(),
MAX_EARLY_ENCRYPTED_PACKETS,
"the early encrypted queue must stop growing at its cap"
);
}
#[test]
fn test_change_cipher_spec_at_the_last_epoch_is_dropped() {
use crate::cipher_suite::CipherSuite;
use crate::cipher_suite::cipher_suite_aes_128_gcm_sha256::CipherSuiteAes128GcmSha256;
let mut conn = setup_dtls_conn_server_handshake_in_progress();
let mut cs = Box::new(CipherSuiteAes128GcmSha256::new(false));
cs.init(
crypto::default_provider().unwrap(),
&[0u8; 48],
&[0u8; 32],
&[0u8; 32],
false,
)
.unwrap();
conn.state.cipher_suite = Some(cs);
conn.state.remote_epoch = u16::MAX;
let change_cipher_spec: Vec<u8> = vec![
0x14, 0xfe, 0xfd, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01,
];
let _ = conn.read(&change_cipher_spec);
assert_eq!(conn.state.remote_epoch, u16::MAX);
}
#[test]
fn test_change_cipher_spec_after_handshake_is_ignored() {
use crate::cipher_suite::CipherSuite;
use crate::cipher_suite::cipher_suite_aes_128_gcm_sha256::CipherSuiteAes128GcmSha256;
let mut conn = setup_dtls_conn_server_handshake_in_progress();
let mut cs = Box::new(CipherSuiteAes128GcmSha256::new(false));
cs.init(
crypto::default_provider().unwrap(),
&[0u8; 48],
&[0u8; 32],
&[0u8; 32],
false,
)
.unwrap();
conn.state.cipher_suite = Some(cs);
conn.state.remote_epoch = 1;
conn.set_handshake_completed();
for epoch in 1u16..200 {
let [hi, lo] = epoch.to_be_bytes();
let change_cipher_spec: Vec<u8> = vec![
0x14, 0xfe, 0xfd, hi, lo, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01,
];
let _ = conn.read(&change_cipher_spec);
}
assert_eq!(
conn.state.remote_epoch, 1,
"a spoofed ChangeCipherSpec moved the epoch"
);
assert!(
conn.replay_detector.len() <= usize::from(MAX_REMOTE_EPOCH) + 2,
"{} replay detectors",
conn.replay_detector.len()
);
}
#[test]
fn test_change_cipher_spec_moves_epoch_0_to_1_only() {
use crate::cipher_suite::CipherSuite;
use crate::cipher_suite::cipher_suite_aes_128_gcm_sha256::CipherSuiteAes128GcmSha256;
let mut conn = setup_dtls_conn_server_handshake_in_progress();
let mut cs = Box::new(CipherSuiteAes128GcmSha256::new(false));
cs.init(
crypto::default_provider().unwrap(),
&[0u8; 48],
&[0u8; 32],
&[0u8; 32],
false,
)
.unwrap();
conn.state.cipher_suite = Some(cs);
for (epoch, sequence) in [(0u8, 0u8), (1, 0), (1, 1)] {
let change_cipher_spec: Vec<u8> = vec![
0x14, 0xfe, 0xfd, 0x00, epoch, 0x00, 0x00, 0x00, 0x00, 0x00, sequence, 0x00, 0x01, 0x01,
];
let _ = conn.read(&change_cipher_spec);
assert_eq!(conn.state.remote_epoch, 1);
}
}
fn encrypt_epoch1_application_data(
peer_cipher_suite: &mut dyn crate::cipher_suite::CipherSuite,
sequence_number: u64,
payload: &[u8],
) -> Vec<u8> {
let mut record = RecordLayer::new(
PROTOCOL_VERSION1_2,
1,
Content::ApplicationData(ApplicationData {
data: BytesMut::from(payload),
}),
);
record.record_layer_header.sequence_number = sequence_number;
let mut raw = vec![];
record.marshal(&mut raw).unwrap();
peer_cipher_suite
.encrypt(&record.record_layer_header, &raw)
.unwrap()
}
#[test]
fn test_pre_handshake_application_data_is_bounded() {
use crate::cipher_suite::CipherSuite;
use crate::cipher_suite::cipher_suite_aes_128_gcm_sha256::CipherSuiteAes128GcmSha256;
let mut conn = setup_dtls_conn_server_handshake_in_progress();
let mut server_cs = Box::new(CipherSuiteAes128GcmSha256::new(false));
server_cs
.init(
crypto::default_provider().unwrap(),
&[7u8; 48],
&[1u8; 32],
&[2u8; 32],
false,
)
.unwrap();
let mut client_cs = CipherSuiteAes128GcmSha256::new(false);
client_cs
.init(
crypto::default_provider().unwrap(),
&[7u8; 48],
&[1u8; 32],
&[2u8; 32],
true,
)
.unwrap();
conn.state.cipher_suite = Some(server_cs);
conn.state.remote_epoch = 1;
let payload = vec![0xabu8; 1200];
for sequence_number in 0..10_000u64 {
let datagram = encrypt_epoch1_application_data(&mut client_cs, sequence_number, &payload);
let _ = conn.read(&datagram);
assert!(
conn.incoming_decrypted_packets.len() <= MAX_PRE_HANDSHAKE_APPLICATION_DATA_PACKETS,
"pre-handshake application data grew to {} records",
conn.incoming_decrypted_packets.len()
);
assert!(
conn.incoming_decrypted_packets
.iter()
.map(|p| p.len())
.sum::<usize>()
<= MAX_PRE_HANDSHAKE_APPLICATION_DATA_BYTES
);
assert!(
conn.incoming_application_data().is_none(),
"application data delivered before the handshake completed"
);
}
assert!(
!conn.incoming_decrypted_packets.is_empty(),
"the first records after the peer's Finished must still be kept"
);
conn.set_handshake_completed();
let held = conn.incoming_decrypted_packets.len();
for sequence_number in 10_000..10_000 + 2 * MAX_PRE_HANDSHAKE_APPLICATION_DATA_PACKETS as u64 {
let datagram = encrypt_epoch1_application_data(&mut client_cs, sequence_number, &payload);
conn.read(&datagram).unwrap();
}
assert_eq!(
conn.incoming_decrypted_packets.len(),
held + 2 * MAX_PRE_HANDSHAKE_APPLICATION_DATA_PACKETS
);
assert_eq!(
conn.incoming_application_data().unwrap().len(),
payload.len()
);
}
#[test]
fn test_a_wrong_cookie_does_not_end_the_flight() {
use crate::cipher_suite::CipherSuiteId;
use crate::compression_methods::default_compression_methods;
use crate::flight::flight2::Flight2;
use crate::handshake::handshake_message_client_hello::HandshakeMessageClientHello;
use crate::handshake::handshake_random::HandshakeRandom;
let mut conn = setup_dtls_conn_server_handshake_in_progress();
conn.current_flight = Box::new(Flight2 {});
conn.current_handshake_state = HandshakeState::Waiting;
conn.state.cookie = vec![1; COOKIE_LENGTH];
conn.state.handshake_recv_sequence = 1;
let mut handshake =
Handshake::new(HandshakeMessage::ClientHello(HandshakeMessageClientHello {
session_id: vec![],
version: PROTOCOL_VERSION1_2,
random: HandshakeRandom::default(),
cookie: vec![2; COOKIE_LENGTH],
cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256],
compression_methods: default_compression_methods(),
extensions: vec![],
}));
handshake.handshake_header.message_sequence = 1;
let mut data = vec![];
handshake.marshal(&mut data).unwrap();
assert!(
conn.cache
.push(data, 0, 1, HandshakeType::ClientHello, true)
);
for _ in 0..3 {
conn.handshake_rx = Some(());
assert_eq!(conn.handshake(Instant::now()), Ok(()));
assert!(conn.current_handshake_state == HandshakeState::Waiting);
assert!(!conn.is_failed());
assert!(conn.outgoing_raw_packet().is_none(), "no alert is sent");
}
}