Vendor dimpl 0.7.4 unmodified and patch it in from third_party
str0m's DTLS stack (dimpl) hard-codes the SRTP profile a DTLS server picks (AES-256-GCM first), with no way to configure it. Official TeamSpeak 6 clients use AES_CM_128_HMAC_SHA1_80, so we need to patch dimpl. This commit only vendors the crate as published and routes crates.io's dimpl to it; the change follows separately so it can be reviewed and dropped on its own. third_party is excluded from the workspace so dimpl's dev-dependencies and tests stay out of our builds, and own-crates.sh skips it like crates/proto. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
152 files changed
+56138
-5
No files matched your search
+104
@@ -0,0 +1,104 @@
|
||||
use super::Asn1Cert;
|
||||
use crate::buffer::Buf;
|
||||
use arrayvec::ArrayVec;
|
||||
use nom::Err;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::{IResult, number::complete::be_u24};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Certificate {
|
||||
pub certificate_list: ArrayVec<Asn1Cert, 32>,
|
||||
}
|
||||
|
||||
impl Certificate {
|
||||
pub fn new(certificate_list: ArrayVec<Asn1Cert, 32>) -> Self {
|
||||
Certificate { certificate_list }
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Certificate> {
|
||||
let original_input = input;
|
||||
let (input, total_len) = be_u24(input)?;
|
||||
let (input, certs_data) = take(total_len)(input)?;
|
||||
|
||||
// Calculate base offset for certs_data within the root buffer
|
||||
let certs_base_offset =
|
||||
base_offset + (certs_data.as_ptr() as usize - original_input.as_ptr() as usize);
|
||||
|
||||
// Parse certificates manually with dynamic base_offset
|
||||
let mut certificate_list = ArrayVec::new();
|
||||
let mut rest = certs_data;
|
||||
while !rest.is_empty() {
|
||||
let offset =
|
||||
certs_base_offset + (rest.as_ptr() as usize - certs_data.as_ptr() as usize);
|
||||
let (new_rest, cert) = Asn1Cert::parse(rest, offset)?;
|
||||
certificate_list
|
||||
.try_push(cert)
|
||||
.map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?;
|
||||
rest = new_rest;
|
||||
}
|
||||
|
||||
Ok((input, Certificate { certificate_list }))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
let total_len: usize = self
|
||||
.certificate_list
|
||||
.iter()
|
||||
.map(|cert| 3 + cert.as_slice(buf).len())
|
||||
.sum();
|
||||
output.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]);
|
||||
|
||||
for cert in &self.certificate_list {
|
||||
let cert_data = cert.as_slice(buf);
|
||||
output.extend_from_slice(&(cert_data.len() as u32).to_be_bytes()[1..]);
|
||||
output.extend_from_slice(cert_data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const MESSAGE: &[u8] = &[
|
||||
0x00, 0x00, 0x0C, // Total length
|
||||
0x00, 0x00, 0x04, // Certificate 1 length
|
||||
0x01, 0x02, 0x03, 0x04, // Certificate 1 data
|
||||
0x00, 0x00, 0x02, // Certificate 2 length
|
||||
0x05, 0x06, // Certificate 2 data
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
// Parse the message with base_offset 0
|
||||
let (rest, parsed) = Certificate::parse(MESSAGE, 0).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Serialize and compare to MESSAGE
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(MESSAGE, &mut serialized);
|
||||
assert_eq!(&*serialized, MESSAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_too_many_certificates() {
|
||||
let mut message = Vec::new();
|
||||
let total_len = 33 * 4;
|
||||
message.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]);
|
||||
for _ in 0..33 {
|
||||
message.extend_from_slice(&[0x00, 0x00, 0x01, 0xAA]);
|
||||
}
|
||||
|
||||
let result = Certificate::parse(&message, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"oversized certificate list should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
use super::{CertificateTypeVec, ClientCertificateType, DistinguishedName};
|
||||
use super::{SignatureAndHashAlgorithm, SignatureAndHashAlgorithmVec};
|
||||
use crate::buffer::Buf;
|
||||
use crate::util::{many0, many1};
|
||||
use arrayvec::ArrayVec;
|
||||
use nom::Err;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::number::complete::{be_u8, be_u16};
|
||||
use nom::{IResult, bytes::complete::take};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct CertificateRequest {
|
||||
pub certificate_types: CertificateTypeVec,
|
||||
pub supported_signature_algorithms: SignatureAndHashAlgorithmVec,
|
||||
pub certificate_authorities: ArrayVec<DistinguishedName, 32>,
|
||||
}
|
||||
|
||||
impl CertificateRequest {
|
||||
pub fn new(
|
||||
certificate_types: CertificateTypeVec,
|
||||
supported_signature_algorithms: SignatureAndHashAlgorithmVec,
|
||||
certificate_authorities: ArrayVec<DistinguishedName, 32>,
|
||||
) -> Self {
|
||||
CertificateRequest {
|
||||
certificate_types,
|
||||
supported_signature_algorithms,
|
||||
certificate_authorities,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], CertificateRequest> {
|
||||
let original_input = input;
|
||||
let (input, cert_types_len) = be_u8(input)?;
|
||||
let (input, input_type) = take(cert_types_len)(input)?;
|
||||
let (rest, certificate_types) = many1(
|
||||
ClientCertificateType::parse,
|
||||
ClientCertificateType::is_supported,
|
||||
)(input_type)?;
|
||||
if !rest.is_empty() {
|
||||
return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
let (input, sig_algs_len) = be_u16(input)?;
|
||||
let (input, input_sigs) = take(sig_algs_len)(input)?;
|
||||
let (rest, supported_signature_algorithms) = many0(
|
||||
SignatureAndHashAlgorithm::parse,
|
||||
SignatureAndHashAlgorithm::is_supported,
|
||||
)(input_sigs)?;
|
||||
if !rest.is_empty() {
|
||||
return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
let (input, cert_auths_len) = be_u16(input)?;
|
||||
let (input, input_auths) = take(cert_auths_len)(input)?;
|
||||
|
||||
// Calculate base offset for input_auths within the root buffer
|
||||
let auths_base_offset =
|
||||
base_offset + (input_auths.as_ptr() as usize - original_input.as_ptr() as usize);
|
||||
|
||||
// Parse certificate authorities manually with dynamic base_offset
|
||||
let mut certificate_authorities = ArrayVec::new();
|
||||
let mut rest = input_auths;
|
||||
while !rest.is_empty() {
|
||||
let offset =
|
||||
auths_base_offset + (rest.as_ptr() as usize - input_auths.as_ptr() as usize);
|
||||
let (new_rest, auth) = DistinguishedName::parse(rest, offset)?;
|
||||
certificate_authorities
|
||||
.try_push(auth)
|
||||
.map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?;
|
||||
rest = new_rest;
|
||||
}
|
||||
|
||||
Ok((
|
||||
input,
|
||||
CertificateRequest {
|
||||
certificate_types,
|
||||
supported_signature_algorithms,
|
||||
certificate_authorities,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
output.push(self.certificate_types.len() as u8);
|
||||
for cert_type in &self.certificate_types {
|
||||
output.push(cert_type.as_u8());
|
||||
}
|
||||
|
||||
let sig_algs_len = (self.supported_signature_algorithms.len() * 2) as u16;
|
||||
output.extend_from_slice(&sig_algs_len.to_be_bytes());
|
||||
for sig_alg in &self.supported_signature_algorithms {
|
||||
output.extend_from_slice(&sig_alg.as_u16().to_be_bytes());
|
||||
}
|
||||
|
||||
let cert_auths_len: usize = self
|
||||
.certificate_authorities
|
||||
.iter()
|
||||
.map(|name| 2 + name.as_slice(buf).len())
|
||||
.sum();
|
||||
output.extend_from_slice(&(cert_auths_len as u16).to_be_bytes());
|
||||
for name in &self.certificate_authorities {
|
||||
let name_data = name.as_slice(buf);
|
||||
output.extend_from_slice(&(name_data.len() as u16).to_be_bytes());
|
||||
output.extend_from_slice(name_data);
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if the CertificateRequest supports a specific hash algorithm
|
||||
pub fn supports_hash_algorithm(&self, hash_algorithm: super::HashAlgorithm) -> bool {
|
||||
self.supported_signature_algorithms
|
||||
.iter()
|
||||
.any(|algo| algo.hash == hash_algorithm)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
// Test message with recognized values:
|
||||
// - Certificate type: 0x40 (ECDSA_SIGN)
|
||||
// - Signature algorithms: SHA256/ECDSA (0x04, 0x03), SHA256/RSA (0x04, 0x01)
|
||||
const MESSAGE: &[u8] = &[
|
||||
0x01, // Certificate types length (1 byte)
|
||||
0x40, // Certificate type: ECDSA_SIGN
|
||||
0x00, 0x04, // Signature algorithms length (4 bytes = 2 algorithms)
|
||||
0x04, 0x03, // SHA256/ECDSA
|
||||
0x04, 0x01, // SHA256/RSA
|
||||
0x00, 0x0C, // Certificate authorities length
|
||||
0x00, 0x04, // Distinguished name 1 length
|
||||
0x01, 0x02, 0x03, 0x04, // Distinguished name 1 data
|
||||
0x00, 0x04, // Distinguished name 2 length
|
||||
0x05, 0x06, 0x07, 0x08, // Distinguished name 2 data
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn filters_unsupported_rsa_signature_algorithm() {
|
||||
// Parse the message with base_offset 0
|
||||
let (rest, parsed) = CertificateRequest::parse(MESSAGE, 0).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
assert_eq!(parsed.supported_signature_algorithms.len(), 1);
|
||||
assert_eq!(
|
||||
parsed.supported_signature_algorithms[0],
|
||||
SignatureAndHashAlgorithm::new(
|
||||
super::super::HashAlgorithm::SHA256,
|
||||
super::super::SignatureAlgorithm::ECDSA,
|
||||
)
|
||||
);
|
||||
|
||||
// Serialization must not re-advertise the filtered RSA algorithm.
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(MESSAGE, &mut serialized);
|
||||
let expected = [
|
||||
0x01, // Certificate types length (1 byte)
|
||||
0x40, // Certificate type: ECDSA_SIGN
|
||||
0x00, 0x02, // Signature algorithms length (2 bytes = 1 algorithm)
|
||||
0x04, 0x03, // SHA256/ECDSA
|
||||
0x00, 0x0C, // Certificate authorities length
|
||||
0x00, 0x04, // Distinguished name 1 length
|
||||
0x01, 0x02, 0x03, 0x04, // Distinguished name 1 data
|
||||
0x00, 0x04, // Distinguished name 2 length
|
||||
0x05, 0x06, 0x07, 0x08, // Distinguished name 2 data
|
||||
];
|
||||
assert_eq!(&*serialized, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_unsupported_types() {
|
||||
// Message with unsupported certificate types and signature algorithms
|
||||
let message_with_unsupported: &[u8] = &[
|
||||
0x03, // Certificate types length (3 bytes)
|
||||
0x01, // RSA_SIGN (unsupported, filtered)
|
||||
0x40, // ECDSA_SIGN (supported)
|
||||
0x02, // DSS_SIGN (unsupported, filtered)
|
||||
0x00, 0x06, // Signature algorithms length (6 bytes = 3 algorithms)
|
||||
0x05, 0x02, // SHA384/DSA (unsupported)
|
||||
0x04, 0x03, // SHA256/ECDSA (supported)
|
||||
0x01, 0x01, // MD5/RSA (unsupported)
|
||||
0x00, 0x00, // Certificate authorities length (0)
|
||||
];
|
||||
|
||||
let (rest, parsed) = CertificateRequest::parse(message_with_unsupported, 0).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Only supported types should remain
|
||||
assert_eq!(parsed.certificate_types.len(), 1);
|
||||
assert_eq!(
|
||||
parsed.certificate_types[0],
|
||||
ClientCertificateType::ECDSA_SIGN
|
||||
);
|
||||
|
||||
assert_eq!(parsed.supported_signature_algorithms.len(), 1);
|
||||
assert_eq!(
|
||||
parsed.supported_signature_algorithms[0],
|
||||
SignatureAndHashAlgorithm::new(
|
||||
super::super::HashAlgorithm::SHA256,
|
||||
super::super::SignatureAlgorithm::ECDSA
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_certificate_authorities_are_rejected() {
|
||||
let mut message = Vec::new();
|
||||
message.push(1); // Certificate types length
|
||||
message.push(ClientCertificateType::ECDSA_SIGN.as_u8());
|
||||
message.extend_from_slice(&0u16.to_be_bytes()); // Signature algorithms length
|
||||
|
||||
let count = 33;
|
||||
let cert_auths_len = count * 3;
|
||||
message.extend_from_slice(&(cert_auths_len as u16).to_be_bytes());
|
||||
for _ in 0..count {
|
||||
message.extend_from_slice(&1u16.to_be_bytes());
|
||||
message.push(0xAA);
|
||||
}
|
||||
|
||||
let result = CertificateRequest::parse(&message, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"too many certificate authorities should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use super::DigitallySigned;
|
||||
use crate::buffer::Buf;
|
||||
use nom::IResult;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct CertificateVerify {
|
||||
pub signed: DigitallySigned,
|
||||
}
|
||||
|
||||
impl CertificateVerify {
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], CertificateVerify> {
|
||||
let (input, signed) = DigitallySigned::parse(input, base_offset)?;
|
||||
Ok((input, CertificateVerify { signed }))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
self.signed.serialize(buf, output);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const MESSAGE: &[u8] = &[
|
||||
0x04, 0x01, // SignatureAndHashAlgorithm (SHA256 + RSA)
|
||||
0x00, 0x04, // Signature length
|
||||
0x01, 0x02, 0x03, 0x04, // Signature data
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
// Parse the message with base_offset 0
|
||||
let (rest, parsed) = CertificateVerify::parse(MESSAGE, 0).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Serialize and compare to MESSAGE
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(MESSAGE, &mut serialized);
|
||||
assert_eq!(&*serialized, MESSAGE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
use super::extensions::{ECPointFormatsExtension, SignatureAlgorithmsExtension};
|
||||
use super::extensions::{SupportedGroupsExtension, UseSrtpExtension};
|
||||
use super::{CipherSuiteVec, CompressionMethod, CompressionMethodVec, Dtls12CipherSuite};
|
||||
use super::{Cookie, Extension, ExtensionType, ProtocolVersion, Random, SessionId};
|
||||
use arrayvec::ArrayVec;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::number::complete::{be_u8, be_u16};
|
||||
use nom::{Err, IResult};
|
||||
|
||||
use super::extension::ExtensionVec;
|
||||
use crate::Config;
|
||||
use crate::buffer::Buf;
|
||||
use crate::util::many1;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ClientHello {
|
||||
pub client_version: ProtocolVersion,
|
||||
pub random: Random,
|
||||
pub session_id: SessionId,
|
||||
pub cookie: Cookie,
|
||||
pub cipher_suites: CipherSuiteVec,
|
||||
pub compression_methods: CompressionMethodVec,
|
||||
pub extensions: ExtensionVec,
|
||||
}
|
||||
|
||||
impl ClientHello {
|
||||
pub fn new(
|
||||
client_version: ProtocolVersion,
|
||||
random: Random,
|
||||
session_id: SessionId,
|
||||
cookie: Cookie,
|
||||
cipher_suites: CipherSuiteVec,
|
||||
compression_methods: CompressionMethodVec,
|
||||
) -> Self {
|
||||
ClientHello {
|
||||
client_version,
|
||||
random,
|
||||
session_id,
|
||||
cookie,
|
||||
cipher_suites,
|
||||
compression_methods,
|
||||
extensions: ArrayVec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add all required extensions for DTLS handshake
|
||||
pub fn with_extensions(mut self, buf: &mut Buf, config: &Config) -> Self {
|
||||
// Clear the extension data buffer
|
||||
buf.clear();
|
||||
|
||||
// First write all extension data
|
||||
let mut ranges = ArrayVec::<(ExtensionType, usize, usize), 8>::new();
|
||||
|
||||
// Check if provider has ECDH support
|
||||
let has_ecdh = config.crypto_provider().has_ecdh();
|
||||
|
||||
// Add supported groups and EC point formats if using ECDH
|
||||
if has_ecdh {
|
||||
// Add supported groups extension from config
|
||||
let mut groups = super::NamedGroupVec::new();
|
||||
for kx_group in config.kx_groups() {
|
||||
groups.push(kx_group.name());
|
||||
}
|
||||
let supported_groups = SupportedGroupsExtension { groups };
|
||||
let start_pos = buf.len();
|
||||
supported_groups.serialize(buf);
|
||||
ranges.push((ExtensionType::SupportedGroups, start_pos, buf.len()));
|
||||
|
||||
// Add EC point formats extension
|
||||
let ec_point_formats = ECPointFormatsExtension::default();
|
||||
let start_pos = buf.len();
|
||||
ec_point_formats.serialize(buf);
|
||||
ranges.push((ExtensionType::EcPointFormats, start_pos, buf.len()));
|
||||
}
|
||||
|
||||
// Add signature algorithms extension (required for TLS 1.2+)
|
||||
let signature_algorithms = SignatureAlgorithmsExtension::default();
|
||||
let start_pos = buf.len();
|
||||
signature_algorithms.serialize(buf);
|
||||
ranges.push((ExtensionType::SignatureAlgorithms, start_pos, buf.len()));
|
||||
|
||||
// Add use_srtp extension for DTLS-SRTP support
|
||||
let use_srtp = UseSrtpExtension::default();
|
||||
let start_pos = buf.len();
|
||||
use_srtp.serialize(buf);
|
||||
ranges.push((ExtensionType::UseSrtp, start_pos, buf.len()));
|
||||
|
||||
// // Add session_ticket extension (empty)
|
||||
// let start_pos = buf.len();
|
||||
// buf.extend_from_slice(&[0x00]); // Empty extension data
|
||||
// ranges.push((ExtensionType::SessionTicket, start_pos, buf.len()));
|
||||
|
||||
let need_etm = self
|
||||
.cipher_suites
|
||||
.iter()
|
||||
.any(|suite| suite.need_encrypt_then_mac());
|
||||
if need_etm {
|
||||
// Add encrypt_then_mac extension (empty)
|
||||
let start_pos = buf.len();
|
||||
buf.extend_from_slice(&[0x00]); // Empty extension data
|
||||
ranges.push((ExtensionType::EncryptThenMac, start_pos, buf.len()));
|
||||
}
|
||||
|
||||
let start_pos = buf.len();
|
||||
ranges.push((
|
||||
ExtensionType::ExtendedMasterSecret,
|
||||
start_pos,
|
||||
start_pos, // No data at all
|
||||
));
|
||||
|
||||
// Now create all extensions using ranges
|
||||
for (extension_type, start, end) in ranges {
|
||||
self.extensions.push(Extension {
|
||||
extension_type,
|
||||
extension_data_range: start..end,
|
||||
});
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientHello> {
|
||||
let original_input = input;
|
||||
let (input, client_version) = ProtocolVersion::parse(input)?;
|
||||
let (input, random) = Random::parse(input)?;
|
||||
let (input, session_id) = SessionId::parse(input)?;
|
||||
let (input, cookie) = Cookie::parse(input)?;
|
||||
let (input, cipher_suites_len) = be_u16(input)?;
|
||||
let (input, input_cipher) = take(cipher_suites_len)(input)?;
|
||||
let (rest, cipher_suites) =
|
||||
many1(Dtls12CipherSuite::parse, Dtls12CipherSuite::is_supported)(input_cipher)?;
|
||||
if !rest.is_empty() {
|
||||
return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue)));
|
||||
}
|
||||
let (input, compression_methods_len) = be_u8(input)?;
|
||||
let (input, input_compression) = take(compression_methods_len)(input)?;
|
||||
let (rest, compression_methods) =
|
||||
many1(CompressionMethod::parse, CompressionMethod::is_supported)(input_compression)?;
|
||||
if !rest.is_empty() {
|
||||
return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
// Calculate base_offset for extensions parsing
|
||||
let consumed = input.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let extensions_base_offset = base_offset + consumed;
|
||||
|
||||
// Parse extensions if there are any left
|
||||
let (remaining_input, extensions) = Self::parse_extensions(input, extensions_base_offset)?;
|
||||
|
||||
Ok((
|
||||
remaining_input,
|
||||
ClientHello {
|
||||
client_version,
|
||||
random,
|
||||
session_id,
|
||||
cookie,
|
||||
cipher_suites,
|
||||
compression_methods,
|
||||
extensions,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Parse extensions from the input, filtering to only known extension types
|
||||
fn parse_extensions(input: &[u8], base_offset: usize) -> IResult<&[u8], ExtensionVec> {
|
||||
let mut extensions = ArrayVec::new();
|
||||
|
||||
// Early return if input is empty
|
||||
if input.is_empty() {
|
||||
return Ok((input, extensions));
|
||||
}
|
||||
|
||||
let original_input = input;
|
||||
|
||||
// Parse extensions length
|
||||
let (remaining, extensions_len) = be_u16(input)?;
|
||||
|
||||
// Early return if extensions length is 0
|
||||
if extensions_len == 0 {
|
||||
return Ok((remaining, extensions));
|
||||
}
|
||||
|
||||
// Take the extensions data
|
||||
let (remaining, extensions_data) = take(extensions_len)(remaining)?;
|
||||
|
||||
// Calculate base_offset for extension data
|
||||
let consumed = extensions_data.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let data_base_offset = base_offset + consumed;
|
||||
|
||||
// Parse individual extensions, filtering to only known types
|
||||
let mut extensions_rest = extensions_data;
|
||||
let mut current_offset = data_base_offset;
|
||||
while !extensions_rest.is_empty() {
|
||||
let before_len = extensions_rest.len();
|
||||
let (rest, extension) = Extension::parse(extensions_rest, current_offset)?;
|
||||
let parsed_len = before_len - rest.len();
|
||||
current_offset += parsed_len;
|
||||
|
||||
// Only keep supported extension types
|
||||
if extension.extension_type.is_supported() {
|
||||
if extensions
|
||||
.iter()
|
||||
.any(|existing| existing.extension_type == extension.extension_type)
|
||||
{
|
||||
return Err(Err::Failure(Error::new(
|
||||
extensions_rest,
|
||||
ErrorKind::LengthValue,
|
||||
)));
|
||||
}
|
||||
extensions.try_push(extension).map_err(|_| {
|
||||
Err::Failure(Error::new(extensions_rest, ErrorKind::LengthValue))
|
||||
})?;
|
||||
}
|
||||
extensions_rest = rest;
|
||||
}
|
||||
|
||||
Ok((remaining, extensions))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) {
|
||||
output.extend_from_slice(&self.client_version.as_u16().to_be_bytes());
|
||||
self.random.serialize(output);
|
||||
output.push(self.session_id.len() as u8);
|
||||
output.extend_from_slice(&self.session_id);
|
||||
output.push(self.cookie.len() as u8);
|
||||
output.extend_from_slice(&self.cookie);
|
||||
output.extend_from_slice(&(self.cipher_suites.len() as u16 * 2).to_be_bytes());
|
||||
for suite in &self.cipher_suites {
|
||||
output.extend_from_slice(&suite.as_u16().to_be_bytes());
|
||||
}
|
||||
output.push(self.compression_methods.len() as u8);
|
||||
for method in &self.compression_methods {
|
||||
output.push(method.as_u8());
|
||||
}
|
||||
|
||||
// Add extensions if any
|
||||
if !self.extensions.is_empty() {
|
||||
// First calculate total extensions length
|
||||
let mut extensions_len = 0;
|
||||
for ext in &self.extensions {
|
||||
// Extension type (2) + Extension length (2) + Extension data
|
||||
let ext_data = ext.extension_data(source_buf);
|
||||
extensions_len += 4 + ext_data.len();
|
||||
}
|
||||
|
||||
// Write extensions length
|
||||
output.extend_from_slice(&(extensions_len as u16).to_be_bytes());
|
||||
|
||||
// Write each extension
|
||||
for ext in &self.extensions {
|
||||
ext.serialize(source_buf, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const MESSAGE: &[u8] = &[
|
||||
0xFE, 0xFD, // ProtocolVersion::DTLS1_2
|
||||
// Random
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E,
|
||||
0x1F, 0x20, //
|
||||
0x01, // SessionId length
|
||||
0xAA, // SessionId
|
||||
0x01, // Cookie length
|
||||
0xBB, // Cookie
|
||||
0x00, 0x04, // Dtls12CipherSuites length
|
||||
0xC0, 0x2B, // Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
0xC0, 0x2C, // Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384
|
||||
0x01, // CompressionMethods length
|
||||
0x00, // CompressionMethod::Null
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let random = Random::parse(&MESSAGE[2..34]).unwrap().1;
|
||||
let session_id = SessionId::try_new(&[0xAA]).unwrap();
|
||||
let cookie = Cookie::try_new(&[0xBB]).unwrap();
|
||||
let mut cipher_suites = ArrayVec::new();
|
||||
cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256);
|
||||
cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384);
|
||||
let mut compression_methods = ArrayVec::new();
|
||||
compression_methods.push(CompressionMethod::Null);
|
||||
|
||||
let client_hello = ClientHello::new(
|
||||
ProtocolVersion::DTLS1_2,
|
||||
random,
|
||||
session_id,
|
||||
cookie,
|
||||
cipher_suites,
|
||||
compression_methods,
|
||||
);
|
||||
|
||||
// Serialize and compare to MESSAGE
|
||||
let mut serialized = Buf::new();
|
||||
client_hello.serialize(&[], &mut serialized);
|
||||
assert_eq!(&*serialized, MESSAGE);
|
||||
|
||||
// Parse and compare with original
|
||||
let (rest, parsed) = ClientHello::parse(&serialized, 0).unwrap();
|
||||
assert_eq!(parsed, client_hello);
|
||||
|
||||
assert!(rest.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_id_too_long() {
|
||||
let mut message = MESSAGE.to_vec();
|
||||
message[34] = 0x21; // SessionId length (33, which is too long)
|
||||
|
||||
let result = ClientHello::parse(&message, 0);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_too_long() {
|
||||
let mut message = MESSAGE.to_vec();
|
||||
message[36] = 0xFF; // Cookie length (255, which is too long)
|
||||
|
||||
let result = ClientHello::parse(&message, 0);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_supported_extensions_are_rejected() {
|
||||
for count in [2, 9] {
|
||||
let mut message = MESSAGE.to_vec();
|
||||
message.extend_from_slice(&(count as u16 * 4).to_be_bytes());
|
||||
for _ in 0..count {
|
||||
message
|
||||
.extend_from_slice(&ExtensionType::ExtendedMasterSecret.as_u16().to_be_bytes());
|
||||
message.extend_from_slice(&0u16.to_be_bytes());
|
||||
}
|
||||
|
||||
let result = ClientHello::parse(&message, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"duplicate supported extensions should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
use super::KeyExchangeAlgorithm;
|
||||
use super::{CurveType, NamedGroup};
|
||||
use crate::buffer::Buf;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::Error;
|
||||
use nom::number::complete::be_u8;
|
||||
use nom::{Err, IResult};
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ClientKeyExchange {
|
||||
pub exchange_keys: ExchangeKeys,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ExchangeKeys {
|
||||
Ecdh(ClientEcdhKeys),
|
||||
Psk(ClientPskKeys),
|
||||
}
|
||||
|
||||
/// ECDHE key exchange parameters
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ClientEcdhKeys {
|
||||
pub curve_type: CurveType,
|
||||
pub named_group: NamedGroup,
|
||||
pub public_key_range: Range<usize>,
|
||||
}
|
||||
|
||||
impl ClientEcdhKeys {
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientEcdhKeys> {
|
||||
let original_input = input;
|
||||
let (input, public_key_length) = be_u8(input)?;
|
||||
let (input, public_key_slice) = take(public_key_length)(input)?;
|
||||
|
||||
// Calculate absolute range in root buffer
|
||||
let relative_offset = public_key_slice.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let start = base_offset + relative_offset;
|
||||
let end = start + public_key_slice.len();
|
||||
|
||||
Ok((
|
||||
input,
|
||||
ClientEcdhKeys {
|
||||
// In ClientKeyExchange, we don't include curve_type and named_group
|
||||
// since they're already established during ServerKeyExchange
|
||||
curve_type: CurveType::NamedCurve, // Default
|
||||
named_group: NamedGroup::Secp256r1, // Default
|
||||
public_key_range: start..end,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn public_key<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
&buf[self.public_key_range.clone()]
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
// For client key exchange, we only need to include the public key length and value
|
||||
// The curve_type and named_group are already established during ServerKeyExchange
|
||||
let public_key = self.public_key(buf);
|
||||
output.push(public_key.len() as u8);
|
||||
output.extend_from_slice(public_key);
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientKeyExchange {
|
||||
pub fn parse(
|
||||
input: &[u8],
|
||||
base_offset: usize,
|
||||
key_exchange_algorithm: KeyExchangeAlgorithm,
|
||||
) -> IResult<&[u8], ClientKeyExchange> {
|
||||
let (input, exchange_keys) = match key_exchange_algorithm {
|
||||
KeyExchangeAlgorithm::EECDH => {
|
||||
let (input, ecdh_keys) = ClientEcdhKeys::parse(input, base_offset)?;
|
||||
(input, ExchangeKeys::Ecdh(ecdh_keys))
|
||||
}
|
||||
KeyExchangeAlgorithm::PSK => {
|
||||
let (input, psk_keys) = ClientPskKeys::parse(input, base_offset)?;
|
||||
(input, ExchangeKeys::Psk(psk_keys))
|
||||
}
|
||||
_ => return Err(Err::Failure(Error::new(input, nom::error::ErrorKind::Tag))),
|
||||
};
|
||||
|
||||
Ok((input, ClientKeyExchange { exchange_keys }))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
match &self.exchange_keys {
|
||||
ExchangeKeys::Ecdh(ecdh_keys) => ecdh_keys.serialize(buf, output),
|
||||
ExchangeKeys::Psk(psk_keys) => psk_keys.serialize(buf, output),
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper to serialize directly from public key bytes (for sending)
|
||||
pub fn serialize_from_bytes(public_key: &[u8], output: &mut Buf) {
|
||||
output.push(public_key.len() as u8);
|
||||
output.extend_from_slice(public_key);
|
||||
}
|
||||
}
|
||||
|
||||
/// PSK identity sent by the client (RFC 4279 §2).
|
||||
///
|
||||
/// Wire format: `uint16 identity_length + identity`
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ClientPskKeys {
|
||||
pub identity_range: Range<usize>,
|
||||
}
|
||||
|
||||
impl ClientPskKeys {
|
||||
pub fn identity<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
&buf[self.identity_range.clone()]
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientPskKeys> {
|
||||
let original_input = input;
|
||||
let (input, identity_len) = nom::number::complete::be_u16(input)?;
|
||||
let (input, identity_slice) = take(identity_len as usize)(input)?;
|
||||
|
||||
let relative_offset = identity_slice.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let start = base_offset + relative_offset;
|
||||
let end = start + identity_slice.len();
|
||||
|
||||
Ok((
|
||||
input,
|
||||
ClientPskKeys {
|
||||
identity_range: start..end,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
let identity = self.identity(buf);
|
||||
output.extend_from_slice(&(identity.len() as u16).to_be_bytes());
|
||||
output.extend_from_slice(identity);
|
||||
}
|
||||
|
||||
/// Serialize directly from identity bytes (for sending).
|
||||
pub fn serialize_from_bytes(identity: &[u8], output: &mut Buf) {
|
||||
output.extend_from_slice(&(identity.len() as u16).to_be_bytes());
|
||||
output.extend_from_slice(identity);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::super::KeyExchangeAlgorithm;
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const ECDH_MESSAGE: &[u8] = &[
|
||||
0x04, // Public key length
|
||||
0x01, 0x02, 0x03, 0x04, // Public key data
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn roundtrip_ecdh() {
|
||||
// Parse the message with base_offset 0
|
||||
let (rest, parsed) =
|
||||
ClientKeyExchange::parse(ECDH_MESSAGE, 0, KeyExchangeAlgorithm::EECDH).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Serialize and compare to ECDH_MESSAGE
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(ECDH_MESSAGE, &mut serialized);
|
||||
assert_eq!(&*serialized, ECDH_MESSAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psk_roundtrip() {
|
||||
const PSK_MESSAGE: &[u8] = &[
|
||||
0x00, 0x05, // identity length = 5
|
||||
b'h', b'e', b'l', b'l', b'o',
|
||||
];
|
||||
let (rest, parsed) =
|
||||
ClientKeyExchange::parse(PSK_MESSAGE, 0, KeyExchangeAlgorithm::PSK).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
let ExchangeKeys::Psk(psk) = &parsed.exchange_keys else {
|
||||
panic!("expected Psk variant");
|
||||
};
|
||||
assert_eq!(&PSK_MESSAGE[psk.identity_range.clone()], b"hello");
|
||||
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(PSK_MESSAGE, &mut serialized);
|
||||
assert_eq!(&*serialized, PSK_MESSAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psk_rejects_oversized_length() {
|
||||
// identity_length=0x0064 (100) but only 3 bytes follow — parser must fail
|
||||
let bad: &[u8] = &[0x00, 0x64, b'a', b'b', b'c'];
|
||||
let result = ClientKeyExchange::parse(bad, 0, KeyExchangeAlgorithm::PSK);
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"parser must reject PSK identity shorter than advertised length"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psk_empty_identity() {
|
||||
// identity_length=0 is wire-legal; parser should accept an empty range.
|
||||
// (RFC 4279 §5.1 says server MAY reject this — that's an application
|
||||
// policy decision, not a parse error.)
|
||||
let empty: &[u8] = &[0x00, 0x00];
|
||||
let (rest, parsed) = ClientKeyExchange::parse(empty, 0, KeyExchangeAlgorithm::PSK).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
let ExchangeKeys::Psk(psk) = &parsed.exchange_keys else {
|
||||
panic!("expected Psk variant");
|
||||
};
|
||||
assert!(psk.identity_range.is_empty());
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,68 @@
|
||||
use super::SignatureAndHashAlgorithm;
|
||||
use crate::buffer::Buf;
|
||||
use nom::number::complete::be_u16;
|
||||
use nom::{IResult, bytes::complete::take};
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct DigitallySigned {
|
||||
pub algorithm: SignatureAndHashAlgorithm,
|
||||
pub signature_range: Range<usize>,
|
||||
}
|
||||
|
||||
impl DigitallySigned {
|
||||
pub fn signature<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
&buf[self.signature_range.clone()]
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], DigitallySigned> {
|
||||
let original_input = input;
|
||||
let (rest, algorithm) = SignatureAndHashAlgorithm::parse(input)?;
|
||||
let (rest, signature_len) = be_u16(rest)?;
|
||||
let (rest, signature_slice) = take(signature_len)(rest)?;
|
||||
|
||||
// Calculate absolute range in root buffer
|
||||
let relative_offset = signature_slice.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let start = base_offset + relative_offset;
|
||||
let end = start + signature_slice.len();
|
||||
|
||||
Ok((
|
||||
rest,
|
||||
DigitallySigned {
|
||||
algorithm,
|
||||
signature_range: start..end,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
output.extend_from_slice(&self.algorithm.as_u16().to_be_bytes());
|
||||
let signature = self.signature(buf);
|
||||
output.extend_from_slice(&(signature.len() as u16).to_be_bytes());
|
||||
output.extend_from_slice(signature);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const MESSAGE: &[u8] = &[
|
||||
0x04, 0x01, // SignatureAndHashAlgorithm (SHA256 + RSA)
|
||||
0x00, 0x04, // Signature length
|
||||
0x01, 0x02, 0x03, 0x04, // Signature data
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
// Parse the message with base_offset 0
|
||||
let (rest, parsed) = DigitallySigned::parse(MESSAGE, 0).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Serialize and compare to MESSAGE
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(MESSAGE, &mut serialized);
|
||||
assert_eq!(&*serialized, MESSAGE);
|
||||
}
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
use crate::buffer::Buf;
|
||||
use arrayvec::ArrayVec;
|
||||
use nom::{IResult, bytes::complete::take, number::complete::be_u16};
|
||||
use std::{fmt, ops::Range};
|
||||
|
||||
pub type ExtensionVec = ArrayVec<Extension, { ExtensionType::supported().len() }>;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Default)]
|
||||
pub struct Extension {
|
||||
pub extension_type: ExtensionType,
|
||||
pub extension_data_range: Range<usize>,
|
||||
}
|
||||
|
||||
impl Extension {
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Extension> {
|
||||
let original_input = input;
|
||||
let (input, extension_type) = ExtensionType::parse(input)?;
|
||||
let (input, extension_length) = be_u16(input)?;
|
||||
let (input, extension_data_slice) = if extension_length > 0 {
|
||||
take(extension_length)(input)?
|
||||
} else {
|
||||
(input, &input[0..0])
|
||||
};
|
||||
|
||||
// Calculate absolute range in root buffer
|
||||
let relative_offset =
|
||||
extension_data_slice.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let start = base_offset + relative_offset;
|
||||
let end = start + extension_data_slice.len();
|
||||
|
||||
Ok((
|
||||
input,
|
||||
Extension {
|
||||
extension_type,
|
||||
extension_data_range: start..end,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn extension_data<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
&buf[self.extension_data_range.clone()]
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
let extension_data = self.extension_data(buf);
|
||||
output.extend_from_slice(&self.extension_type.as_u16().to_be_bytes());
|
||||
output.extend_from_slice(&(extension_data.len() as u16).to_be_bytes());
|
||||
if !extension_data.is_empty() {
|
||||
output.extend_from_slice(extension_data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub struct ExtensionType(u16);
|
||||
|
||||
#[allow(non_upper_case_globals)]
|
||||
impl ExtensionType {
|
||||
pub const ServerName: Self = Self(0x0000);
|
||||
pub const MaxFragmentLength: Self = Self(0x0001);
|
||||
pub const ClientCertificateUrl: Self = Self(0x0002);
|
||||
pub const TrustedCaKeys: Self = Self(0x0003);
|
||||
pub const TruncatedHmac: Self = Self(0x0004);
|
||||
pub const StatusRequest: Self = Self(0x0005);
|
||||
pub const UserMapping: Self = Self(0x0006);
|
||||
pub const ClientAuthz: Self = Self(0x0007);
|
||||
pub const ServerAuthz: Self = Self(0x0008);
|
||||
pub const CertType: Self = Self(0x0009);
|
||||
pub const SupportedGroups: Self = Self(0x000A);
|
||||
pub const EcPointFormats: Self = Self(0x000B);
|
||||
pub const Srp: Self = Self(0x000C);
|
||||
pub const SignatureAlgorithms: Self = Self(0x000D);
|
||||
pub const UseSrtp: Self = Self(0x000E);
|
||||
pub const Heartbeat: Self = Self(0x000F);
|
||||
pub const ApplicationLayerProtocolNegotiation: Self = Self(0x0010);
|
||||
pub const StatusRequestV2: Self = Self(0x0011);
|
||||
pub const SignedCertificateTimestamp: Self = Self(0x0012);
|
||||
pub const ClientCertificateType: Self = Self(0x0013);
|
||||
pub const ServerCertificateType: Self = Self(0x0014);
|
||||
pub const Padding: Self = Self(0x0015);
|
||||
pub const EncryptThenMac: Self = Self(0x0016);
|
||||
pub const ExtendedMasterSecret: Self = Self(0x0017);
|
||||
pub const TokenBinding: Self = Self(0x0018);
|
||||
pub const CachedInfo: Self = Self(0x0019);
|
||||
pub const SessionTicket: Self = Self(0x0023);
|
||||
pub const PreSharedKey: Self = Self(0x0029);
|
||||
pub const EarlyData: Self = Self(0x002A);
|
||||
pub const SupportedVersions: Self = Self(0x002B);
|
||||
pub const Cookie: Self = Self(0x002C);
|
||||
pub const PskKeyExchangeModes: Self = Self(0x002D);
|
||||
pub const CertificateAuthorities: Self = Self(0x002F);
|
||||
pub const OidFilters: Self = Self(0x0030);
|
||||
pub const PostHandshakeAuth: Self = Self(0x0031);
|
||||
pub const SignatureAlgorithmsCert: Self = Self(0x0032);
|
||||
pub const KeyShare: Self = Self(0x0033);
|
||||
pub const RenegotiationInfo: Self = Self(0xFF01);
|
||||
|
||||
pub const fn from_u16(value: u16) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
pub const fn as_u16(&self) -> u16 {
|
||||
self.0
|
||||
}
|
||||
|
||||
const fn is_unknown(&self) -> bool {
|
||||
!matches!(
|
||||
*self,
|
||||
Self(0x0000..=0x0019 | 0x0023 | 0x0029..=0x002D | 0x002F..=0x0033 | 0xFF01)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], ExtensionType> {
|
||||
let (input, value) = be_u16(input)?;
|
||||
Ok((input, ExtensionType::from_u16(value)))
|
||||
}
|
||||
|
||||
/// Returns true if this extension type is supported by this implementation.
|
||||
pub fn is_supported(&self) -> bool {
|
||||
Self::supported().contains(self)
|
||||
}
|
||||
|
||||
/// Supported extension types that this implementation handles.
|
||||
pub const fn supported() -> &'static [ExtensionType; 8] {
|
||||
&[
|
||||
ExtensionType::SupportedGroups,
|
||||
ExtensionType::EcPointFormats,
|
||||
ExtensionType::SignatureAlgorithms,
|
||||
ExtensionType::UseSrtp,
|
||||
ExtensionType::EncryptThenMac,
|
||||
ExtensionType::ExtendedMasterSecret,
|
||||
ExtensionType::RenegotiationInfo,
|
||||
ExtensionType::SessionTicket,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ExtensionType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.is_unknown() {
|
||||
return f.debug_tuple("Unknown").field(&self.0).finish();
|
||||
}
|
||||
|
||||
let name = match *self {
|
||||
ExtensionType::ServerName => "ServerName",
|
||||
ExtensionType::MaxFragmentLength => "MaxFragmentLength",
|
||||
ExtensionType::ClientCertificateUrl => "ClientCertificateUrl",
|
||||
ExtensionType::TrustedCaKeys => "TrustedCaKeys",
|
||||
ExtensionType::TruncatedHmac => "TruncatedHmac",
|
||||
ExtensionType::StatusRequest => "StatusRequest",
|
||||
ExtensionType::UserMapping => "UserMapping",
|
||||
ExtensionType::ClientAuthz => "ClientAuthz",
|
||||
ExtensionType::ServerAuthz => "ServerAuthz",
|
||||
ExtensionType::CertType => "CertType",
|
||||
ExtensionType::SupportedGroups => "SupportedGroups",
|
||||
ExtensionType::EcPointFormats => "EcPointFormats",
|
||||
ExtensionType::Srp => "Srp",
|
||||
ExtensionType::SignatureAlgorithms => "SignatureAlgorithms",
|
||||
ExtensionType::UseSrtp => "UseSrtp",
|
||||
ExtensionType::Heartbeat => "Heartbeat",
|
||||
ExtensionType::ApplicationLayerProtocolNegotiation => {
|
||||
"ApplicationLayerProtocolNegotiation"
|
||||
}
|
||||
ExtensionType::StatusRequestV2 => "StatusRequestV2",
|
||||
ExtensionType::SignedCertificateTimestamp => "SignedCertificateTimestamp",
|
||||
ExtensionType::ClientCertificateType => "ClientCertificateType",
|
||||
ExtensionType::ServerCertificateType => "ServerCertificateType",
|
||||
ExtensionType::Padding => "Padding",
|
||||
ExtensionType::EncryptThenMac => "EncryptThenMac",
|
||||
ExtensionType::ExtendedMasterSecret => "ExtendedMasterSecret",
|
||||
ExtensionType::TokenBinding => "TokenBinding",
|
||||
ExtensionType::CachedInfo => "CachedInfo",
|
||||
ExtensionType::SessionTicket => "SessionTicket",
|
||||
ExtensionType::PreSharedKey => "PreSharedKey",
|
||||
ExtensionType::EarlyData => "EarlyData",
|
||||
ExtensionType::SupportedVersions => "SupportedVersions",
|
||||
ExtensionType::Cookie => "Cookie",
|
||||
ExtensionType::PskKeyExchangeModes => "PskKeyExchangeModes",
|
||||
ExtensionType::CertificateAuthorities => "CertificateAuthorities",
|
||||
ExtensionType::OidFilters => "OidFilters",
|
||||
ExtensionType::PostHandshakeAuth => "PostHandshakeAuth",
|
||||
ExtensionType::SignatureAlgorithmsCert => "SignatureAlgorithmsCert",
|
||||
ExtensionType::KeyShare => "KeyShare",
|
||||
ExtensionType::RenegotiationInfo => "RenegotiationInfo",
|
||||
_ => unreachable!("known DTLS 1.2 extension type missing Debug label"),
|
||||
};
|
||||
|
||||
f.write_str(name)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const MESSAGE: &[u8] = &[
|
||||
0x00, 0x0A, // ExtensionType::SupportedGroups
|
||||
0x00, 0x08, // Extension length
|
||||
0x00, 0x06, 0x00, 0x17, 0x00, 0x18, 0x00, 0x19, // Extension data
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn extension_type_newtype_shape() {
|
||||
assert_eq!(std::mem::size_of::<ExtensionType>(), 2);
|
||||
assert_eq!(ExtensionType::default().as_u16(), 0);
|
||||
assert_eq!(ExtensionType::default(), ExtensionType::ServerName);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extension_type_wire_roundtrip() {
|
||||
for extension_type in ExtensionType::supported() {
|
||||
assert_eq!(
|
||||
ExtensionType::from_u16(extension_type.as_u16()),
|
||||
*extension_type
|
||||
);
|
||||
assert!(!extension_type.is_unknown());
|
||||
}
|
||||
|
||||
let unknown = ExtensionType::from_u16(0xFFFF);
|
||||
assert_eq!(unknown.as_u16(), 0xFFFF);
|
||||
assert!(unknown.is_unknown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extension_type_debug_stays_enum_like() {
|
||||
assert_eq!(
|
||||
format!("{:?}", ExtensionType::SupportedGroups),
|
||||
"SupportedGroups"
|
||||
);
|
||||
assert_eq!(
|
||||
format!("{:?}", ExtensionType::from_u16(0xFFFF)),
|
||||
"Unknown(65535)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
// Parse the message with base_offset 0
|
||||
let (rest, parsed) = Extension::parse(MESSAGE, 0).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Serialize and compare to MESSAGE
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(MESSAGE, &mut serialized);
|
||||
assert_eq!(&*serialized, MESSAGE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
use crate::buffer::Buf;
|
||||
use arrayvec::ArrayVec;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::{Err, IResult, number::complete::be_u8};
|
||||
|
||||
/// EC Point Format as defined in RFC 4492 Section 5.1.2
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
#[allow(unused)]
|
||||
pub enum ECPointFormat {
|
||||
#[default]
|
||||
Uncompressed = 0x00,
|
||||
AnsiX962CompressedPrime = 0x01,
|
||||
AnsiX962CompressedChar2 = 0x02,
|
||||
}
|
||||
|
||||
impl ECPointFormat {
|
||||
#[allow(unused)]
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], ECPointFormat> {
|
||||
let (input, value) = be_u8(input)?;
|
||||
let format = match value {
|
||||
0x00 => ECPointFormat::Uncompressed,
|
||||
0x01 => ECPointFormat::AnsiX962CompressedPrime,
|
||||
0x02 => ECPointFormat::AnsiX962CompressedChar2,
|
||||
_ => {
|
||||
return Err(nom::Err::Error(nom::error::Error::new(
|
||||
input,
|
||||
nom::error::ErrorKind::Switch,
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok((input, format))
|
||||
}
|
||||
|
||||
pub fn as_u8(&self) -> u8 {
|
||||
*self as u8
|
||||
}
|
||||
}
|
||||
|
||||
/// ECPointFormats extension as defined in RFC 4492
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ECPointFormatsExtension {
|
||||
pub formats: ArrayVec<ECPointFormat, 3>,
|
||||
}
|
||||
|
||||
impl ECPointFormatsExtension {
|
||||
/// Create a default ECPointFormatsExtension with standard formats
|
||||
pub fn default() -> Self {
|
||||
let mut formats = ArrayVec::new();
|
||||
// Most implementations only support uncompressed format
|
||||
formats.push(ECPointFormat::Uncompressed);
|
||||
|
||||
ECPointFormatsExtension { formats }
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], ECPointFormatsExtension> {
|
||||
let (input, list_len) = be_u8(input)?;
|
||||
let (input, formats_data) = take(list_len)(input)?;
|
||||
if !input.is_empty() {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
let mut formats = ArrayVec::new();
|
||||
let mut current_input = formats_data;
|
||||
|
||||
while !current_input.is_empty() {
|
||||
let format_input = current_input;
|
||||
let (rest, format) = be_u8(current_input)?;
|
||||
let Some(format) = (match format {
|
||||
0x00 => Some(ECPointFormat::Uncompressed),
|
||||
0x01 => Some(ECPointFormat::AnsiX962CompressedPrime),
|
||||
0x02 => Some(ECPointFormat::AnsiX962CompressedChar2),
|
||||
_ => None,
|
||||
}) else {
|
||||
current_input = rest;
|
||||
continue;
|
||||
};
|
||||
|
||||
formats
|
||||
.try_push(format)
|
||||
.map_err(|_| Err::Failure(Error::new(format_input, ErrorKind::LengthValue)))?;
|
||||
current_input = rest;
|
||||
}
|
||||
|
||||
Ok((current_input, ECPointFormatsExtension { formats }))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, output: &mut Buf) {
|
||||
// Write the number of formats
|
||||
output.push(self.formats.len() as u8);
|
||||
|
||||
// Write each format
|
||||
for format in &self.formats {
|
||||
output.push(format.as_u8());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
#[test]
|
||||
fn test_ec_point_formats_extension() {
|
||||
let mut formats = ArrayVec::new();
|
||||
formats.push(ECPointFormat::Uncompressed);
|
||||
formats.push(ECPointFormat::AnsiX962CompressedPrime);
|
||||
|
||||
let ext = ECPointFormatsExtension { formats };
|
||||
|
||||
let mut serialized = Buf::new();
|
||||
ext.serialize(&mut serialized);
|
||||
|
||||
let expected = [
|
||||
0x02, // Number of formats (2)
|
||||
0x00, // Uncompressed (0x00)
|
||||
0x01, // ANSI X9.62 compressed prime (0x01)
|
||||
];
|
||||
|
||||
assert_eq!(&*serialized, expected);
|
||||
|
||||
let (_, parsed) = ECPointFormatsExtension::parse(&serialized).unwrap();
|
||||
|
||||
assert_eq!(parsed.formats.as_slice(), ext.formats.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_ec_point_formats_are_rejected() {
|
||||
let bytes = [
|
||||
0x04, // Four point formats.
|
||||
0x00, // Uncompressed.
|
||||
0x00, // Uncompressed.
|
||||
0x00, // Uncompressed.
|
||||
0x00, // Uncompressed.
|
||||
];
|
||||
|
||||
let err = ECPointFormatsExtension::parse(&bytes).unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
Err::Failure(Error {
|
||||
code: ErrorKind::LengthValue,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_ec_point_formats_are_ignored() {
|
||||
let (rest, parsed) = ECPointFormatsExtension::parse(&[
|
||||
0x03, // Three point formats.
|
||||
0x02, // ANSI X9.62 compressed char2.
|
||||
0x00, // Uncompressed.
|
||||
0xFF, // Unknown/private point format.
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
assert!(rest.is_empty());
|
||||
assert_eq!(
|
||||
parsed.formats.as_slice(),
|
||||
&[
|
||||
ECPointFormat::AnsiX962CompressedChar2,
|
||||
ECPointFormat::Uncompressed,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_ec_point_format_bytes_are_rejected() {
|
||||
let result = ECPointFormatsExtension::parse(&[
|
||||
0x01, // One point format.
|
||||
0x00, // Uncompressed.
|
||||
0xFF, // Extension body has a trailing byte beyond the vector.
|
||||
]);
|
||||
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(Err::Failure(Error {
|
||||
code: ErrorKind::LengthValue,
|
||||
..
|
||||
}))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
pub mod ec_point_formats;
|
||||
pub mod signature_algorithms;
|
||||
pub mod supported_groups;
|
||||
pub mod use_srtp;
|
||||
|
||||
pub use ec_point_formats::ECPointFormatsExtension;
|
||||
pub use signature_algorithms::SignatureAlgorithmsExtension;
|
||||
pub use supported_groups::SupportedGroupsExtension;
|
||||
pub use use_srtp::UseSrtpExtension;
|
||||
@@ -0,0 +1,213 @@
|
||||
use super::super::{SignatureAndHashAlgorithm, SignatureAndHashAlgorithmVec};
|
||||
use crate::buffer::Buf;
|
||||
use nom::Err;
|
||||
use nom::IResult;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
|
||||
/// SignatureAlgorithms extension as defined in RFC 5246
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SignatureAlgorithmsExtension {
|
||||
pub supported_signature_algorithms: SignatureAndHashAlgorithmVec,
|
||||
}
|
||||
|
||||
impl SignatureAlgorithmsExtension {
|
||||
/// Create a default SignatureAlgorithmsExtension with standard algorithms
|
||||
pub fn default() -> Self {
|
||||
SignatureAlgorithmsExtension {
|
||||
supported_signature_algorithms: SignatureAndHashAlgorithmVec::from(
|
||||
*SignatureAndHashAlgorithm::supported(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureAlgorithmsExtension> {
|
||||
let (input, list_len) = nom::number::complete::be_u16(input)?;
|
||||
if list_len == 0 || list_len % 2 != 0 {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
let mut algorithms = SignatureAndHashAlgorithmVec::new();
|
||||
let (input, mut current_input) = take(list_len)(input)?;
|
||||
if !input.is_empty() {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
// Parse algorithms, filtering to only keep supported ones
|
||||
while !current_input.is_empty() {
|
||||
let (rest, alg) = SignatureAndHashAlgorithm::parse(current_input)?;
|
||||
// Only keep supported signature+hash combinations
|
||||
if alg.is_supported() {
|
||||
algorithms
|
||||
.try_push(alg)
|
||||
.map_err(|_| Err::Failure(Error::new(current_input, ErrorKind::LengthValue)))?;
|
||||
}
|
||||
current_input = rest;
|
||||
}
|
||||
|
||||
Ok((
|
||||
input,
|
||||
SignatureAlgorithmsExtension {
|
||||
supported_signature_algorithms: algorithms,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, output: &mut Buf) {
|
||||
// Write the total length of all algorithms (2 bytes per algorithm)
|
||||
output.extend_from_slice(
|
||||
&((self.supported_signature_algorithms.len() * 2) as u16).to_be_bytes(),
|
||||
);
|
||||
|
||||
// Write each algorithm
|
||||
for alg in &self.supported_signature_algorithms {
|
||||
output.extend_from_slice(&alg.as_u16().to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::super::{HashAlgorithm, SignatureAlgorithm};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_signature_algorithms_extension() {
|
||||
let mut algorithms = SignatureAndHashAlgorithmVec::new();
|
||||
algorithms.push(SignatureAndHashAlgorithm::new(
|
||||
HashAlgorithm::SHA256,
|
||||
SignatureAlgorithm::ECDSA,
|
||||
));
|
||||
algorithms.push(SignatureAndHashAlgorithm::new(
|
||||
HashAlgorithm::SHA256,
|
||||
SignatureAlgorithm::RSA,
|
||||
));
|
||||
|
||||
let ext = SignatureAlgorithmsExtension {
|
||||
supported_signature_algorithms: algorithms.clone(),
|
||||
};
|
||||
|
||||
let mut serialized = Buf::new();
|
||||
ext.serialize(&mut serialized);
|
||||
|
||||
let expected = [
|
||||
0x00, 0x04, // Length (4 bytes)
|
||||
0x04, 0x03, // SHA256/ECDSA
|
||||
0x04, 0x01, // SHA256/RSA
|
||||
];
|
||||
|
||||
assert_eq!(&*serialized, expected);
|
||||
|
||||
let (_, parsed) = SignatureAlgorithmsExtension::parse(&serialized).unwrap();
|
||||
|
||||
assert_eq!(parsed.supported_signature_algorithms.len(), 1);
|
||||
assert_eq!(
|
||||
parsed.supported_signature_algorithms[0],
|
||||
SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA,)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_does_not_advertise_rsa() {
|
||||
let extension = SignatureAlgorithmsExtension::default();
|
||||
|
||||
assert!(
|
||||
extension
|
||||
.supported_signature_algorithms
|
||||
.iter()
|
||||
.all(|algorithm| algorithm.signature != SignatureAlgorithm::RSA)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capacity_matches_supported() {
|
||||
let extension = SignatureAlgorithmsExtension::default();
|
||||
|
||||
assert_eq!(
|
||||
extension.supported_signature_algorithms.capacity(),
|
||||
SignatureAndHashAlgorithm::supported().len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_supported_signature_algorithms_are_rejected() {
|
||||
let mut bytes = Vec::new();
|
||||
let count = SignatureAndHashAlgorithm::supported().len() + 1;
|
||||
bytes.extend_from_slice(&(count as u16 * 2).to_be_bytes());
|
||||
for _ in 0..count {
|
||||
bytes.extend_from_slice(
|
||||
&SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA)
|
||||
.as_u16()
|
||||
.to_be_bytes(),
|
||||
);
|
||||
}
|
||||
|
||||
let result = SignatureAlgorithmsExtension::parse(&bytes);
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"too many supported signature algorithms should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_length_signature_algorithms_are_rejected_without_panic() {
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
SignatureAlgorithmsExtension::parse(&[
|
||||
0x00, 0x01, // Declared list length is not divisible by 2.
|
||||
0x04, 0x03, // Extra byte proves the parser must reject before looping.
|
||||
])
|
||||
});
|
||||
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"odd signature_algorithms length must not panic"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
result.unwrap(),
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"odd signature_algorithms length should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_signature_algorithms_are_rejected() {
|
||||
let result = SignatureAlgorithmsExtension::parse(&[
|
||||
0x00, 0x00, // Empty signature_algorithms vector is invalid.
|
||||
]);
|
||||
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"empty signature_algorithms vector should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_signature_algorithms_bytes_are_rejected() {
|
||||
let result = SignatureAlgorithmsExtension::parse(&[
|
||||
0x00, 0x02, // One algorithm follows.
|
||||
0x04, 0x03, // SHA256/ECDSA
|
||||
0xff, // Extension body has a trailing byte beyond the vector.
|
||||
]);
|
||||
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"trailing signature_algorithms bytes should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
use super::super::{NamedGroup, NamedGroupVec};
|
||||
use crate::buffer::Buf;
|
||||
use nom::Err;
|
||||
use nom::IResult;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
|
||||
/// SupportedGroups extension as defined in RFC 8422
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SupportedGroupsExtension {
|
||||
pub groups: NamedGroupVec,
|
||||
}
|
||||
|
||||
impl SupportedGroupsExtension {
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], SupportedGroupsExtension> {
|
||||
let (input, list_len) = nom::number::complete::be_u16(input)?;
|
||||
if list_len % 2 != 0 {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
let (input, mut current_input) = take(list_len)(input)?;
|
||||
if !input.is_empty() {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
let mut groups = NamedGroupVec::new();
|
||||
|
||||
// Parse groups; only include supported groups (skip Unknown and unsupported)
|
||||
while !current_input.is_empty() {
|
||||
let group_input = current_input;
|
||||
let (rest, group) = NamedGroup::parse(group_input)?;
|
||||
current_input = rest;
|
||||
// Only add supported groups
|
||||
if group.is_supported() {
|
||||
groups
|
||||
.try_push(group)
|
||||
.map_err(|_| Err::Failure(Error::new(group_input, ErrorKind::LengthValue)))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok((input, SupportedGroupsExtension { groups }))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, output: &mut Buf) {
|
||||
// Write the total length of all groups (2 bytes per group)
|
||||
output.extend_from_slice(&((self.groups.len() * 2) as u16).to_be_bytes());
|
||||
|
||||
// Write each group
|
||||
for group in &self.groups {
|
||||
output.extend_from_slice(&group.as_u16().to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
#[test]
|
||||
fn test_supported_groups_extension() {
|
||||
let mut groups = NamedGroupVec::new();
|
||||
groups.push(NamedGroup::X25519);
|
||||
groups.push(NamedGroup::Secp256r1);
|
||||
|
||||
let ext = SupportedGroupsExtension { groups };
|
||||
|
||||
let mut serialized = Buf::new();
|
||||
ext.serialize(&mut serialized);
|
||||
|
||||
let expected = [
|
||||
0x00, 0x04, // Groups length (4 bytes)
|
||||
0x00, 0x1D, // X25519 (0x001D)
|
||||
0x00, 0x17, // secp256r1 (0x0017)
|
||||
];
|
||||
|
||||
assert_eq!(&*serialized, expected);
|
||||
|
||||
let (_, parsed) = SupportedGroupsExtension::parse(&serialized).unwrap();
|
||||
|
||||
assert_eq!(parsed.groups.as_slice(), ext.groups.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_supported_groups_parse_provided_bytes() {
|
||||
// Provided bytes: [0,10,0,29,0,23,0,24,1,0,1,1]
|
||||
// Meaning:
|
||||
// 0x000A -> list length = 10 bytes (5 groups)
|
||||
// groups: 0x001D (X25519), 0x0017 (P-256), 0x0018 (P-384), 0x0100 (unknown), 0x0101 (unknown)
|
||||
let bytes = [0, 10, 0, 29, 0, 23, 0, 24, 1, 0, 1, 1];
|
||||
|
||||
let (rest, parsed) =
|
||||
SupportedGroupsExtension::parse(&bytes).expect("parse SupportedGroups");
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Expect only the supported groups in order as they appear
|
||||
assert_eq!(
|
||||
parsed.groups.as_slice(),
|
||||
&[
|
||||
NamedGroup::X25519,
|
||||
NamedGroup::Secp256r1,
|
||||
NamedGroup::Secp384r1
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_supported_groups_are_rejected() {
|
||||
let mut bytes = Vec::new();
|
||||
let count = NamedGroup::supported().len() + 1;
|
||||
bytes.extend_from_slice(&(count as u16 * 2).to_be_bytes());
|
||||
for _ in 0..count {
|
||||
bytes.extend_from_slice(&NamedGroup::X25519.as_u16().to_be_bytes());
|
||||
}
|
||||
|
||||
let result = SupportedGroupsExtension::parse(&bytes);
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"too many supported groups should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_supported_groups_vector_is_rejected() {
|
||||
let result = SupportedGroupsExtension::parse(&[
|
||||
0x00, 0x03, // Declared vector length is not divisible by 2.
|
||||
0x00, 0x1D, 0xFF,
|
||||
]);
|
||||
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"odd supported_groups vector should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_supported_groups_bytes_are_rejected() {
|
||||
let result = SupportedGroupsExtension::parse(&[
|
||||
0x00, 0x02, // One named group.
|
||||
0x00, 0x1D, // X25519.
|
||||
0xFF, // Extension body has a trailing byte beyond the vector.
|
||||
]);
|
||||
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"trailing supported_groups bytes should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
use crate::SrtpProfile;
|
||||
use crate::buffer::Buf;
|
||||
use arrayvec::ArrayVec;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::number::complete::{be_u8, be_u16};
|
||||
use nom::{Err, IResult};
|
||||
|
||||
pub type SrtpProfileVec = ArrayVec<SrtpProfileId, { SrtpProfileId::supported().len() }>;
|
||||
|
||||
/// DTLS-SRTP protection profile identifiers
|
||||
/// From RFC 5764 Section 4.1.2
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum SrtpProfileId {
|
||||
#[default]
|
||||
SRTP_AES128_CM_SHA1_80 = 0x0001,
|
||||
SRTP_AEAD_AES_128_GCM = 0x0007,
|
||||
SRTP_AEAD_AES_256_GCM = 0x0008,
|
||||
}
|
||||
|
||||
impl SrtpProfileId {
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], SrtpProfileId> {
|
||||
let (input, value) = be_u16(input)?;
|
||||
let profile = match value {
|
||||
0x0001 => SrtpProfileId::SRTP_AES128_CM_SHA1_80,
|
||||
0x0007 => SrtpProfileId::SRTP_AEAD_AES_128_GCM,
|
||||
0x0008 => SrtpProfileId::SRTP_AEAD_AES_256_GCM,
|
||||
_ => {
|
||||
return Err(nom::Err::Error(nom::error::Error::new(
|
||||
input,
|
||||
nom::error::ErrorKind::Switch,
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok((input, profile))
|
||||
}
|
||||
|
||||
pub fn as_u16(&self) -> u16 {
|
||||
*self as u16
|
||||
}
|
||||
|
||||
/// All recognized SRTP profile IDs (every non-`Unknown` variant).
|
||||
pub const fn all() -> &'static [SrtpProfileId; 3] {
|
||||
&[
|
||||
SrtpProfileId::SRTP_AES128_CM_SHA1_80,
|
||||
SrtpProfileId::SRTP_AEAD_AES_128_GCM,
|
||||
SrtpProfileId::SRTP_AEAD_AES_256_GCM,
|
||||
]
|
||||
}
|
||||
|
||||
/// Supported SRTP profile IDs.
|
||||
pub const fn supported() -> &'static [SrtpProfileId; 3] {
|
||||
Self::all()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SrtpProfile> for SrtpProfileId {
|
||||
fn from(profile: SrtpProfile) -> Self {
|
||||
match profile {
|
||||
SrtpProfile::AES128_CM_SHA1_80 => SrtpProfileId::SRTP_AES128_CM_SHA1_80,
|
||||
SrtpProfile::AEAD_AES_128_GCM => SrtpProfileId::SRTP_AEAD_AES_128_GCM,
|
||||
SrtpProfile::AEAD_AES_256_GCM => SrtpProfileId::SRTP_AEAD_AES_256_GCM,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SrtpProfileId> for SrtpProfile {
|
||||
fn from(profile: SrtpProfileId) -> Self {
|
||||
match profile {
|
||||
SrtpProfileId::SRTP_AES128_CM_SHA1_80 => SrtpProfile::AES128_CM_SHA1_80,
|
||||
SrtpProfileId::SRTP_AEAD_AES_128_GCM => SrtpProfile::AEAD_AES_128_GCM,
|
||||
SrtpProfileId::SRTP_AEAD_AES_256_GCM => SrtpProfile::AEAD_AES_256_GCM,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// UseSrtp extension as defined in RFC 5764
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UseSrtpExtension {
|
||||
pub profiles: SrtpProfileVec,
|
||||
pub mki: ArrayVec<u8, 255>, // MKI value (usually empty)
|
||||
}
|
||||
|
||||
impl UseSrtpExtension {
|
||||
pub fn new(profiles: SrtpProfileVec, mki: ArrayVec<u8, 255>) -> Self {
|
||||
UseSrtpExtension { profiles, mki }
|
||||
}
|
||||
|
||||
/// Create a default UseSrtpExtension with standard profiles
|
||||
pub fn default() -> Self {
|
||||
let mut profiles = SrtpProfileVec::new();
|
||||
// Add profiles in order of preference (most secure first)
|
||||
profiles.push(SrtpProfileId::SRTP_AEAD_AES_256_GCM);
|
||||
profiles.push(SrtpProfileId::SRTP_AEAD_AES_128_GCM);
|
||||
profiles.push(SrtpProfileId::SRTP_AES128_CM_SHA1_80);
|
||||
|
||||
// MKI is typically empty as per RFC 5764
|
||||
UseSrtpExtension {
|
||||
profiles,
|
||||
mki: ArrayVec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], UseSrtpExtension> {
|
||||
let (input, profiles_length) = be_u16(input)?;
|
||||
let (input, profiles_data) = take(profiles_length)(input)?;
|
||||
|
||||
// Parse the profiles (ignore unknown profile IDs instead of failing)
|
||||
let mut profiles = SrtpProfileVec::new();
|
||||
let mut profiles_rest = profiles_data;
|
||||
|
||||
while profiles_rest.len() >= 2 {
|
||||
let profile_input = profiles_rest;
|
||||
let (rest, value) = be_u16(profile_input)?;
|
||||
profiles_rest = rest;
|
||||
match value {
|
||||
0x0001 => profiles
|
||||
.try_push(SrtpProfileId::SRTP_AES128_CM_SHA1_80)
|
||||
.map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?,
|
||||
0x0007 => profiles
|
||||
.try_push(SrtpProfileId::SRTP_AEAD_AES_128_GCM)
|
||||
.map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?,
|
||||
0x0008 => profiles
|
||||
.try_push(SrtpProfileId::SRTP_AEAD_AES_256_GCM)
|
||||
.map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?,
|
||||
_ => {
|
||||
// Unknown SRTP profile: skip
|
||||
}
|
||||
}
|
||||
}
|
||||
if !profiles_rest.is_empty() {
|
||||
return Err(Err::Failure(Error::new(
|
||||
profiles_rest,
|
||||
ErrorKind::LengthValue,
|
||||
)));
|
||||
}
|
||||
|
||||
// Parse MKI
|
||||
let (input, mki_length) = be_u8(input)?;
|
||||
let (input, mki) = take(mki_length)(input)?;
|
||||
if !input.is_empty() {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
Ok((
|
||||
input,
|
||||
UseSrtpExtension {
|
||||
profiles,
|
||||
mki: ArrayVec::try_from(mki).unwrap_or_default(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, output: &mut Buf) {
|
||||
// Length of all profiles (2 bytes per profile)
|
||||
output.extend_from_slice(&((self.profiles.len() * 2) as u16).to_be_bytes());
|
||||
|
||||
// Write each profile
|
||||
for profile in &self.profiles {
|
||||
output.extend_from_slice(&profile.as_u16().to_be_bytes());
|
||||
}
|
||||
|
||||
// MKI length and data
|
||||
output.push(self.mki.len() as u8);
|
||||
output.extend_from_slice(&self.mki);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
#[test]
|
||||
fn test_use_srtp_extension() {
|
||||
let mut profiles = SrtpProfileVec::new();
|
||||
profiles.push(SrtpProfileId::SRTP_AEAD_AES_256_GCM);
|
||||
profiles.push(SrtpProfileId::SRTP_AEAD_AES_128_GCM);
|
||||
profiles.push(SrtpProfileId::SRTP_AES128_CM_SHA1_80);
|
||||
|
||||
let mut mki = ArrayVec::new();
|
||||
mki.push(1);
|
||||
mki.push(2);
|
||||
mki.push(3);
|
||||
|
||||
let ext = UseSrtpExtension::new(profiles, mki.clone());
|
||||
|
||||
let mut serialized = Buf::new();
|
||||
ext.serialize(&mut serialized);
|
||||
|
||||
let expected = [
|
||||
0x00, 0x06, // Profiles length (6 bytes)
|
||||
0x00, 0x08, // SRTP_AEAD_AES_256_GCM (0x0008)
|
||||
0x00, 0x07, // SRTP_AEAD_AES_128_GCM (0x0007)
|
||||
0x00, 0x01, // SRTP_AES128_CM_SHA1_80 (0x0001)
|
||||
0x03, // MKI length (3 bytes)
|
||||
0x01, 0x02, 0x03, // MKI
|
||||
];
|
||||
|
||||
assert_eq!(&*serialized, expected);
|
||||
|
||||
let (_, parsed) = UseSrtpExtension::parse(&serialized).unwrap();
|
||||
|
||||
assert_eq!(parsed.profiles.as_slice(), ext.profiles.as_slice());
|
||||
assert_eq!(parsed.mki, mki);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_use_srtp_parse_provided_bytes() {
|
||||
// Provided bytes: [0,8,0,7,0,8,0,1,0,2,0]
|
||||
// Meaning:
|
||||
// 0x0008 -> profiles length = 8 bytes (4 profile IDs)
|
||||
// profiles: 0x0007, 0x0008, 0x0001, 0x0002 (0x0002 is unknown and should be ignored)
|
||||
// MKI length = 0
|
||||
let bytes = [0, 8, 0, 7, 0, 8, 0, 1, 0, 2, 0];
|
||||
|
||||
let (_, parsed) = UseSrtpExtension::parse(&bytes).expect("parse UseSrtpExtension");
|
||||
|
||||
// Expect only the three known profiles, in the same order as offered
|
||||
assert_eq!(
|
||||
parsed.profiles.as_slice(),
|
||||
&[
|
||||
SrtpProfileId::SRTP_AEAD_AES_128_GCM,
|
||||
SrtpProfileId::SRTP_AEAD_AES_256_GCM,
|
||||
SrtpProfileId::SRTP_AES128_CM_SHA1_80
|
||||
]
|
||||
);
|
||||
assert_eq!(parsed.mki, ArrayVec::<u8, 255>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_supported_srtp_profiles_are_rejected() {
|
||||
let bytes = [
|
||||
0x00, 0x08, // Four profile IDs.
|
||||
0x00, 0x01, // SRTP_AES128_CM_SHA1_80.
|
||||
0x00, 0x01, // SRTP_AES128_CM_SHA1_80.
|
||||
0x00, 0x01, // SRTP_AES128_CM_SHA1_80.
|
||||
0x00, 0x01, // SRTP_AES128_CM_SHA1_80.
|
||||
0x00, // Empty MKI.
|
||||
];
|
||||
|
||||
let err = UseSrtpExtension::parse(&bytes).unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
Err::Failure(Error {
|
||||
code: ErrorKind::LengthValue,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_srtp_profile_vector_is_rejected() {
|
||||
let bytes = [
|
||||
0x00, 0x03, // Odd profile vector length.
|
||||
0x00, 0x01, // SRTP_AES128_CM_SHA1_80.
|
||||
0x00, // Dangling byte in profile vector.
|
||||
0x00, // Empty MKI.
|
||||
];
|
||||
|
||||
let err = UseSrtpExtension::parse(&bytes).unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
Err::Failure(Error {
|
||||
code: ErrorKind::LengthValue,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_mki_bytes_are_rejected() {
|
||||
let bytes = [
|
||||
0x00, 0x02, // One profile ID.
|
||||
0x00, 0x01, // SRTP_AES128_CM_SHA1_80.
|
||||
0x00, // Empty MKI.
|
||||
0xFF, // Trailing extension-body byte.
|
||||
];
|
||||
|
||||
let err = UseSrtpExtension::parse(&bytes).unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
Err::Failure(Error {
|
||||
code: ErrorKind::LengthValue,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
use super::Dtls12CipherSuite;
|
||||
use crate::buffer::Buf;
|
||||
use nom::IResult;
|
||||
use nom::bytes::complete::take;
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Finished {
|
||||
pub verify_data_range: Range<usize>,
|
||||
}
|
||||
|
||||
impl Finished {
|
||||
pub fn verify_data<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
&buf[self.verify_data_range.clone()]
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8], cipher_suite: Dtls12CipherSuite) -> IResult<&[u8], Finished> {
|
||||
let verify_data_length = cipher_suite.verify_data_length();
|
||||
let (rest, verify_data_slice) = take(verify_data_length)(input)?;
|
||||
|
||||
// Calculate range relative to input buffer without unsafe code
|
||||
// verify_data_slice is a sub-slice of input from nom's take combinator
|
||||
let start = verify_data_slice.as_ptr() as usize - input.as_ptr() as usize;
|
||||
let end = start + verify_data_slice.len();
|
||||
|
||||
Ok((
|
||||
rest,
|
||||
Finished {
|
||||
verify_data_range: start..end,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
output.extend_from_slice(self.verify_data(buf));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::Dtls12CipherSuite;
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let verify_data = vec![
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
|
||||
];
|
||||
|
||||
// Parse the data
|
||||
let (rest, parsed) = Finished::parse(
|
||||
&verify_data,
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Serialize and compare to original
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(&verify_data, &mut serialized);
|
||||
assert_eq!(&*serialized, &verify_data[..]);
|
||||
}
|
||||
}
|
||||
+836
@@ -0,0 +1,836 @@
|
||||
use std::fmt;
|
||||
use std::ops::Range;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use super::Certificate;
|
||||
use super::CertificateRequest;
|
||||
use super::CertificateVerify;
|
||||
use super::ClientHello;
|
||||
use super::ClientKeyExchange;
|
||||
use super::Dtls12CipherSuite;
|
||||
use super::Finished;
|
||||
use super::HelloVerifyRequest;
|
||||
use super::ServerHello;
|
||||
use super::ServerKeyExchange;
|
||||
use crate::buffer::Buf;
|
||||
use arrayvec::ArrayVec;
|
||||
use nom::Err;
|
||||
use nom::IResult;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::number::complete::be_u8;
|
||||
use nom::number::complete::{be_u16, be_u24};
|
||||
|
||||
// Defensive stack cap over flattened handshake fragments selected for one
|
||||
// defragmentation attempt. This intentionally does not mirror the receive
|
||||
// queue's record-count cap; exceeding 50 fragments for one handshake implies
|
||||
// pathologically tiny records and is treated as invalid input.
|
||||
const MAX_DEFRAGMENT_HANDSHAKES: usize = 50;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
|
||||
pub struct Header {
|
||||
pub msg_type: MessageType,
|
||||
pub length: u32,
|
||||
pub message_seq: u16,
|
||||
pub fragment_offset: u32,
|
||||
pub fragment_length: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Handshake {
|
||||
pub header: Header,
|
||||
pub body: Body,
|
||||
pub handled: AtomicBool,
|
||||
}
|
||||
|
||||
impl PartialEq for Handshake {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.header == other.header
|
||||
&& self.body == other.body
|
||||
&& self.handled.load(Ordering::Relaxed) == other.handled.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Handshake {}
|
||||
|
||||
impl Handshake {
|
||||
#[cfg(test)]
|
||||
pub fn new(
|
||||
msg_type: MessageType,
|
||||
length: u32,
|
||||
message_seq: u16,
|
||||
fragment_offset: u32,
|
||||
fragment_length: u32,
|
||||
body: Body,
|
||||
) -> Self {
|
||||
Handshake {
|
||||
header: Header {
|
||||
msg_type,
|
||||
length,
|
||||
message_seq,
|
||||
fragment_offset,
|
||||
fragment_length,
|
||||
},
|
||||
body,
|
||||
handled: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_header(input: &[u8]) -> IResult<&[u8], Header> {
|
||||
let (input, msg_type) = MessageType::parse(input)?;
|
||||
let (input, length) = be_u24(input)?;
|
||||
let (input, message_seq) = be_u16(input)?;
|
||||
let (input, fragment_offset) = be_u24(input)?;
|
||||
let (input, fragment_length) = be_u24(input)?;
|
||||
|
||||
Ok((
|
||||
input,
|
||||
Header {
|
||||
msg_type,
|
||||
length,
|
||||
message_seq,
|
||||
fragment_offset,
|
||||
fragment_length,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn parse(
|
||||
input: &[u8],
|
||||
base_offset: usize,
|
||||
c: Option<Dtls12CipherSuite>,
|
||||
as_fragment: bool,
|
||||
) -> IResult<&[u8], Handshake> {
|
||||
let original_input = input;
|
||||
let (input, header) = Self::parse_header(input)?;
|
||||
|
||||
let is_fragment = header.fragment_offset > 0 || header.fragment_length < header.length;
|
||||
|
||||
if !as_fragment && is_fragment {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
let (input, body) = if as_fragment {
|
||||
let (input, fragment_slice) = take(header.fragment_length as usize)(input)?;
|
||||
// Calculate range relative to original input
|
||||
let relative_offset =
|
||||
fragment_slice.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let start = base_offset + relative_offset;
|
||||
let end = start + fragment_slice.len();
|
||||
(input, Body::Fragment(start..end))
|
||||
} else {
|
||||
let (input, body_bytes) = take(header.length as usize)(input)?;
|
||||
// Calculate base_offset for body parsing
|
||||
let consumed = body_bytes.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let body_base_offset = base_offset + consumed;
|
||||
let (_, body) = Body::parse(body_bytes, body_base_offset, header.msg_type, c)?;
|
||||
(input, body)
|
||||
};
|
||||
|
||||
Ok((
|
||||
input,
|
||||
Handshake {
|
||||
header,
|
||||
body,
|
||||
handled: AtomicBool::new(false),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) {
|
||||
output.push(self.header.msg_type.as_u8());
|
||||
output.extend_from_slice(&self.header.length.to_be_bytes()[1..]);
|
||||
output.extend_from_slice(&self.header.message_seq.to_be_bytes());
|
||||
output.extend_from_slice(&self.header.fragment_offset.to_be_bytes()[1..]);
|
||||
output.extend_from_slice(&self.header.fragment_length.to_be_bytes()[1..]);
|
||||
self.body.serialize(source_buf, output);
|
||||
}
|
||||
|
||||
#[allow(private_interfaces)]
|
||||
pub fn defragment<'b>(
|
||||
mut iter: impl Iterator<Item = (&'b Handshake, &'b [u8])>,
|
||||
buffer: &mut Buf,
|
||||
cipher_suite: Option<Dtls12CipherSuite>,
|
||||
transcript: Option<&mut Buf>,
|
||||
) -> Result<Handshake, crate::InternalError> {
|
||||
buffer.clear();
|
||||
|
||||
// Invariant is upheld by the caller.
|
||||
let (first_handshake, first_buffer) = iter.next().unwrap();
|
||||
|
||||
let Body::Fragment(range) = &first_handshake.body else {
|
||||
unreachable!("Non-Fragment body in defragment()")
|
||||
};
|
||||
let mut handled = ArrayVec::<&Handshake, MAX_DEFRAGMENT_HANDSHAKES>::new();
|
||||
handled
|
||||
.try_push(first_handshake)
|
||||
.map_err(|_| crate::InternalError::too_many_records())?;
|
||||
buffer.extend_from_slice(&first_buffer[range.clone()]);
|
||||
|
||||
for (handshake, source_buf) in iter {
|
||||
if handshake.header.msg_type != first_handshake.header.msg_type
|
||||
|| handshake.header.message_seq != first_handshake.header.message_seq
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
let Body::Fragment(range) = &handshake.body else {
|
||||
unreachable!("Non-Fragment body in defragment()")
|
||||
};
|
||||
|
||||
handled
|
||||
.try_push(handshake)
|
||||
.map_err(|_| crate::InternalError::too_many_records())?;
|
||||
|
||||
buffer.extend_from_slice(&source_buf[range.clone()]);
|
||||
}
|
||||
|
||||
if buffer.len() != first_handshake.header.length as usize {
|
||||
debug!("Defragmentation failed. Fragment length mismatch");
|
||||
return Err(crate::InternalError::parse_incomplete());
|
||||
}
|
||||
|
||||
let (rest, body) =
|
||||
match Body::parse(buffer, 0, first_handshake.header.msg_type, cipher_suite) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(err) => {
|
||||
mark_handled(handled);
|
||||
return Err(err.into());
|
||||
}
|
||||
};
|
||||
|
||||
if !rest.is_empty()
|
||||
&& first_handshake
|
||||
.header
|
||||
.msg_type
|
||||
.rejects_trailing_body_bytes()
|
||||
{
|
||||
debug!("Defragmentation failed. Body::parse() did not consume the entire buffer");
|
||||
mark_handled(handled);
|
||||
return Err(crate::InternalError::parse_incomplete());
|
||||
}
|
||||
|
||||
// Intentional boundary: Body::parse validates the handshake body shape and
|
||||
// extension envelopes, but known extension payloads remain validated by the
|
||||
// client/server state handlers. A transiently corrupted UDP datagram whose
|
||||
// extension payload fails later may therefore have been consumed here; that
|
||||
// recovery edge is accepted to keep this path parser-only and avoid the
|
||||
// broader transaction/rollback machinery.
|
||||
mark_handled(handled);
|
||||
|
||||
// If transcript is provided, write the handshake header + body after parsing succeeds.
|
||||
if let Some(transcript) = transcript {
|
||||
transcript.push(first_handshake.header.msg_type.as_u8());
|
||||
transcript.extend_from_slice(&first_handshake.header.length.to_be_bytes()[1..]);
|
||||
transcript.extend_from_slice(&first_handshake.header.message_seq.to_be_bytes());
|
||||
// Defragmented handshake has fragment_offset=0 and fragment_length=length
|
||||
transcript.extend_from_slice(&0u32.to_be_bytes()[1..]);
|
||||
transcript.extend_from_slice(&first_handshake.header.length.to_be_bytes()[1..]);
|
||||
transcript.extend_from_slice(&buffer[..first_handshake.header.length as usize]);
|
||||
}
|
||||
|
||||
let handshake = Handshake {
|
||||
header: Header {
|
||||
msg_type: first_handshake.header.msg_type,
|
||||
length: first_handshake.header.length,
|
||||
message_seq: first_handshake.header.message_seq,
|
||||
fragment_offset: 0,
|
||||
fragment_length: first_handshake.header.length,
|
||||
},
|
||||
body,
|
||||
handled: AtomicBool::new(false),
|
||||
};
|
||||
|
||||
// Create a new Handshake with the merged body
|
||||
Ok(handshake)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn do_clone(&self) -> Handshake {
|
||||
Handshake {
|
||||
header: Header {
|
||||
msg_type: self.header.msg_type,
|
||||
length: self.header.length,
|
||||
message_seq: self.header.message_seq,
|
||||
fragment_offset: self.header.fragment_offset,
|
||||
fragment_length: self.header.fragment_length,
|
||||
},
|
||||
body: Body::HelloRequest, // Placeholder
|
||||
handled: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn fragment<'b>(
|
||||
&self,
|
||||
max: usize,
|
||||
buffer: &'b mut Buf,
|
||||
) -> impl Iterator<Item = Handshake> + 'b {
|
||||
// Must be called with an empty buffer.
|
||||
assert!(buffer.is_empty());
|
||||
|
||||
// Note: For fragmentize, self is already serialized data in Body::Fragment
|
||||
// which doesn't need source_buf, so we pass an empty slice
|
||||
self.body.serialize(&[], buffer);
|
||||
|
||||
// If this is wrong, the serialize has not produced the same output as we parsed.
|
||||
assert_eq!(buffer.len(), self.header.length as usize);
|
||||
|
||||
let to_clone = self.do_clone();
|
||||
|
||||
buffer.chunks(max).enumerate().map(move |(i, chunk)| {
|
||||
let fragment_length = chunk.len() as u32;
|
||||
let offset = i * max;
|
||||
let fragment_range = offset..(offset + chunk.len());
|
||||
|
||||
let mut fragment = to_clone.do_clone();
|
||||
fragment.header.fragment_offset = offset as u32;
|
||||
fragment.header.fragment_length = fragment_length;
|
||||
fragment.header.message_seq = to_clone.header.message_seq;
|
||||
fragment.body = Body::Fragment(fragment_range);
|
||||
|
||||
fragment
|
||||
})
|
||||
}
|
||||
|
||||
// These are (unencrypted) handshakes that, when detected as
|
||||
// duplicates, trigger a resend of the entire flight.
|
||||
pub fn dupe_triggers_resend(&self) -> Option<u16> {
|
||||
// Only trigger on the first fragment of a handshake message to avoid
|
||||
// multiple resends caused by fragmented duplicates of the same message.
|
||||
if self.header.fragment_offset != 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let qualifies = matches!(
|
||||
self.header.msg_type,
|
||||
MessageType::ClientHello | // flight 1 and 3
|
||||
MessageType::HelloVerifyRequest | // flight 2
|
||||
MessageType::ServerHelloDone | // flight 4
|
||||
MessageType::ClientKeyExchange // flight 5
|
||||
);
|
||||
|
||||
qualifies.then_some(self.header.message_seq)
|
||||
}
|
||||
|
||||
pub fn is_handled(&self) -> bool {
|
||||
self.handled.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn set_handled(&self) {
|
||||
self.handled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_handled(handled: ArrayVec<&Handshake, MAX_DEFRAGMENT_HANDSHAKES>) {
|
||||
for handshake in handled {
|
||||
handshake.set_handled();
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub struct MessageType(u8);
|
||||
|
||||
#[allow(non_upper_case_globals)]
|
||||
impl MessageType {
|
||||
pub const HelloRequest: Self = Self(0);
|
||||
pub const ClientHello: Self = Self(1);
|
||||
pub const ServerHello: Self = Self(2);
|
||||
pub const HelloVerifyRequest: Self = Self(3);
|
||||
pub const NewSessionTicket: Self = Self(4);
|
||||
pub const Certificate: Self = Self(11);
|
||||
pub const ServerKeyExchange: Self = Self(12);
|
||||
pub const CertificateRequest: Self = Self(13);
|
||||
pub const ServerHelloDone: Self = Self(14);
|
||||
pub const CertificateVerify: Self = Self(15);
|
||||
pub const ClientKeyExchange: Self = Self(16);
|
||||
pub const Finished: Self = Self(20);
|
||||
|
||||
pub const fn from_u8(value: u8) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
pub const fn as_u8(&self) -> u8 {
|
||||
self.0
|
||||
}
|
||||
|
||||
const fn is_unknown(&self) -> bool {
|
||||
!matches!(*self, Self(0..=4 | 11..=16 | 20))
|
||||
}
|
||||
|
||||
const fn rejects_trailing_body_bytes(&self) -> bool {
|
||||
!self.is_unknown()
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], MessageType> {
|
||||
let (input, byte) = be_u8(input)?;
|
||||
Ok((input, Self::from_u8(byte)))
|
||||
}
|
||||
|
||||
pub fn epoch(&self) -> u16 {
|
||||
if matches!(*self, MessageType::NewSessionTicket | MessageType::Finished) {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for MessageType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.is_unknown() {
|
||||
return f.debug_tuple("Unknown").field(&self.0).finish();
|
||||
}
|
||||
|
||||
let name = match *self {
|
||||
MessageType::HelloRequest => "HelloRequest",
|
||||
MessageType::ClientHello => "ClientHello",
|
||||
MessageType::HelloVerifyRequest => "HelloVerifyRequest",
|
||||
MessageType::ServerHello => "ServerHello",
|
||||
MessageType::Certificate => "Certificate",
|
||||
MessageType::ServerKeyExchange => "ServerKeyExchange",
|
||||
MessageType::CertificateRequest => "CertificateRequest",
|
||||
MessageType::ServerHelloDone => "ServerHelloDone",
|
||||
MessageType::CertificateVerify => "CertificateVerify",
|
||||
MessageType::ClientKeyExchange => "ClientKeyExchange",
|
||||
MessageType::NewSessionTicket => "NewSessionTicket",
|
||||
MessageType::Finished => "Finished",
|
||||
_ => unreachable!("known DTLS 1.2 handshake message type missing Debug label"),
|
||||
};
|
||||
|
||||
f.write_str(name)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum Body {
|
||||
HelloRequest, // empty
|
||||
ClientHello(ClientHello),
|
||||
HelloVerifyRequest(HelloVerifyRequest),
|
||||
ServerHello(ServerHello),
|
||||
Certificate(Certificate),
|
||||
ServerKeyExchange(ServerKeyExchange),
|
||||
CertificateRequest(CertificateRequest),
|
||||
ServerHelloDone, // empty
|
||||
CertificateVerify(CertificateVerify),
|
||||
ClientKeyExchange(ClientKeyExchange),
|
||||
NewSessionTicket(Range<usize>),
|
||||
Finished(Finished),
|
||||
Unknown(u8),
|
||||
Fragment(Range<usize>),
|
||||
}
|
||||
|
||||
impl Default for Body {
|
||||
fn default() -> Self {
|
||||
Self::Unknown(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Body {
|
||||
pub fn parse(
|
||||
input: &[u8],
|
||||
base_offset: usize,
|
||||
m: MessageType,
|
||||
c: Option<Dtls12CipherSuite>,
|
||||
) -> IResult<&[u8], Body> {
|
||||
match m {
|
||||
MessageType::HelloRequest => Ok((input, Body::HelloRequest)),
|
||||
MessageType::ClientHello => {
|
||||
let (input, client_hello) = ClientHello::parse(input, base_offset)?;
|
||||
Ok((input, Body::ClientHello(client_hello)))
|
||||
}
|
||||
MessageType::HelloVerifyRequest => {
|
||||
let (input, hello_verify_request) = HelloVerifyRequest::parse(input)?;
|
||||
Ok((input, Body::HelloVerifyRequest(hello_verify_request)))
|
||||
}
|
||||
MessageType::ServerHello => {
|
||||
let (input, server_hello) = ServerHello::parse(input, base_offset)?;
|
||||
Ok((input, Body::ServerHello(server_hello)))
|
||||
}
|
||||
MessageType::Certificate => {
|
||||
let (input, certificate) = Certificate::parse(input, base_offset)?;
|
||||
Ok((input, Body::Certificate(certificate)))
|
||||
}
|
||||
MessageType::ServerKeyExchange => {
|
||||
let cipher_suite =
|
||||
c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?;
|
||||
let algo = cipher_suite.as_key_exchange_algorithm();
|
||||
let (input, server_key_exchange) =
|
||||
ServerKeyExchange::parse(input, base_offset, algo)?;
|
||||
Ok((input, Body::ServerKeyExchange(server_key_exchange)))
|
||||
}
|
||||
MessageType::CertificateRequest => {
|
||||
let (input, certificate_request) = CertificateRequest::parse(input, base_offset)?;
|
||||
Ok((input, Body::CertificateRequest(certificate_request)))
|
||||
}
|
||||
MessageType::ServerHelloDone => Ok((input, Body::ServerHelloDone)),
|
||||
MessageType::CertificateVerify => {
|
||||
let (input, certificate_verify) = CertificateVerify::parse(input, base_offset)?;
|
||||
Ok((input, Body::CertificateVerify(certificate_verify)))
|
||||
}
|
||||
MessageType::ClientKeyExchange => {
|
||||
let cipher_suite =
|
||||
c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?;
|
||||
let algo = cipher_suite.as_key_exchange_algorithm();
|
||||
let (input, client_key_exchange) =
|
||||
ClientKeyExchange::parse(input, base_offset, algo)?;
|
||||
Ok((input, Body::ClientKeyExchange(client_key_exchange)))
|
||||
}
|
||||
MessageType::NewSessionTicket => {
|
||||
// Treat ticket as opaque per RFC 5077: lifetime_hint(4) + ticket (opaque vector)
|
||||
let range = base_offset..(base_offset + input.len());
|
||||
Ok((&[], Body::NewSessionTicket(range)))
|
||||
}
|
||||
MessageType::Finished => {
|
||||
let cipher_suite =
|
||||
c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?;
|
||||
let (input, finished) = Finished::parse(input, cipher_suite)?;
|
||||
Ok((input, Body::Finished(finished)))
|
||||
}
|
||||
_ => Ok((input, Body::Unknown(m.as_u8()))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) {
|
||||
match self {
|
||||
Body::HelloRequest => {
|
||||
// Serialize HelloRequest (empty)
|
||||
}
|
||||
Body::ClientHello(client_hello) => {
|
||||
client_hello.serialize(source_buf, output);
|
||||
}
|
||||
Body::HelloVerifyRequest(hello_verify_request) => {
|
||||
hello_verify_request.serialize(output);
|
||||
}
|
||||
Body::ServerHello(server_hello) => {
|
||||
server_hello.serialize(source_buf, output);
|
||||
}
|
||||
Body::Certificate(certificate) => {
|
||||
certificate.serialize(source_buf, output);
|
||||
}
|
||||
Body::ServerKeyExchange(server_key_exchange) => {
|
||||
server_key_exchange.serialize(source_buf, output, true);
|
||||
}
|
||||
Body::CertificateRequest(certificate_request) => {
|
||||
certificate_request.serialize(source_buf, output);
|
||||
}
|
||||
Body::ServerHelloDone => {
|
||||
// Serialize ServerHelloDone (empty)
|
||||
}
|
||||
Body::CertificateVerify(certificate_verify) => {
|
||||
certificate_verify.serialize(source_buf, output);
|
||||
}
|
||||
Body::ClientKeyExchange(client_key_exchange) => {
|
||||
client_key_exchange.serialize(source_buf, output);
|
||||
}
|
||||
Body::NewSessionTicket(range) => {
|
||||
output.extend_from_slice(&source_buf[range.clone()]);
|
||||
}
|
||||
Body::Finished(finished) => {
|
||||
finished.serialize(source_buf, output);
|
||||
}
|
||||
Body::Unknown(value) => {
|
||||
output.push(*value);
|
||||
}
|
||||
Body::Fragment(range) => {
|
||||
output.extend_from_slice(&source_buf[range.clone()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use arrayvec::ArrayVec;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
use crate::dtls12::message::CompressionMethod;
|
||||
use crate::dtls12::message::Cookie;
|
||||
use crate::dtls12::message::Dtls12CipherSuite;
|
||||
use crate::dtls12::message::ProtocolVersion;
|
||||
use crate::dtls12::message::Random;
|
||||
use crate::dtls12::message::SessionId;
|
||||
|
||||
const MESSAGE: &[u8] = &[
|
||||
0x01, // MessageType::ClientHello
|
||||
0x00, 0x00, 0x2E, // length
|
||||
0x00, 0x00, // message_seq
|
||||
0x00, 0x00, 0x00, // fragment_offset
|
||||
0x00, 0x00, 0x2E, // fragment_length
|
||||
// ClientHello
|
||||
0xFE, 0xFD, // ProtocolVersion::DTLS1_2
|
||||
// Random
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E,
|
||||
0x1F, 0x20, //
|
||||
0x01, // SessionId length
|
||||
0xAA, // SessionId
|
||||
0x01, // Cookie length
|
||||
0xBB, // Cookie
|
||||
0x00, 0x04, // Dtls12CipherSuites length
|
||||
0xC0, 0x2B, // Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
0xC0, 0x2C, // Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384
|
||||
0x01, // CompressionMethods length
|
||||
0x00, // CompressionMethod::Null
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn message_type_newtype_shape() {
|
||||
assert_eq!(std::mem::size_of::<MessageType>(), 1);
|
||||
assert_eq!(MessageType::default().as_u8(), 0);
|
||||
assert_eq!(MessageType::default(), MessageType::HelloRequest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_type_wire_roundtrip() {
|
||||
for message_type in [
|
||||
MessageType::HelloRequest,
|
||||
MessageType::ClientHello,
|
||||
MessageType::ServerHello,
|
||||
MessageType::HelloVerifyRequest,
|
||||
MessageType::NewSessionTicket,
|
||||
MessageType::Certificate,
|
||||
MessageType::ServerKeyExchange,
|
||||
MessageType::CertificateRequest,
|
||||
MessageType::ServerHelloDone,
|
||||
MessageType::CertificateVerify,
|
||||
MessageType::ClientKeyExchange,
|
||||
MessageType::Finished,
|
||||
] {
|
||||
assert_eq!(MessageType::from_u8(message_type.as_u8()), message_type);
|
||||
assert!(!message_type.is_unknown());
|
||||
}
|
||||
|
||||
let unknown = MessageType::from_u8(0xFF);
|
||||
assert_eq!(unknown.as_u8(), 0xFF);
|
||||
assert!(unknown.is_unknown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_type_debug_stays_enum_like() {
|
||||
assert_eq!(format!("{:?}", MessageType::ClientHello), "ClientHello");
|
||||
assert_eq!(format!("{:?}", MessageType::from_u8(0xFF)), "Unknown(255)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_size() {
|
||||
let h = Handshake::new(
|
||||
// ServerHelloDone has a 0 sized body.
|
||||
MessageType::ServerHelloDone,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
Body::ServerHelloDone,
|
||||
);
|
||||
|
||||
let mut v = Buf::new();
|
||||
h.serialize(&[], &mut v);
|
||||
|
||||
assert_eq!(v.len(), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let mut serialized = Buf::new();
|
||||
|
||||
let random = Random::parse(&MESSAGE[14..46]).unwrap().1;
|
||||
let session_id = SessionId::try_new(&[0xAA]).unwrap();
|
||||
let cookie = Cookie::try_new(&[0xBB]).unwrap();
|
||||
let mut cipher_suites = ArrayVec::new();
|
||||
cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256);
|
||||
cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384);
|
||||
let mut compression_methods = ArrayVec::new();
|
||||
compression_methods.push(CompressionMethod::Null);
|
||||
|
||||
let client_hello = ClientHello::new(
|
||||
ProtocolVersion::DTLS1_2,
|
||||
random,
|
||||
session_id,
|
||||
cookie,
|
||||
cipher_suites,
|
||||
compression_methods,
|
||||
);
|
||||
|
||||
let handshake = Handshake::new(
|
||||
MessageType::ClientHello,
|
||||
0x2E,
|
||||
0,
|
||||
0,
|
||||
0x2E,
|
||||
Body::ClientHello(client_hello),
|
||||
);
|
||||
|
||||
// Serialize and compare to MESSAGE
|
||||
handshake.serialize(&[], &mut serialized);
|
||||
assert_eq!(&*serialized, MESSAGE);
|
||||
|
||||
// Parse and compare with original
|
||||
let (rest, parsed) = Handshake::parse(&serialized, 0, None, false).unwrap();
|
||||
assert_eq!(parsed, handshake);
|
||||
|
||||
assert!(rest.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_fragment() {
|
||||
let mut serialized = Buf::new();
|
||||
let mut buffer = Buf::new();
|
||||
|
||||
let random = Random::parse(&MESSAGE[14..46]).unwrap().1;
|
||||
let session_id = SessionId::try_new(&[0xAA]).unwrap();
|
||||
let cookie = Cookie::try_new(&[0xBB]).unwrap();
|
||||
let mut cipher_suites = ArrayVec::new();
|
||||
cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256);
|
||||
cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384);
|
||||
let mut compression_methods = ArrayVec::new();
|
||||
compression_methods.push(CompressionMethod::Null);
|
||||
|
||||
let client_hello = ClientHello::new(
|
||||
ProtocolVersion::DTLS1_2,
|
||||
random,
|
||||
session_id,
|
||||
cookie,
|
||||
cipher_suites,
|
||||
compression_methods,
|
||||
);
|
||||
|
||||
let handshake = Handshake::new(
|
||||
MessageType::ClientHello,
|
||||
46,
|
||||
0,
|
||||
0,
|
||||
46,
|
||||
Body::ClientHello(client_hello),
|
||||
);
|
||||
|
||||
// Fragment the handshake with size 10
|
||||
let fragments: VecDeque<_> = handshake.fragment(10, &mut buffer).collect();
|
||||
|
||||
// Defragment the fragments
|
||||
let mut defragmented_buffer = Buf::new();
|
||||
let defragmented_handshake = Handshake::defragment(
|
||||
fragments.iter().map(|h| (h, &buffer[..])),
|
||||
&mut defragmented_buffer,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Serialize and compare to MESSAGE
|
||||
// Save header info and drop handshake to release buffer borrow
|
||||
let header = defragmented_handshake.header;
|
||||
drop(defragmented_handshake);
|
||||
|
||||
serialized.push(header.msg_type.as_u8());
|
||||
serialized.extend_from_slice(&header.length.to_be_bytes()[1..]);
|
||||
serialized.extend_from_slice(&header.message_seq.to_be_bytes());
|
||||
serialized.extend_from_slice(&header.fragment_offset.to_be_bytes()[1..]);
|
||||
serialized.extend_from_slice(&header.fragment_length.to_be_bytes()[1..]);
|
||||
serialized.extend_from_slice(&defragmented_buffer[..header.length as usize]);
|
||||
assert_eq!(&*serialized, MESSAGE);
|
||||
|
||||
// Parse and compare with original
|
||||
let (rest, parsed) = Handshake::parse(&serialized, 0, None, false).unwrap();
|
||||
assert_eq!(parsed, handshake);
|
||||
|
||||
assert!(rest.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_defragment_parse_discards_candidate_without_writing_transcript() {
|
||||
let mut body = MESSAGE[12..].to_vec();
|
||||
body[38] = 0;
|
||||
body[39] = 3;
|
||||
|
||||
let handshake = Handshake::new(
|
||||
MessageType::ClientHello,
|
||||
body.len() as u32,
|
||||
0,
|
||||
0,
|
||||
body.len() as u32,
|
||||
Body::Fragment(0..body.len()),
|
||||
);
|
||||
|
||||
let mut defragmented_buffer = Buf::new();
|
||||
let mut transcript = Buf::new();
|
||||
let result = Handshake::defragment(
|
||||
std::iter::once((&handshake, body.as_slice())),
|
||||
&mut defragmented_buffer,
|
||||
None,
|
||||
Some(&mut transcript),
|
||||
);
|
||||
|
||||
assert!(result.is_err());
|
||||
assert!(handshake.is_handled());
|
||||
assert!(transcript.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defragment_stops_at_cross_sequence_fragment() {
|
||||
let body = &MESSAGE[12..];
|
||||
let mut source = body.to_vec();
|
||||
source.push(0);
|
||||
|
||||
let handshake = Handshake::new(
|
||||
MessageType::ClientHello,
|
||||
body.len() as u32,
|
||||
0,
|
||||
0,
|
||||
body.len() as u32,
|
||||
Body::Fragment(0..body.len()),
|
||||
);
|
||||
let decoy = Handshake::new(
|
||||
MessageType::ClientHello,
|
||||
body.len() as u32 + 1,
|
||||
1,
|
||||
body.len() as u32,
|
||||
1,
|
||||
Body::Fragment(body.len()..body.len() + 1),
|
||||
);
|
||||
|
||||
let mut defragmented_buffer = Buf::new();
|
||||
let defragmented_handshake = Handshake::defragment(
|
||||
[(&handshake, source.as_slice()), (&decoy, source.as_slice())].into_iter(),
|
||||
&mut defragmented_buffer,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(defragmented_handshake.header.message_seq, 0);
|
||||
assert_eq!(&defragmented_buffer[..body.len()], body);
|
||||
assert!(handshake.is_handled());
|
||||
assert!(!decoy.is_handled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_body_rejects_trailing_bytes() {
|
||||
let body = [0];
|
||||
let handshake = Handshake::new(
|
||||
MessageType::HelloRequest,
|
||||
body.len() as u32,
|
||||
0,
|
||||
0,
|
||||
body.len() as u32,
|
||||
Body::Fragment(0..body.len()),
|
||||
);
|
||||
|
||||
let mut defragmented_buffer = Buf::new();
|
||||
let mut transcript = Buf::new();
|
||||
let result = Handshake::defragment(
|
||||
std::iter::once((&handshake, body.as_slice())),
|
||||
&mut defragmented_buffer,
|
||||
None,
|
||||
Some(&mut transcript),
|
||||
);
|
||||
|
||||
assert!(result.is_err());
|
||||
assert!(handshake.is_handled());
|
||||
assert!(transcript.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use super::ProtocolVersion;
|
||||
use super::id::Cookie;
|
||||
use crate::buffer::Buf;
|
||||
use nom::IResult;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct HelloVerifyRequest {
|
||||
pub server_version: ProtocolVersion,
|
||||
pub cookie: Cookie,
|
||||
}
|
||||
|
||||
impl HelloVerifyRequest {
|
||||
pub fn new(server_version: ProtocolVersion, cookie: Cookie) -> Self {
|
||||
HelloVerifyRequest {
|
||||
server_version,
|
||||
cookie,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], HelloVerifyRequest> {
|
||||
let (input, server_version) = ProtocolVersion::parse(input)?;
|
||||
let (input, cookie) = Cookie::parse(input)?;
|
||||
|
||||
if cookie.is_empty() {
|
||||
return Err(nom::Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
|
||||
Ok((
|
||||
input,
|
||||
HelloVerifyRequest {
|
||||
server_version,
|
||||
cookie,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, output: &mut Buf) {
|
||||
output.extend_from_slice(&self.server_version.as_u16().to_be_bytes());
|
||||
output.push(self.cookie.len() as u8);
|
||||
output.extend_from_slice(&self.cookie);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const MESSAGE: &[u8] = &[
|
||||
0xFE, 0xFD, // ProtocolVersion::DTLS1_2
|
||||
0x01, // Cookie length
|
||||
0xBB, // Cookie
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let cookie = Cookie::try_new(&[0xBB]).unwrap();
|
||||
|
||||
let hello_verify_request = HelloVerifyRequest::new(ProtocolVersion::DTLS1_2, cookie);
|
||||
|
||||
// Serialize and compare to MESSAGE
|
||||
let mut serialized = Buf::new();
|
||||
hello_verify_request.serialize(&mut serialized);
|
||||
assert_eq!(&*serialized, MESSAGE);
|
||||
|
||||
// Parse and compare with original
|
||||
let (rest, parsed) = HelloVerifyRequest::parse(&serialized).unwrap();
|
||||
assert_eq!(parsed, hello_verify_request);
|
||||
|
||||
assert!(rest.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_cookie() {
|
||||
let message: &[u8] = &[
|
||||
0xFE, 0xFD, // ProtocolVersion::DTLS1_2
|
||||
0x00, // Cookie length (0, which is empty)
|
||||
];
|
||||
|
||||
let result = HelloVerifyRequest::parse(message);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_too_long() {
|
||||
let mut message = MESSAGE.to_vec();
|
||||
message[2] = 0xFF; // Cookie length (255, which is too long)
|
||||
|
||||
let result = HelloVerifyRequest::parse(&message);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::number::complete::be_u8;
|
||||
use nom::{Err, IResult};
|
||||
use std::fmt;
|
||||
use std::ops::Deref;
|
||||
|
||||
pub struct InvalidLength(&'static str, IdType, usize);
|
||||
|
||||
impl fmt::Debug for InvalidLength {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidLength {}
|
||||
|
||||
impl fmt::Display for InvalidLength {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self.1 {
|
||||
IdType::Fixed(len) => write!(
|
||||
f,
|
||||
"Incorrect fixed ID ({}) length: {} should be {}",
|
||||
self.0, self.2, len
|
||||
),
|
||||
IdType::Variable(min, max) => write!(
|
||||
f,
|
||||
"Incorrect variable ID ({}) length: {} <= {} <= {}",
|
||||
self.0, min, self.2, max,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum IdType {
|
||||
#[allow(unused)]
|
||||
Fixed(usize),
|
||||
Variable(usize, usize),
|
||||
}
|
||||
|
||||
macro_rules! var_array {
|
||||
($name:ident, $min:expr, $max:expr) => {
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct $name([u8; $max], usize);
|
||||
|
||||
impl $name {
|
||||
pub fn try_new(data: &[u8]) -> Result<Self, InvalidLength> {
|
||||
#[allow(unused_comparisons)]
|
||||
if data.len() < $min || data.len() > $max {
|
||||
return Err(InvalidLength(
|
||||
stringify!($name),
|
||||
IdType::Variable($min, $max),
|
||||
data.len(),
|
||||
));
|
||||
}
|
||||
let mut array = [0; $max];
|
||||
array[..data.len()].copy_from_slice(data);
|
||||
Ok($name(array, data.len()))
|
||||
}
|
||||
|
||||
pub fn empty() -> Self {
|
||||
if $min > 0 {
|
||||
panic!("{}::empty() is not valid", stringify!($name));
|
||||
}
|
||||
Self([0; $max], 0)
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], Self> {
|
||||
let (input, len) = be_u8(input)?;
|
||||
if len < $min as u8 || len > $max as u8 {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
let (input, data) = take(len as usize)(input)?;
|
||||
// unwrap() is ok because we check the size above.
|
||||
let instance = Self::try_new(data).unwrap();
|
||||
Ok((input, instance))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for $name {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for $name {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}({:02x?})", stringify!($name), &self.0[..self.1])
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for $name {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.deref() == other.deref()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for $name {}
|
||||
|
||||
impl Deref for $name {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0[..self.1]
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<&'a [u8]> for $name {
|
||||
type Error = InvalidLength;
|
||||
|
||||
fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
|
||||
Self::try_new(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<&'a str> for $name {
|
||||
type Error = InvalidLength;
|
||||
|
||||
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
|
||||
Self::try_new(value.as_bytes())
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var_array!(SessionId, 0, 32);
|
||||
var_array!(Cookie, 0, 255);
|
||||
+465
@@ -0,0 +1,465 @@
|
||||
//! Low-level DTLS message parsing and serialization types.
|
||||
//!
|
||||
//! This module exposes enums and helpers used by the public API for negotiating
|
||||
//! cipher suites and signature algorithms, as well as parsing wire formats.
|
||||
//! Only the public items are documented here; the rest are internal helpers.
|
||||
|
||||
mod certificate;
|
||||
mod certificate_request;
|
||||
mod certificate_verify;
|
||||
mod client_hello;
|
||||
mod client_key_exchange;
|
||||
mod digitally_signed;
|
||||
mod extension;
|
||||
mod extensions;
|
||||
mod finished;
|
||||
mod handshake;
|
||||
mod hello_verify;
|
||||
mod id;
|
||||
mod named_group;
|
||||
mod record;
|
||||
mod server_hello;
|
||||
mod server_key_exchange;
|
||||
mod wrapped;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
pub use certificate::Certificate;
|
||||
pub use certificate_request::CertificateRequest;
|
||||
pub use certificate_verify::CertificateVerify;
|
||||
pub use client_hello::ClientHello;
|
||||
pub use client_key_exchange::{ClientKeyExchange, ClientPskKeys, ExchangeKeys};
|
||||
pub use digitally_signed::DigitallySigned;
|
||||
pub use extension::{Extension, ExtensionType};
|
||||
pub use extensions::ec_point_formats::ECPointFormatsExtension;
|
||||
pub use extensions::signature_algorithms::SignatureAlgorithmsExtension;
|
||||
pub use extensions::supported_groups::SupportedGroupsExtension;
|
||||
pub use extensions::use_srtp::{SrtpProfileId, SrtpProfileVec, UseSrtpExtension};
|
||||
pub use finished::Finished;
|
||||
pub use handshake::{Body, Handshake, Header, MessageType};
|
||||
pub use hello_verify::HelloVerifyRequest;
|
||||
pub use id::{Cookie, SessionId};
|
||||
pub use named_group::CurveType;
|
||||
pub use record::DTLSRecord;
|
||||
|
||||
// Re-export shared types for backwards compatibility
|
||||
pub use crate::types::{
|
||||
CompressionMethod, ContentType, HashAlgorithm, NamedGroup, NamedGroupVec, ProtocolVersion,
|
||||
Random, Sequence, SignatureAlgorithm,
|
||||
};
|
||||
pub use server_hello::ServerHello;
|
||||
pub use server_key_exchange::{PskParams, ServerKeyExchange, ServerKeyExchangeParams};
|
||||
pub use wrapped::{Asn1Cert, DistinguishedName};
|
||||
|
||||
use nom::IResult;
|
||||
use nom::number::complete::{be_u8, be_u16};
|
||||
|
||||
pub type CipherSuiteVec = ArrayVec<Dtls12CipherSuite, { Dtls12CipherSuite::supported().len() }>;
|
||||
|
||||
/// Supported TLS 1.2 cipher suites for DTLS.
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub struct Dtls12CipherSuite(u16);
|
||||
|
||||
impl Dtls12CipherSuite {
|
||||
/// ECDHE with ECDSA authentication, AES-256-GCM, SHA-384.
|
||||
pub const ECDHE_ECDSA_AES256_GCM_SHA384: Self = Self(0xC02C);
|
||||
/// ECDHE with ECDSA authentication, AES-128-GCM, SHA-256.
|
||||
pub const ECDHE_ECDSA_AES128_GCM_SHA256: Self = Self(0xC02B);
|
||||
/// ECDHE with ECDSA authentication, ChaCha20-Poly1305, SHA-256.
|
||||
pub const ECDHE_ECDSA_CHACHA20_POLY1305_SHA256: Self = Self(0xCCA9);
|
||||
/// PSK with AES-128-CCM-8 (8-byte tag), SHA-256.
|
||||
pub const PSK_AES128_CCM_8: Self = Self(0xC0A8);
|
||||
|
||||
/// Convert the 16-bit IANA value to a `Dtls12CipherSuite`.
|
||||
pub const fn from_u16(value: u16) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
/// Return the 16-bit IANA value for this cipher suite.
|
||||
pub const fn as_u16(&self) -> u16 {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Returns true if this is not a known DTLS 1.2 cipher suite wire value.
|
||||
pub const fn is_unknown(&self) -> bool {
|
||||
!matches!(*self, Self(0xC02B..=0xC02C | 0xC0A8 | 0xCCA9))
|
||||
}
|
||||
|
||||
/// Parse a `Dtls12CipherSuite` from network byte order.
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], Dtls12CipherSuite> {
|
||||
let (input, value) = be_u16(input)?;
|
||||
Ok((input, Dtls12CipherSuite::from_u16(value)))
|
||||
}
|
||||
|
||||
/// Length in bytes of verify_data for Finished MACs.
|
||||
pub fn verify_data_length(&self) -> usize {
|
||||
match *self {
|
||||
// AES-GCM suites
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384
|
||||
| Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
| Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256
|
||||
| Dtls12CipherSuite::PSK_AES128_CCM_8 => 12,
|
||||
|
||||
_ => 12, // Default length for unknown cipher suites
|
||||
}
|
||||
}
|
||||
|
||||
/// The key exchange algorithm family for this cipher suite.
|
||||
pub fn as_key_exchange_algorithm(&self) -> KeyExchangeAlgorithm {
|
||||
match *self {
|
||||
// All ECDHE ciphers
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384
|
||||
| Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
| Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => {
|
||||
KeyExchangeAlgorithm::EECDH
|
||||
}
|
||||
|
||||
Dtls12CipherSuite::PSK_AES128_CCM_8 => KeyExchangeAlgorithm::PSK,
|
||||
|
||||
_ => KeyExchangeAlgorithm::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this cipher suite uses ECC-based key exchange.
|
||||
pub fn has_ecc(&self) -> bool {
|
||||
matches!(
|
||||
*self,
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384
|
||||
| Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
| Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether this cipher suite uses PSK (Pre-Shared Key) key exchange.
|
||||
pub fn is_psk(&self) -> bool {
|
||||
matches!(*self, Dtls12CipherSuite::PSK_AES128_CCM_8)
|
||||
}
|
||||
|
||||
/// All supported cipher suites in server preference order.
|
||||
pub const fn all() -> &'static [Dtls12CipherSuite; 4] {
|
||||
&[
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384,
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256,
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256,
|
||||
Dtls12CipherSuite::PSK_AES128_CCM_8,
|
||||
]
|
||||
}
|
||||
|
||||
/// Cipher suites compatible with a given certificate's signature algorithm.
|
||||
pub fn compatible_with_certificate(
|
||||
cert_type: SignatureAlgorithm,
|
||||
) -> &'static [Dtls12CipherSuite; 3] {
|
||||
match cert_type {
|
||||
SignatureAlgorithm::ECDSA => &[
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384,
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256,
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256,
|
||||
],
|
||||
_ => panic!("Need either RSA or ECDSA certificate"),
|
||||
}
|
||||
}
|
||||
|
||||
fn need_encrypt_then_mac(&self) -> bool {
|
||||
// We do not support and ciphers such as:
|
||||
// ECDHE-RSA-AES128-SHA
|
||||
// ECDHE-RSA-AES256-SHA
|
||||
// DHE-RSA-AES128-SHA256
|
||||
false
|
||||
}
|
||||
|
||||
/// The hash algorithm used by this cipher suite.
|
||||
pub fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
match *self {
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 => HashAlgorithm::SHA384,
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
| Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256
|
||||
| Dtls12CipherSuite::PSK_AES128_CCM_8 => HashAlgorithm::SHA256,
|
||||
_ => HashAlgorithm::UNKNOWN_DERIVED,
|
||||
}
|
||||
}
|
||||
|
||||
/// The signature algorithm associated with the suite's key exchange.
|
||||
///
|
||||
/// Returns `None` for PSK cipher suites (no signature authentication).
|
||||
pub fn signature_algorithm(&self) -> Option<SignatureAlgorithm> {
|
||||
match *self {
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384
|
||||
| Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
| Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => {
|
||||
Some(SignatureAlgorithm::ECDSA)
|
||||
}
|
||||
Dtls12CipherSuite::PSK_AES128_CCM_8 => None,
|
||||
_ => Some(SignatureAlgorithm::UNKNOWN_DERIVED),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if this cipher suite is supported by this implementation.
|
||||
pub fn is_supported(&self) -> bool {
|
||||
Self::supported().contains(self)
|
||||
}
|
||||
|
||||
/// Supported DTLS 1.2 cipher suites in server preference order.
|
||||
pub const fn supported() -> &'static [Dtls12CipherSuite; 4] {
|
||||
Self::all()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Dtls12CipherSuite {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 => {
|
||||
f.write_str("ECDHE_ECDSA_AES256_GCM_SHA384")
|
||||
}
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 => {
|
||||
f.write_str("ECDHE_ECDSA_AES128_GCM_SHA256")
|
||||
}
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => {
|
||||
f.write_str("ECDHE_ECDSA_CHACHA20_POLY1305_SHA256")
|
||||
}
|
||||
Dtls12CipherSuite::PSK_AES128_CCM_8 => f.write_str("PSK_AES128_CCM_8"),
|
||||
_ => f.debug_tuple("Unknown").field(&self.0).finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type CompressionMethodVec =
|
||||
ArrayVec<CompressionMethod, { CompressionMethod::supported().len() }>;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[allow(non_camel_case_types)]
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
pub enum KeyExchangeAlgorithm {
|
||||
EECDH,
|
||||
PSK,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
pub type CertificateTypeVec =
|
||||
ArrayVec<ClientCertificateType, { ClientCertificateType::supported().len() }>;
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub struct ClientCertificateType(u8);
|
||||
|
||||
impl ClientCertificateType {
|
||||
pub const RSA_SIGN: Self = Self(1);
|
||||
pub const DSS_SIGN: Self = Self(2);
|
||||
pub const RSA_FIXED_DH: Self = Self(3);
|
||||
pub const DSS_FIXED_DH: Self = Self(4);
|
||||
pub const RSA_EPHEMERAL_DH: Self = Self(5);
|
||||
pub const DSS_EPHEMERAL_DH: Self = Self(6);
|
||||
pub const FORTEZZA_DMS: Self = Self(20);
|
||||
pub const ECDSA_SIGN: Self = Self(64);
|
||||
|
||||
pub const fn from_u8(value: u8) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
/// Returns true if this certificate type is supported by this implementation.
|
||||
/// Currently only ECDSA_SIGN is supported.
|
||||
pub fn is_supported(&self) -> bool {
|
||||
Self::supported().contains(self)
|
||||
}
|
||||
|
||||
/// Supported client certificate types.
|
||||
pub const fn supported() -> &'static [ClientCertificateType; 1] {
|
||||
&[ClientCertificateType::ECDSA_SIGN]
|
||||
}
|
||||
|
||||
pub const fn as_u8(&self) -> u8 {
|
||||
self.0
|
||||
}
|
||||
|
||||
const fn is_unknown(&self) -> bool {
|
||||
!matches!(*self, Self(1..=6 | 20 | 64))
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], ClientCertificateType> {
|
||||
let (input, value) = be_u8(input)?;
|
||||
Ok((input, ClientCertificateType::from_u8(value)))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ClientCertificateType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.is_unknown() {
|
||||
return f.debug_tuple("Unknown").field(&self.0).finish();
|
||||
}
|
||||
|
||||
let name = match *self {
|
||||
ClientCertificateType::RSA_SIGN => "RSA_SIGN",
|
||||
ClientCertificateType::DSS_SIGN => "DSS_SIGN",
|
||||
ClientCertificateType::RSA_FIXED_DH => "RSA_FIXED_DH",
|
||||
ClientCertificateType::DSS_FIXED_DH => "DSS_FIXED_DH",
|
||||
ClientCertificateType::RSA_EPHEMERAL_DH => "RSA_EPHEMERAL_DH",
|
||||
ClientCertificateType::DSS_EPHEMERAL_DH => "DSS_EPHEMERAL_DH",
|
||||
ClientCertificateType::FORTEZZA_DMS => "FORTEZZA_DMS",
|
||||
ClientCertificateType::ECDSA_SIGN => "ECDSA_SIGN",
|
||||
_ => unreachable!("known DTLS 1.2 client certificate type missing Debug label"),
|
||||
};
|
||||
|
||||
f.write_str(name)
|
||||
}
|
||||
}
|
||||
|
||||
// SignatureAlgorithm and HashAlgorithm are now in crate::types
|
||||
|
||||
pub type SignatureAndHashAlgorithmVec =
|
||||
ArrayVec<SignatureAndHashAlgorithm, { SignatureAndHashAlgorithm::supported().len() }>;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct SignatureAndHashAlgorithm {
|
||||
pub hash: HashAlgorithm,
|
||||
pub signature: SignatureAlgorithm,
|
||||
}
|
||||
|
||||
impl SignatureAndHashAlgorithm {
|
||||
pub const fn new(hash: HashAlgorithm, signature: SignatureAlgorithm) -> Self {
|
||||
SignatureAndHashAlgorithm { hash, signature }
|
||||
}
|
||||
|
||||
pub fn from_u16(value: u16) -> Self {
|
||||
let hash = HashAlgorithm::from_u8((value >> 8) as u8);
|
||||
let signature = SignatureAlgorithm::from_u8(value as u8);
|
||||
SignatureAndHashAlgorithm { hash, signature }
|
||||
}
|
||||
|
||||
pub fn as_u16(&self) -> u16 {
|
||||
((self.hash.as_u8() as u16) << 8) | (self.signature.as_u8() as u16)
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureAndHashAlgorithm> {
|
||||
let (input, value) = be_u16(input)?;
|
||||
Ok((input, SignatureAndHashAlgorithm::from_u16(value)))
|
||||
}
|
||||
|
||||
/// All recognized signature+hash combinations.
|
||||
#[allow(dead_code)]
|
||||
pub const fn all() -> &'static [SignatureAndHashAlgorithm; 4] {
|
||||
const ALL: &[SignatureAndHashAlgorithm; 4] = &[
|
||||
SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA),
|
||||
SignatureAndHashAlgorithm::new(HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA),
|
||||
SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::RSA),
|
||||
SignatureAndHashAlgorithm::new(HashAlgorithm::SHA384, SignatureAlgorithm::RSA),
|
||||
];
|
||||
|
||||
ALL
|
||||
}
|
||||
|
||||
/// Supported signature+hash combinations.
|
||||
pub const fn supported() -> &'static [SignatureAndHashAlgorithm; 2] {
|
||||
const SUPPORTED: &[SignatureAndHashAlgorithm; 2] = &[
|
||||
SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA),
|
||||
SignatureAndHashAlgorithm::new(HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA),
|
||||
];
|
||||
|
||||
SUPPORTED
|
||||
}
|
||||
|
||||
/// Returns true if this signature+hash combination is supported.
|
||||
pub fn is_supported(&self) -> bool {
|
||||
Self::supported().contains(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rsa_signature_algorithms_are_recognized_but_not_supported() {
|
||||
let rsa_sha256 =
|
||||
SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::RSA);
|
||||
|
||||
assert!(SignatureAndHashAlgorithm::all().contains(&rsa_sha256));
|
||||
assert!(!rsa_sha256.is_supported());
|
||||
assert_eq!(SignatureAndHashAlgorithm::supported().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dtls12_cipher_suite_newtype_shape() {
|
||||
assert_eq!(std::mem::size_of::<Dtls12CipherSuite>(), 2);
|
||||
assert_eq!(Dtls12CipherSuite::default().as_u16(), 0);
|
||||
assert!(Dtls12CipherSuite::default().is_unknown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dtls12_cipher_suite_wire_roundtrip() {
|
||||
for suite in Dtls12CipherSuite::all() {
|
||||
assert_eq!(Dtls12CipherSuite::from_u16(suite.as_u16()), *suite);
|
||||
assert!(!suite.is_unknown());
|
||||
}
|
||||
|
||||
let unknown = Dtls12CipherSuite::from_u16(0xFFFF);
|
||||
assert_eq!(unknown.as_u16(), 0xFFFF);
|
||||
assert!(unknown.is_unknown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dtls12_cipher_suite_debug_stays_enum_like() {
|
||||
assert_eq!(
|
||||
format!("{:?}", Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256),
|
||||
"ECDHE_ECDSA_AES128_GCM_SHA256"
|
||||
);
|
||||
assert_eq!(
|
||||
format!("{:?}", Dtls12CipherSuite::from_u16(0xFFFF)),
|
||||
"Unknown(65535)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_certificate_type_newtype_shape() {
|
||||
assert_eq!(std::mem::size_of::<ClientCertificateType>(), 1);
|
||||
assert_eq!(ClientCertificateType::default().as_u8(), 0);
|
||||
assert!(ClientCertificateType::default().is_unknown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_certificate_type_wire_roundtrip() {
|
||||
for certificate_type in [
|
||||
ClientCertificateType::RSA_SIGN,
|
||||
ClientCertificateType::DSS_SIGN,
|
||||
ClientCertificateType::RSA_FIXED_DH,
|
||||
ClientCertificateType::DSS_FIXED_DH,
|
||||
ClientCertificateType::RSA_EPHEMERAL_DH,
|
||||
ClientCertificateType::DSS_EPHEMERAL_DH,
|
||||
ClientCertificateType::FORTEZZA_DMS,
|
||||
ClientCertificateType::ECDSA_SIGN,
|
||||
] {
|
||||
assert_eq!(
|
||||
ClientCertificateType::from_u8(certificate_type.as_u8()),
|
||||
certificate_type
|
||||
);
|
||||
assert!(!certificate_type.is_unknown());
|
||||
}
|
||||
|
||||
let unknown = ClientCertificateType::from_u8(0xFF);
|
||||
assert_eq!(unknown.as_u8(), 0xFF);
|
||||
assert!(unknown.is_unknown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_certificate_type_debug_stays_enum_like() {
|
||||
assert_eq!(
|
||||
format!("{:?}", ClientCertificateType::ECDSA_SIGN),
|
||||
"ECDSA_SIGN"
|
||||
);
|
||||
assert_eq!(
|
||||
format!("{:?}", ClientCertificateType::from_u8(0xFF)),
|
||||
"Unknown(255)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_dtls12_cipher_suite_uses_internal_derived_markers() {
|
||||
let unknown = Dtls12CipherSuite::from_u16(0xFFFF);
|
||||
assert!(unknown.hash_algorithm().is_unknown());
|
||||
assert!(
|
||||
unknown
|
||||
.signature_algorithm()
|
||||
.is_some_and(|s| s.is_unknown())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! DTLS 1.2 curve type definitions.
|
||||
//!
|
||||
//! NamedGroup is now in crate::types as it's shared between DTLS versions.
|
||||
//! CurveType is DTLS 1.2 specific (used in ServerKeyExchange).
|
||||
|
||||
use nom::IResult;
|
||||
use nom::number::complete::be_u8;
|
||||
use std::fmt;
|
||||
|
||||
/// Curve type for ECDH parameters in DTLS 1.2.
|
||||
///
|
||||
/// This is specific to DTLS 1.2's ServerKeyExchange message format.
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct CurveType(u8);
|
||||
|
||||
#[allow(non_upper_case_globals)]
|
||||
impl CurveType {
|
||||
/// Explicit prime curve parameters.
|
||||
pub const ExplicitPrime: Self = Self(1);
|
||||
/// Explicit characteristic-2 curve parameters.
|
||||
pub const ExplicitChar2: Self = Self(2);
|
||||
/// Named curve (the common case).
|
||||
pub const NamedCurve: Self = Self(3);
|
||||
|
||||
/// Convert a u8 value to a `CurveType`.
|
||||
pub const fn from_u8(value: u8) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
/// Convert this `CurveType` to its u8 value.
|
||||
pub const fn as_u8(&self) -> u8 {
|
||||
self.0
|
||||
}
|
||||
|
||||
const fn is_unknown(&self) -> bool {
|
||||
!matches!(*self, Self(1..=3))
|
||||
}
|
||||
|
||||
/// Parse a `CurveType` from wire format.
|
||||
pub fn parse(input: &[u8]) -> IResult<&[u8], CurveType> {
|
||||
let (input, value) = be_u8(input)?;
|
||||
Ok((input, CurveType::from_u8(value)))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CurveType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.is_unknown() {
|
||||
return f.debug_tuple("Unknown").field(&self.0).finish();
|
||||
}
|
||||
|
||||
let name = match *self {
|
||||
CurveType::ExplicitPrime => "ExplicitPrime",
|
||||
CurveType::ExplicitChar2 => "ExplicitChar2",
|
||||
CurveType::NamedCurve => "NamedCurve",
|
||||
_ => unreachable!("known DTLS 1.2 curve type missing Debug label"),
|
||||
};
|
||||
|
||||
f.write_str(name)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn curve_type_newtype_shape() {
|
||||
assert_eq!(std::mem::size_of::<CurveType>(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curve_type_wire_roundtrip() {
|
||||
for curve_type in [
|
||||
CurveType::ExplicitPrime,
|
||||
CurveType::ExplicitChar2,
|
||||
CurveType::NamedCurve,
|
||||
] {
|
||||
assert_eq!(CurveType::from_u8(curve_type.as_u8()), curve_type);
|
||||
assert!(!curve_type.is_unknown());
|
||||
}
|
||||
|
||||
let unknown = CurveType::from_u8(0xFF);
|
||||
assert_eq!(unknown.as_u8(), 0xFF);
|
||||
assert!(unknown.is_unknown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curve_type_debug_stays_enum_like() {
|
||||
assert_eq!(format!("{:?}", CurveType::NamedCurve), "NamedCurve");
|
||||
assert_eq!(format!("{:?}", CurveType::from_u8(0xFF)), "Unknown(255)");
|
||||
}
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
//! DTLS 1.2 record layer types.
|
||||
//!
|
||||
//! ContentType and Sequence are now in crate::types as they're shared between DTLS versions.
|
||||
|
||||
use std::fmt;
|
||||
use std::ops::Range;
|
||||
|
||||
use super::ProtocolVersion;
|
||||
use crate::buffer::Buf;
|
||||
use crate::types::{ContentType, Sequence};
|
||||
use crate::util::be_u48;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::number::complete::be_u16;
|
||||
use nom::{Err, IResult};
|
||||
|
||||
/// DTLS 1.2 record structure.
|
||||
#[derive(PartialEq, Eq, Default)]
|
||||
pub struct DTLSRecord {
|
||||
/// The content type of this record.
|
||||
pub content_type: ContentType,
|
||||
/// The protocol version.
|
||||
pub version: ProtocolVersion,
|
||||
/// The epoch and sequence number.
|
||||
pub sequence: Sequence,
|
||||
/// The length of the fragment.
|
||||
pub length: u16,
|
||||
/// The range of the fragment in the source buffer.
|
||||
pub fragment_range: Range<usize>,
|
||||
}
|
||||
|
||||
impl DTLSRecord {
|
||||
/// DTLS record header length: content_type(1) + version(2) + epoch(2) + seq(6) + length(2)
|
||||
pub const HEADER_LEN: usize = 13;
|
||||
|
||||
/// Length of the explicit nonce prefix in DTLS 1.2 AES-GCM records.
|
||||
pub const EXPLICIT_NONCE_LEN: usize = 8;
|
||||
|
||||
/// Byte offset in the record header where the 2-byte length field is
|
||||
pub const LENGTH_OFFSET: Range<usize> = 11..13;
|
||||
|
||||
/// Parse a DTLS record from the input buffer.
|
||||
pub fn parse(
|
||||
input: &[u8],
|
||||
base_offset: usize,
|
||||
skip_offset: usize,
|
||||
) -> IResult<&[u8], DTLSRecord> {
|
||||
let original_input = input;
|
||||
let (input, content_type) = ContentType::parse(input)?; // u8
|
||||
let (input, version) = ProtocolVersion::parse(input)?; // u16
|
||||
|
||||
// Accept DTLS 1.0 or 1.2 in record layer per RFC 6347
|
||||
// DTLS 1.0 (0xFEFF) is often used in record layer during handshake for compatibility
|
||||
// The actual protocol version is negotiated in the handshake messages
|
||||
match version {
|
||||
ProtocolVersion::DTLS1_0 | ProtocolVersion::DTLS1_2 => {
|
||||
// Valid DTLS versions for record layer
|
||||
}
|
||||
_ => {
|
||||
return Err(Err::Failure(nom::error::Error::new(
|
||||
input,
|
||||
nom::error::ErrorKind::Tag,
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
let (input, epoch) = be_u16(input)?; // u16
|
||||
|
||||
// Epoch 0 records are plaintext in DTLS 1.2. Reject plaintext
|
||||
// ApplicationData before record protection is active, and only accept
|
||||
// the epoch-0 content types this implementation supports.
|
||||
if epoch == 0 {
|
||||
match content_type {
|
||||
ContentType::ChangeCipherSpec | ContentType::Alert | ContentType::Handshake => {}
|
||||
_ => {
|
||||
return Err(Err::Failure(nom::error::Error::new(
|
||||
input,
|
||||
nom::error::ErrorKind::Tag,
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (input, sequence_number) = be_u48(input)?; // u48
|
||||
let (input, length) = be_u16(input)?; // u16
|
||||
|
||||
// When encrypted, skip_offset is 0 and this has the explicit nonce.
|
||||
// When decrypted, skip_offset is > 0 to skip the explicit nonce.
|
||||
let input = &input[skip_offset..];
|
||||
|
||||
let (rest, fragment_slice) = take(length as usize)(input)?;
|
||||
|
||||
// Calculate absolute range in root buffer
|
||||
// fragment_slice is already offset from original_input by all the header bytes and skip_offset
|
||||
let relative_offset = fragment_slice.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let start = base_offset + relative_offset;
|
||||
let end = start + fragment_slice.len();
|
||||
|
||||
let sequence = Sequence {
|
||||
epoch,
|
||||
sequence_number,
|
||||
};
|
||||
|
||||
Ok((
|
||||
rest,
|
||||
DTLSRecord {
|
||||
content_type,
|
||||
version,
|
||||
sequence,
|
||||
length,
|
||||
fragment_range: start..end,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Get the fragment data from the source buffer.
|
||||
pub fn fragment<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
&buf[self.fragment_range.clone()]
|
||||
}
|
||||
|
||||
/// Serialize this record to the output buffer.
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
output.push(self.content_type.as_u8());
|
||||
self.version.serialize(output);
|
||||
output.extend_from_slice(&self.sequence.epoch.to_be_bytes());
|
||||
output.extend_from_slice(&self.sequence.sequence_number.to_be_bytes()[2..]);
|
||||
output.extend_from_slice(&self.length.to_be_bytes());
|
||||
output.extend_from_slice(self.fragment(buf));
|
||||
}
|
||||
|
||||
/// Get the explicit nonce from the fragment using the requested length.
|
||||
pub fn nonce_with_len<'a>(&self, buf: &'a [u8], len: usize) -> &'a [u8] {
|
||||
let fragment = self.fragment(buf);
|
||||
&fragment[..len]
|
||||
}
|
||||
|
||||
/// Get the explicit nonce from the fragment (AES-GCM default).
|
||||
pub fn nonce<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
self.nonce_with_len(buf, Self::EXPLICIT_NONCE_LEN)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for DTLSRecord {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("DTLSRecord")
|
||||
.field("content_type", &self.content_type)
|
||||
.field("version", &self.version)
|
||||
.field("sequence", &self.sequence)
|
||||
.field("length", &self.length)
|
||||
.field("fragment_range", &self.fragment_range)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const RECORD: &[u8] = &[
|
||||
0x16, // ContentType::Handshake
|
||||
0xFE, 0xFD, // ProtocolVersion::DTLS1_2
|
||||
0x00, 0x01, // epoch
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // sequence_number
|
||||
0x00, 0x10, // length
|
||||
// fragment
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
|
||||
0x10,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
// Parse the record with base_offset 0, skip_offset 0
|
||||
let (rest, parsed) = DTLSRecord::parse(RECORD, 0, 0).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Serialize and compare to RECORD
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(RECORD, &mut serialized);
|
||||
assert_eq!(&*serialized, RECORD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn epoch_0_content_type_whitelist() {
|
||||
// Epoch 0 is plaintext (RFC 6347 §4.1: epoch starts at 0, incremented by each CCS).
|
||||
// Only ChangeCipherSpec(20), Alert(21), and Handshake(22) can legitimately
|
||||
// appear unencrypted. ApplicationData in epoch 0 is rejected at parse time.
|
||||
|
||||
fn build_epoch_0_record(content_type: u8) -> Vec<u8> {
|
||||
vec![
|
||||
content_type, // ContentType
|
||||
0xFE,
|
||||
0xFD, // version: DTLS 1.2
|
||||
0x00,
|
||||
0x00, // epoch: 0 (plaintext)
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x01, // sequence_number
|
||||
0x00,
|
||||
0x02, // length: 2
|
||||
0xAA,
|
||||
0xBB, // fragment payload
|
||||
]
|
||||
}
|
||||
|
||||
// ALLOWED: ChangeCipherSpec (20)
|
||||
let ccs = build_epoch_0_record(0x14);
|
||||
assert!(
|
||||
DTLSRecord::parse(&ccs, 0, 0).is_ok(),
|
||||
"ChangeCipherSpec should be allowed in epoch 0"
|
||||
);
|
||||
|
||||
// ALLOWED: Alert (21)
|
||||
let alert = build_epoch_0_record(0x15);
|
||||
assert!(
|
||||
DTLSRecord::parse(&alert, 0, 0).is_ok(),
|
||||
"Alert should be allowed in epoch 0"
|
||||
);
|
||||
|
||||
// ALLOWED: Handshake (22)
|
||||
let handshake = build_epoch_0_record(0x16);
|
||||
assert!(
|
||||
DTLSRecord::parse(&handshake, 0, 0).is_ok(),
|
||||
"Handshake should be allowed in epoch 0"
|
||||
);
|
||||
|
||||
// REJECTED: ApplicationData (23)
|
||||
let app_data = build_epoch_0_record(0x17);
|
||||
assert!(
|
||||
DTLSRecord::parse(&app_data, 0, 0).is_err(),
|
||||
"ApplicationData must be rejected in epoch 0"
|
||||
);
|
||||
|
||||
// REJECTED: Ack (26) - valid in DTLS 1.3 but not DTLS 1.2
|
||||
let ack = build_epoch_0_record(0x1A);
|
||||
assert!(
|
||||
DTLSRecord::parse(&ack, 0, 0).is_err(),
|
||||
"Ack must be rejected in DTLS 1.2 epoch 0"
|
||||
);
|
||||
|
||||
// REJECTED: Unknown ContentType (0x99)
|
||||
let unknown = build_epoch_0_record(0x99);
|
||||
assert!(
|
||||
DTLSRecord::parse(&unknown, 0, 0).is_err(),
|
||||
"Unknown ContentType must be rejected in epoch 0"
|
||||
);
|
||||
|
||||
// Verify that epoch 1+ allows ApplicationData (no whitelist restriction)
|
||||
let mut epoch_1_app_data = build_epoch_0_record(0x17);
|
||||
epoch_1_app_data[3] = 0x00; // epoch high byte
|
||||
epoch_1_app_data[4] = 0x01; // epoch low byte = 1
|
||||
assert!(
|
||||
DTLSRecord::parse(&epoch_1_app_data, 0, 0).is_ok(),
|
||||
"ApplicationData should be allowed in epoch 1+"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
use super::extension::ExtensionVec;
|
||||
use super::extensions::use_srtp::{SrtpProfileId, UseSrtpExtension};
|
||||
use super::{CompressionMethod, Dtls12CipherSuite, Extension, ExtensionType};
|
||||
use super::{ProtocolVersion, Random, SessionId};
|
||||
use crate::buffer::Buf;
|
||||
use arrayvec::ArrayVec;
|
||||
use nom::Err;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::{IResult, bytes::complete::take, number::complete::be_u16};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ServerHello {
|
||||
pub server_version: ProtocolVersion,
|
||||
pub random: Random,
|
||||
pub session_id: SessionId,
|
||||
pub cipher_suite: Dtls12CipherSuite,
|
||||
pub compression_method: CompressionMethod,
|
||||
pub extensions: Option<ExtensionVec>,
|
||||
}
|
||||
|
||||
impl ServerHello {
|
||||
pub fn new(
|
||||
server_version: ProtocolVersion,
|
||||
random: Random,
|
||||
session_id: SessionId,
|
||||
cipher_suite: Dtls12CipherSuite,
|
||||
compression_method: CompressionMethod,
|
||||
extensions: Option<ExtensionVec>,
|
||||
) -> Self {
|
||||
ServerHello {
|
||||
server_version,
|
||||
random,
|
||||
session_id,
|
||||
cipher_suite,
|
||||
compression_method,
|
||||
extensions,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add extensions to ServerHello using a builder-style API, mirroring ClientHello::with_extensions
|
||||
///
|
||||
/// - Uses the provided buffer to stage extension bytes and then stores Range references
|
||||
/// - Includes UseSRTP if a profile is provided
|
||||
/// - Includes Extended Master Secret if the flag is set
|
||||
pub fn with_extensions(mut self, buf: &mut Buf, srtp_profile: Option<SrtpProfileId>) -> Self {
|
||||
// Clear the buffer and collect extension byte ranges
|
||||
buf.clear();
|
||||
|
||||
let mut ranges: ArrayVec<
|
||||
(ExtensionType, usize, usize),
|
||||
{ ExtensionType::supported().len() },
|
||||
> = ArrayVec::new();
|
||||
|
||||
// UseSRTP (if negotiated)
|
||||
if let Some(pid) = srtp_profile {
|
||||
let start = buf.len();
|
||||
let mut profiles = ArrayVec::new();
|
||||
profiles.push(pid);
|
||||
let ext = UseSrtpExtension::new(profiles, ArrayVec::new());
|
||||
ext.serialize(buf);
|
||||
ranges.push((ExtensionType::UseSrtp, start, buf.len()));
|
||||
}
|
||||
|
||||
// Extended Master Secret (mandatory)
|
||||
let start = buf.len();
|
||||
ranges.push((ExtensionType::ExtendedMasterSecret, start, start));
|
||||
|
||||
// Renegotiation Info (RFC 5746) - empty for initial handshake
|
||||
let start = buf.len();
|
||||
buf.push(0); // renegotiated_connection length = 0
|
||||
ranges.push((ExtensionType::RenegotiationInfo, start, buf.len()));
|
||||
|
||||
let mut extensions = ExtensionVec::new();
|
||||
for (t, s, e) in ranges {
|
||||
extensions.push(Extension {
|
||||
extension_type: t,
|
||||
extension_data_range: s..e,
|
||||
});
|
||||
}
|
||||
self.extensions = Some(extensions);
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ServerHello> {
|
||||
let original_input = input;
|
||||
let (input, server_version) = ProtocolVersion::parse(input)?;
|
||||
let (input, random) = Random::parse(input)?;
|
||||
let (input, session_id) = SessionId::parse(input)?;
|
||||
let (input, cipher_suite) = Dtls12CipherSuite::parse(input)?;
|
||||
let (input, compression_method) = CompressionMethod::parse(input)?;
|
||||
|
||||
// Parse extensions if there are any bytes left
|
||||
let (input, extensions) = if !input.is_empty() {
|
||||
// Check if we have enough bytes to read the extensions length (2 bytes)
|
||||
if input.len() < 2 {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::Eof)));
|
||||
}
|
||||
let (input, extensions_len) = be_u16(input)?;
|
||||
|
||||
// Check if we have enough bytes to read the extensions data
|
||||
if input.len() < extensions_len as usize {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::Eof)));
|
||||
}
|
||||
|
||||
if extensions_len > 0 {
|
||||
let (rest, input_ext) = take(extensions_len)(input)?;
|
||||
if !rest.is_empty() {
|
||||
return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue)));
|
||||
}
|
||||
let consumed_to_ext_data =
|
||||
input_ext.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let ext_base_offset = base_offset + consumed_to_ext_data;
|
||||
|
||||
// Parse extensions manually to pass base_offset, filtering unknown types
|
||||
let mut extensions_vec = ExtensionVec::new();
|
||||
let mut current_input = input_ext;
|
||||
let mut current_offset = ext_base_offset;
|
||||
while !current_input.is_empty() {
|
||||
let before_len = current_input.len();
|
||||
let (new_rest, ext) = Extension::parse(current_input, current_offset)?;
|
||||
let parsed_len = before_len - new_rest.len();
|
||||
current_offset += parsed_len;
|
||||
// Only keep supported extension types
|
||||
if ext.extension_type.is_supported() {
|
||||
if extensions_vec
|
||||
.iter()
|
||||
.any(|existing| existing.extension_type == ext.extension_type)
|
||||
{
|
||||
return Err(Err::Failure(Error::new(
|
||||
current_input,
|
||||
ErrorKind::LengthValue,
|
||||
)));
|
||||
}
|
||||
extensions_vec.try_push(ext).map_err(|_| {
|
||||
Err::Failure(Error::new(current_input, ErrorKind::LengthValue))
|
||||
})?;
|
||||
}
|
||||
current_input = new_rest;
|
||||
}
|
||||
(rest, Some(extensions_vec))
|
||||
} else {
|
||||
(input, None)
|
||||
}
|
||||
} else {
|
||||
(input, None)
|
||||
};
|
||||
|
||||
Ok((
|
||||
input,
|
||||
ServerHello {
|
||||
server_version,
|
||||
random,
|
||||
session_id,
|
||||
cipher_suite,
|
||||
compression_method,
|
||||
extensions,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) {
|
||||
output.extend_from_slice(&self.server_version.as_u16().to_be_bytes());
|
||||
self.random.serialize(output);
|
||||
output.push(self.session_id.len() as u8);
|
||||
output.extend_from_slice(&self.session_id);
|
||||
output.extend_from_slice(&self.cipher_suite.as_u16().to_be_bytes());
|
||||
output.push(self.compression_method.as_u8());
|
||||
if let Some(extensions) = &self.extensions {
|
||||
// Calculate total extensions length according to spec:
|
||||
// For each extension: type (2) + length (2) + data
|
||||
let mut extensions_len = 0;
|
||||
for ext in extensions.iter() {
|
||||
let ext_data = ext.extension_data(source_buf);
|
||||
extensions_len += 2 + 2 + ext_data.len();
|
||||
}
|
||||
|
||||
// Write extensions length
|
||||
output.extend_from_slice(&(extensions_len as u16).to_be_bytes());
|
||||
|
||||
// Write each extension
|
||||
for ext in extensions {
|
||||
ext.serialize(source_buf, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const MESSAGE: &[u8] = &[
|
||||
0xFE, 0xFD, // ProtocolVersion::DTLS1_2
|
||||
// Random
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E,
|
||||
0x1F, 0x20, //
|
||||
0x01, // SessionId length
|
||||
0xAA, // SessionId
|
||||
0xC0, 0x2B, // Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
0x00, // CompressionMethod::Null
|
||||
0x00, 0x0C, // Extensions length (12 bytes total: 2 type + 2 length + 8 data)
|
||||
0x00, 0x0A, // ExtensionType::SupportedGroups
|
||||
0x00, 0x08, // Extension data length (8 bytes)
|
||||
0x00, 0x06, // Extension data
|
||||
0x00, 0x17, // NamedGroup::Secp256r1
|
||||
0x00, 0x18, // NamedGroup::Secp384r1
|
||||
0x00, 0x19, // NamedGroup::Secp521r1
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
// Parse the message first to get the Extension with proper ranges
|
||||
let (rest, parsed) = ServerHello::parse(MESSAGE, 0).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Serialize and compare to MESSAGE
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(MESSAGE, &mut serialized);
|
||||
assert_eq!(&*serialized, MESSAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_id_too_long() {
|
||||
let mut message = MESSAGE.to_vec();
|
||||
message[34] = 0x21; // SessionId length (33, which is too long)
|
||||
|
||||
let result = ServerHello::parse(&message, 0);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_supported_extensions_are_rejected() {
|
||||
for count in [2, 9] {
|
||||
let mut message = MESSAGE[..39].to_vec();
|
||||
message.extend_from_slice(&(count as u16 * 4).to_be_bytes());
|
||||
for _ in 0..count {
|
||||
message
|
||||
.extend_from_slice(&ExtensionType::ExtendedMasterSecret.as_u16().to_be_bytes());
|
||||
message.extend_from_slice(&0u16.to_be_bytes());
|
||||
}
|
||||
|
||||
let result = ServerHello::parse(&message, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(nom::Err::Failure(error))
|
||||
if error.code == nom::error::ErrorKind::LengthValue
|
||||
),
|
||||
"duplicate supported extensions should fail with LengthValue"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
use super::{CurveType, DigitallySigned, KeyExchangeAlgorithm, NamedGroup};
|
||||
use crate::buffer::Buf;
|
||||
use nom::Err;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::number::complete::be_u8;
|
||||
use nom::{IResult, bytes::complete::take};
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ServerKeyExchange {
|
||||
pub params: ServerKeyExchangeParams,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ServerKeyExchangeParams {
|
||||
Ecdh(EcdhParams),
|
||||
Psk(PskParams),
|
||||
}
|
||||
|
||||
impl ServerKeyExchange {
|
||||
pub fn parse(
|
||||
input: &[u8],
|
||||
base_offset: usize,
|
||||
key_exchange_algorithm: KeyExchangeAlgorithm,
|
||||
) -> IResult<&[u8], ServerKeyExchange> {
|
||||
let (input, params) = match key_exchange_algorithm {
|
||||
KeyExchangeAlgorithm::EECDH => {
|
||||
let (input, ecdh_params) = EcdhParams::parse(input, base_offset)?;
|
||||
(input, ServerKeyExchangeParams::Ecdh(ecdh_params))
|
||||
}
|
||||
KeyExchangeAlgorithm::PSK => {
|
||||
let (input, psk_params) = PskParams::parse(input, base_offset)?;
|
||||
(input, ServerKeyExchangeParams::Psk(psk_params))
|
||||
}
|
||||
_ => return Err(Err::Failure(Error::new(input, ErrorKind::Tag))),
|
||||
};
|
||||
|
||||
Ok((input, ServerKeyExchange { params }))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf, with_signature: bool) {
|
||||
match &self.params {
|
||||
ServerKeyExchangeParams::Ecdh(ecdh_params) => {
|
||||
ecdh_params.serialize(buf, output, with_signature)
|
||||
}
|
||||
ServerKeyExchangeParams::Psk(psk_params) => psk_params.serialize(buf, output),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn signature(&self) -> Option<&DigitallySigned> {
|
||||
match &self.params {
|
||||
ServerKeyExchangeParams::Ecdh(ecdh_params) => ecdh_params.signature.as_ref(),
|
||||
ServerKeyExchangeParams::Psk(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct EcdhParams {
|
||||
pub curve_type: CurveType,
|
||||
pub named_group: NamedGroup,
|
||||
pub public_key_range: Range<usize>,
|
||||
pub signature: Option<DigitallySigned>,
|
||||
}
|
||||
|
||||
impl EcdhParams {
|
||||
pub fn public_key<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
&buf[self.public_key_range.clone()]
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], EcdhParams> {
|
||||
let original_input = input;
|
||||
let (input, curve_type) = CurveType::parse(input)?;
|
||||
let (input, named_group) = NamedGroup::parse(input)?;
|
||||
|
||||
// First byte is the length of the public key
|
||||
let (input, public_key_len) = be_u8(input)?;
|
||||
let (input, public_key_slice) = take(public_key_len as usize)(input)?;
|
||||
|
||||
// Calculate absolute range for public key
|
||||
let relative_offset = public_key_slice.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let start = base_offset + relative_offset;
|
||||
let end = start + public_key_slice.len();
|
||||
let public_key_range = start..end;
|
||||
|
||||
// Optionally parse a trailing DigitallySigned structure
|
||||
let (input, signature) = if !input.is_empty() {
|
||||
// Calculate absolute offset for the signature part
|
||||
let sig_offset =
|
||||
base_offset + (input.as_ptr() as usize - original_input.as_ptr() as usize);
|
||||
let (rest, signed) = DigitallySigned::parse(input, sig_offset)?;
|
||||
(rest, Some(signed))
|
||||
} else {
|
||||
(input, None)
|
||||
};
|
||||
|
||||
Ok((
|
||||
input,
|
||||
EcdhParams {
|
||||
curve_type,
|
||||
named_group,
|
||||
public_key_range,
|
||||
signature,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf, with_signature: bool) {
|
||||
let public_key = self.public_key(buf);
|
||||
output.push(self.curve_type.as_u8());
|
||||
output.extend_from_slice(&self.named_group.as_u16().to_be_bytes());
|
||||
output.push(public_key.len() as u8);
|
||||
output.extend_from_slice(public_key);
|
||||
|
||||
if with_signature {
|
||||
if let Some(signed) = &self.signature {
|
||||
signed.serialize(buf, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PSK identity hint (RFC 4279 §2).
|
||||
///
|
||||
/// Wire format: `uint16 hint_length + hint`
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct PskParams {
|
||||
pub hint_range: Range<usize>,
|
||||
}
|
||||
|
||||
impl PskParams {
|
||||
pub fn hint<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
&buf[self.hint_range.clone()]
|
||||
}
|
||||
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], PskParams> {
|
||||
let original_input = input;
|
||||
let (input, hint_len) = nom::number::complete::be_u16(input)?;
|
||||
let (input, hint_slice) = take(hint_len as usize)(input)?;
|
||||
|
||||
let relative_offset = hint_slice.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let start = base_offset + relative_offset;
|
||||
let end = start + hint_slice.len();
|
||||
|
||||
Ok((
|
||||
input,
|
||||
PskParams {
|
||||
hint_range: start..end,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
|
||||
let hint = self.hint(buf);
|
||||
output.extend_from_slice(&(hint.len() as u16).to_be_bytes());
|
||||
output.extend_from_slice(hint);
|
||||
}
|
||||
|
||||
/// Serialize directly from hint bytes (for sending).
|
||||
pub fn serialize_from_bytes(hint: &[u8], output: &mut Buf) {
|
||||
output.extend_from_slice(&(hint.len() as u16).to_be_bytes());
|
||||
output.extend_from_slice(hint);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::super::{HashAlgorithm, SignatureAlgorithm, SignatureAndHashAlgorithm};
|
||||
use super::*;
|
||||
use crate::buffer::Buf;
|
||||
|
||||
const MESSAGE_ECDH_PUBKEY: &[u8] = &[
|
||||
0x03, // curve_type
|
||||
0x00, 0x17, // named_group
|
||||
0x04, // public_key length
|
||||
0x01, 0x02, 0x03, 0x04, // public_key
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn roundtrip_ecdh() {
|
||||
// Build expected message
|
||||
let algorithm =
|
||||
SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::RSA);
|
||||
let signature_bytes: &[u8] = &[0x05, 0x06, 0x07, 0x08];
|
||||
|
||||
let mut expected = Buf::new();
|
||||
expected.extend_from_slice(MESSAGE_ECDH_PUBKEY);
|
||||
expected.extend_from_slice(&algorithm.as_u16().to_be_bytes());
|
||||
expected.extend_from_slice(&(signature_bytes.len() as u16).to_be_bytes());
|
||||
expected.extend_from_slice(signature_bytes);
|
||||
|
||||
// Parse the message with base_offset 0
|
||||
let (rest, parsed) =
|
||||
ServerKeyExchange::parse(&expected, 0, KeyExchangeAlgorithm::EECDH).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
// Serialize and compare to expected bytes
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(&expected, &mut serialized, true);
|
||||
assert_eq!(&*serialized, &*expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psk_roundtrip() {
|
||||
// PSK ServerKeyExchange: just hint_length + hint
|
||||
const PSK_MESSAGE: &[u8] = &[
|
||||
0x00, 0x04, // hint length = 4
|
||||
b'h', b'i', b'n', b't',
|
||||
];
|
||||
let (rest, parsed) =
|
||||
ServerKeyExchange::parse(PSK_MESSAGE, 0, KeyExchangeAlgorithm::PSK).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
|
||||
let ServerKeyExchangeParams::Psk(psk) = &parsed.params else {
|
||||
panic!("expected Psk variant");
|
||||
};
|
||||
assert_eq!(&PSK_MESSAGE[psk.hint_range.clone()], b"hint");
|
||||
assert!(
|
||||
parsed.signature().is_none(),
|
||||
"PSK SKE must have no signature"
|
||||
);
|
||||
|
||||
let mut serialized = Buf::new();
|
||||
parsed.serialize(PSK_MESSAGE, &mut serialized, true);
|
||||
assert_eq!(&*serialized, PSK_MESSAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psk_rejects_oversized_hint_length() {
|
||||
// hint_length=0x00FF (255) but only 2 bytes follow — parser must fail
|
||||
let bad: &[u8] = &[0x00, 0xFF, b'a', b'b'];
|
||||
let result = ServerKeyExchange::parse(bad, 0, KeyExchangeAlgorithm::PSK);
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"parser must reject PSK hint shorter than advertised length"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psk_empty_hint() {
|
||||
// Zero-length hint is wire-legal (RFC 4279 §2).
|
||||
let empty: &[u8] = &[0x00, 0x00];
|
||||
let (rest, parsed) = ServerKeyExchange::parse(empty, 0, KeyExchangeAlgorithm::PSK).unwrap();
|
||||
assert!(rest.is_empty());
|
||||
let ServerKeyExchangeParams::Psk(psk) = &parsed.params else {
|
||||
panic!("expected Psk variant");
|
||||
};
|
||||
assert!(psk.hint_range.is_empty());
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
use nom::Err;
|
||||
use nom::IResult;
|
||||
use nom::bytes::complete::take;
|
||||
use nom::error::{Error, ErrorKind};
|
||||
use nom::number::complete::{be_u16, be_u24};
|
||||
use std::ops::Range;
|
||||
|
||||
macro_rules! wrapped_slice {
|
||||
($name:ident, $length_parser:path, $min:expr) => {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct $name(pub Range<usize>);
|
||||
|
||||
impl $name {
|
||||
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Self> {
|
||||
let original_input = input;
|
||||
let (input, len) = $length_parser(input)?;
|
||||
#[allow(unused_comparisons)]
|
||||
if len < $min {
|
||||
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
|
||||
}
|
||||
let (input, data_slice) = take(len)(input)?;
|
||||
|
||||
// Calculate absolute range in root buffer
|
||||
let relative_offset =
|
||||
data_slice.as_ptr() as usize - original_input.as_ptr() as usize;
|
||||
let start = base_offset + relative_offset;
|
||||
let end = start + data_slice.len();
|
||||
|
||||
Ok((input, $name(start..end)))
|
||||
}
|
||||
|
||||
pub fn as_slice<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
|
||||
&buf[self.0.clone()]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
wrapped_slice!(Asn1Cert, be_u24, 0);
|
||||
wrapped_slice!(DistinguishedName, be_u16, 1);
|
||||
Reference in new issue
Block a user