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:
Claude committed 2026-09-26 23:27:21 +00:00
1 parent 3aba9a165d
commit ce7c833aa8
152 files changed
+56138 -5

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+633
View File
@@ -0,0 +1,633 @@
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use arrayvec::ArrayVec;
use std::fmt;
use crate::buffer::{Buf, TmpBuf};
use crate::dtls13::message::{ContentType, Dtls13CipherSuite, Dtls13Record, Handshake, Sequence};
use crate::{Error, InternalError};
/// Holds both the UDP packet and the parsed result of that packet.
pub struct Incoming {
// Box is here to reduce the size of the Incoming struct
// to be passed in register instead of using memmove.
records: Box<Records>,
}
impl Incoming {
pub fn records(&self) -> &Records {
&self.records
}
pub fn first(&self) -> &Record {
// Invariant: Every Incoming must have at least one Record
// or the parser of Incoming returns None.
&self.records()[0]
}
pub fn into_records(self) -> impl Iterator<Item = Record> {
self.records.records.into_iter()
}
}
impl Incoming {
/// Parse an incoming UDP packet
///
/// * `packet` is the data from the UDP socket.
/// * `decrypt` provides the decryption operations for encrypted records.
/// * `cs` is the negotiated cipher suite, if any.
///
/// Will surface parser errors.
pub fn parse_packet(
packet: &[u8],
decrypt: &mut dyn RecordHandler,
cs: Option<Dtls13CipherSuite>,
) -> Result<Option<Self>, InternalError> {
// Parse records directly from packet, copying each record ONCE into its own buffer
let records = Records::parse(packet, decrypt, cs)?;
// We need at least one Record to be valid. For replayed frames, we discard
// the records, hence this might be None
if records.records.is_empty() {
return Ok(None);
}
let records = Box::new(records);
Ok(Some(Incoming { records }))
}
}
/// A number of records parsed from a single UDP packet.
#[derive(Debug)]
pub struct Records {
pub records: ArrayVec<Record, 16>,
}
impl Records {
pub fn parse(
mut packet: &[u8],
decrypt: &mut dyn RecordHandler,
cs: Option<Dtls13CipherSuite>,
) -> Result<Records, InternalError> {
let mut parsed_records: ArrayVec<Record, 16> = ArrayVec::new();
// Find record boundaries and copy each record ONCE from the packet
while !packet.is_empty() {
let record_end = if Dtls13Record::is_ciphertext_header(packet[0]) {
// CID bit set means we can't determine record boundaries (unsupported).
// Discard the rest of the datagram.
if packet[0] & 0x10 != 0 {
break;
}
// Unified header: variable length
if packet.len() < 2 {
return Err(InternalError::parse_incomplete());
}
let flags = packet[0];
let s_flag = flags & 0b0000_1000 != 0;
let l_flag = flags & 0b0000_0100 != 0;
let seq_len = if s_flag { 2 } else { 1 };
let len_len = if l_flag { 2 } else { 0 };
let header_len = 1 + seq_len + len_len;
if packet.len() < header_len {
return Err(InternalError::parse_incomplete());
}
if l_flag {
let len_offset = 1 + seq_len;
// unwrap: header_len check above ensures 2 bytes at len_offset
let length_bytes: [u8; 2] =
packet[len_offset..len_offset + 2].try_into().unwrap();
let length = u16::from_be_bytes(length_bytes) as usize;
header_len + length
} else {
// No length field: record consumes the rest of the datagram
packet.len()
}
} else {
// Plaintext: fixed 13-byte header
if packet.len() < Dtls13Record::PLAINTEXT_HEADER_LEN {
return Err(InternalError::parse_incomplete());
}
// unwrap: PLAINTEXT_HEADER_LEN check above ensures 2 bytes at offset
let length_bytes: [u8; 2] = packet[Dtls13Record::PLAINTEXT_LENGTH_OFFSET]
.try_into()
.unwrap();
let length = u16::from_be_bytes(length_bytes) as usize;
Dtls13Record::PLAINTEXT_HEADER_LEN + length
};
if packet.len() < record_end {
return Err(InternalError::parse_incomplete());
}
// This is the ONLY copy: packet -> record buffer
let record_slice = &packet[..record_end];
let record = Record::parse(record_slice, decrypt, cs)?;
if let Some(record) = record {
if parsed_records.try_push(record).is_err() {
return Err(InternalError::too_many_records());
}
} else {
trace!("Discarding replayed rec");
}
packet = &packet[record_end..];
}
let mut records = ArrayVec::new();
for record in parsed_records {
if let Some(record) = decrypt.classify_record(record)? {
records
.try_push(record)
.expect("filtered records cannot exceed parsed records");
}
}
Ok(Records { records })
}
}
impl Deref for Records {
type Target = [Record];
fn deref(&self) -> &Self::Target {
&self.records
}
}
pub struct Record {
buffer: Buf,
// Box is here to reduce the size of the Record struct
// to be passed in register instead of using memmove.
parsed: Box<ParsedRecord>,
}
impl Record {
/// The first parse pass only parses the record header which is unencrypted.
/// Copies record data from UDP packet ONCE into a pooled buffer.
pub fn parse(
record_slice: &[u8],
decrypt: &mut dyn RecordHandler,
cs: Option<Dtls13CipherSuite>,
) -> Result<Option<Record>, InternalError> {
// ONLY COPY: UDP packet slice -> pooled buffer
let mut buffer = Buf::new();
buffer.extend_from_slice(record_slice);
let is_ciphertext = Dtls13Record::is_ciphertext_header(buffer[0]);
// Decrypt record number in-place before parsing (RFC 9147 Section 4.2.3)
if is_ciphertext && decrypt.is_peer_encryption_enabled() {
let flags = buffer[0];
let s_flag = flags & 0b0000_1000 != 0;
let l_flag = flags & 0b0000_0100 != 0;
let seq_len: usize = if s_flag { 2 } else { 1 };
let len_len: usize = if l_flag { 2 } else { 0 };
let header_len = 1 + seq_len + len_len;
if buffer.len() >= header_len + 16 {
// unwrap: bounds checked above
let ciphertext_sample: [u8; 16] =
buffer[header_len..header_len + 16].try_into().unwrap();
// Resolve epoch from 2-bit field (doesn't depend on seq bytes)
let epoch_bits = flags & 0x03;
let full_epoch = decrypt.resolve_epoch(epoch_bits);
// Decrypt sequence bytes in place
decrypt.decrypt_sequence_number(
full_epoch,
&mut buffer[1..1 + seq_len],
&ciphertext_sample,
);
}
}
let parsed = match ParsedRecord::parse(&buffer, cs) {
Ok(p) => p,
Err(e) => {
trace!("Discarding record: parse failed: {}", e);
return Ok(None);
}
};
let parsed = Box::new(parsed);
let record = Record { buffer, parsed };
// Plaintext records (epoch 0) are not encrypted
if !is_ciphertext || !decrypt.is_peer_encryption_enabled() {
return Ok(Some(record));
}
// Resolve the full epoch from the 2-bit value in the unified header
let epoch_bits = record.record().sequence.epoch as u8;
let full_epoch = decrypt.resolve_epoch(epoch_bits);
// Resolve the full sequence number from the (now decrypted) partial value
let seq_bits = record.record().sequence.sequence_number;
let s_flag = record_slice[0] & 0b0000_1000 != 0;
let full_seq = decrypt.resolve_sequence(full_epoch, seq_bits, s_flag);
let full_sequence = Sequence {
epoch: full_epoch,
sequence_number: full_seq,
};
// Anti-replay check (read-only, does not update window)
if !decrypt.replay_check(full_sequence) {
return Ok(None);
}
// Save the raw header bytes for AAD before mutating the buffer.
// Max unified header without CID: flags(1) + seq(2) + length(2) = 5 bytes.
let header_end = record.record().fragment_range.start;
// Reject protected records whose encrypted fragment is shorter than
// the per-suite minimum — they cannot hold a valid ciphertext + tag,
// so decryption would necessarily fail. Catching it here keeps the
// cipher impls' bounds-checking from being the only line of defence.
if record.buffer.len() - header_end < decrypt.min_protected_fragment_len() {
return Ok(None);
}
let mut header_buf = [0u8; 5];
header_buf[..header_end].copy_from_slice(&record.buffer[..header_end]);
// Extract the buffer for decryption
let mut buffer = record.buffer;
// The encrypted part starts right after the unified header.
let ciphertext = &mut buffer[header_end..];
let new_len = {
let mut buffer = TmpBuf::new(ciphertext);
// This decrypts in place.
// RFC 9147 §4.5.2: failed-to-decrypt ciphertext records MUST be silently discarded.
match decrypt.decrypt_record(&header_buf[..header_end], full_sequence, &mut buffer) {
Ok(()) => {}
Err(e) => {
trace!("Discarding ciphertext record: decryption failed: {}", e);
return Ok(None);
}
}
buffer.len()
};
// Decryption succeeded — now commit the replay window update.
// RFC 9147 §4.5.1: "The window MUST NOT be updated due to a received
// record until that record has been deprotected successfully."
decrypt.replay_update(full_sequence);
// Recover inner content type from DTLSInnerPlaintext
let decrypted = &buffer[header_end..header_end + new_len];
let (inner_content_type, content_len) = match recover_inner_content_type(decrypted) {
Ok(v) => v,
Err(e) => {
trace!("Discarding record: invalid inner content type: {}", e);
return Ok(None);
}
};
let parsed = ParsedRecord::parse_decrypted(
Dtls13Record {
content_type: inner_content_type,
sequence: full_sequence,
length: content_len as u16,
fragment_range: header_end..(header_end + content_len),
},
&buffer,
cs,
);
let parsed = Box::new(parsed);
Ok(Some(Record { buffer, parsed }))
}
pub fn record(&self) -> &Dtls13Record {
&self.parsed.record
}
pub fn handshakes(&self) -> &[Handshake] {
&self.parsed.handshakes
}
pub fn first_handshake(&self) -> Option<&Handshake> {
self.parsed.handshakes.first()
}
pub fn is_handled(&self) -> bool {
if self.parsed.handshakes.is_empty() {
self.parsed.handled.load(Ordering::Relaxed)
} else {
self.parsed.handshakes.iter().all(|h| h.is_handled())
}
}
pub fn set_handled(&self) {
// Handshakes should be empty because we set_handled() on them individually
// during defragmentation. set_handled() on the record is only for non-handshakes.
assert!(self.parsed.handshakes.is_empty());
self.parsed.handled.store(true, Ordering::Relaxed);
}
pub fn buffer(&self) -> &[u8] {
&self.buffer
}
pub(crate) fn into_buffer(self) -> Buf {
self.buffer
}
}
pub struct ParsedRecord {
record: Dtls13Record,
handshakes: ArrayVec<Handshake, 8>,
handled: AtomicBool,
}
impl ParsedRecord {
pub fn parse(
input: &[u8],
cipher_suite: Option<Dtls13CipherSuite>,
) -> Result<ParsedRecord, InternalError> {
let (_, record) = Dtls13Record::parse(input, 0)?;
let handshakes = if record.content_type == ContentType::Handshake {
let fragment_offset = record.fragment_range.start;
parse_handshakes(record.fragment(input), fragment_offset, cipher_suite)
} else {
ArrayVec::new()
};
Ok(ParsedRecord {
record,
handshakes,
handled: AtomicBool::new(false),
})
}
/// Build a ParsedRecord from an already-constructed record (after decryption).
pub fn parse_decrypted(
record: Dtls13Record,
input: &[u8],
cipher_suite: Option<Dtls13CipherSuite>,
) -> ParsedRecord {
let handshakes = if record.content_type == ContentType::Handshake {
let fragment_offset = record.fragment_range.start;
parse_handshakes(record.fragment(input), fragment_offset, cipher_suite)
} else {
ArrayVec::new()
};
ParsedRecord {
record,
handshakes,
handled: AtomicBool::new(false),
}
}
}
/// Trait abstracting record parsing-time handling for incoming records.
///
/// This decouples the record parser from the full `Engine`, allowing the parse loop
/// to decrypt records, classify control records, and queue only the records that
/// should survive into `Incoming`.
pub trait RecordHandler {
fn classify_record(&mut self, record: Record) -> Result<Option<Record>, Error>;
fn is_peer_encryption_enabled(&self) -> bool;
fn resolve_epoch(&self, epoch_bits: u8) -> u16;
fn resolve_sequence(&self, epoch: u16, seq_bits: u64, s_flag: bool) -> u64;
fn replay_check(&self, seq: Sequence) -> bool;
fn replay_update(&mut self, seq: Sequence);
/// Minimum length of a protected record's encrypted fragment for the
/// negotiated suite (tag length in DTLS 1.3). Used to reject records that
/// cannot possibly contain a valid ciphertext + tag.
fn min_protected_fragment_len(&self) -> usize;
fn decrypt_record(
&mut self,
header: &[u8],
seq: Sequence,
ciphertext: &mut TmpBuf,
) -> Result<(), Error>;
/// Decrypt the sequence number bytes in a unified header (RFC 9147 Section 4.2.3).
///
/// `epoch` is the resolved full epoch, `seq_bytes` are the encrypted sequence
/// bytes from the header (1 or 2 bytes), and `ciphertext_sample` is the first
/// 16 bytes of the ciphertext following the header.
///
/// Returns the decrypted sequence bytes in-place.
fn decrypt_sequence_number(
&self,
epoch: u16,
seq_bytes: &mut [u8],
ciphertext_sample: &[u8; 16],
);
}
fn parse_handshakes(
mut input: &[u8],
mut base_offset: usize,
cipher_suite: Option<Dtls13CipherSuite>,
) -> ArrayVec<Handshake, 8> {
let mut handshakes = ArrayVec::new();
while !input.is_empty() {
if let Ok((remaining, handshake)) = Handshake::parse(input, base_offset, cipher_suite, true)
{
let len = input.len() - remaining.len();
base_offset += len;
input = remaining;
if handshakes.try_push(handshake).is_err() {
break;
}
} else {
break;
}
}
handshakes
}
/// Recover the inner content type from a decrypted DTLSInnerPlaintext.
///
/// The format is: `content || ContentType || zeros*`
/// Scan backward past zero padding to find the content type byte.
fn recover_inner_content_type(decrypted: &[u8]) -> Result<(ContentType, usize), InternalError> {
let mut i = decrypted.len();
// Skip zero padding
while i > 0 && decrypted[i - 1] == 0 {
i -= 1;
}
if i == 0 {
return Err(InternalError::parse(nom::error::ErrorKind::Fail));
}
// The byte before padding is the content type
i -= 1;
let content_type = ContentType::from_u8(decrypted[i]);
// Content length is everything before the content type byte
Ok((content_type, i))
}
impl fmt::Debug for Incoming {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Incoming")
.field("records", &self.records())
.finish()
}
}
impl fmt::Debug for Record {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Record")
.field("record", &self.parsed.record)
.field("handshakes", &self.parsed.handshakes)
.finish()
}
}
/*
Why it is sound to assert UnwindSafe for Incoming
- No internal unwind boundaries: this crate does not use catch_unwind. We do not
cross panic boundaries internally while mutating state. This marker exists to
document that external callers can wrap our APIs in catch_unwind without
observing broken invariants from this type.
- Read-only builders: our dependent builders (e.g., ParsedRecord::parse) take
only a &[u8] to the buffer and do not mutate the buffer during construction.
An unwind during builder execution therefore cannot leave the buffer partially
mutated across a boundary.
- Decrypt-and-reparse is publish-after-complete: when decrypting we first extract
the buffer, mutate it (in-place decrypt), and only then construct a fresh Record
from the fully transformed bytes. If a panic occurs mid-transformation, the new
Record is not built and the previously-built Record is dropped; no consumer can
observe a half-transformed record across an unwind boundary.
- Interior mutability is benign across unwind: the only interior mutability is
AtomicBool "handled" flags. They are monotonic (false -> true). If an external
caller catches a panic and continues, the worst effect is conservatively
skipping work already done. This does not introduce memory unsafety or aliasing
violations, and no invariants rely on "handled implies delivery".
Given the above, an unwind cannot leave Incoming in a state where broken
invariants are later observed across a catch_unwind boundary. Marking Incoming
as UnwindSafe is a sound assertion and clarifies behavior for callers.
*/
impl std::panic::UnwindSafe for Incoming {}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct TestHandler {
classify_calls: usize,
dropped_acks: usize,
}
impl RecordHandler for TestHandler {
fn classify_record(&mut self, record: Record) -> Result<Option<Record>, Error> {
self.classify_calls += 1;
if record.record().content_type == ContentType::Ack {
self.dropped_acks += 1;
return Ok(None);
}
Ok(Some(record))
}
fn is_peer_encryption_enabled(&self) -> bool {
false
}
fn resolve_epoch(&self, _epoch_bits: u8) -> u16 {
panic!("resolve_epoch should not be called when peer encryption is disabled");
}
fn resolve_sequence(&self, _epoch: u16, _seq_bits: u64, _s_flag: bool) -> u64 {
panic!("resolve_sequence should not be called when peer encryption is disabled");
}
fn replay_check(&self, _seq: Sequence) -> bool {
panic!("replay_check should not be called when peer encryption is disabled");
}
fn replay_update(&mut self, _seq: Sequence) {
panic!("replay_update should not be called when peer encryption is disabled");
}
fn min_protected_fragment_len(&self) -> usize {
panic!(
"min_protected_fragment_len should not be called when peer encryption is disabled"
);
}
fn decrypt_record(
&mut self,
_header: &[u8],
_seq: Sequence,
_ciphertext: &mut TmpBuf,
) -> Result<(), Error> {
panic!("decrypt_record should not be called when peer encryption is disabled");
}
fn decrypt_sequence_number(
&self,
_epoch: u16,
_seq_bytes: &mut [u8],
_ciphertext_sample: &[u8; 16],
) {
panic!("decrypt_sequence_number should not be called when peer encryption is disabled");
}
}
fn build_plaintext_record(content_type: ContentType, seq: u64, fragment: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.push(content_type.as_u8());
out.extend_from_slice(&[0xFE, 0xFD]);
out.extend_from_slice(&0u16.to_be_bytes());
out.extend_from_slice(&seq.to_be_bytes()[2..]);
out.extend_from_slice(&(fragment.len() as u16).to_be_bytes());
out.extend_from_slice(fragment);
out
}
fn build_ciphertext_record(epoch: u16, seq: u16, fragment: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let flags = 0b0010_0000 | 0b0000_1000 | 0b0000_0100 | (epoch as u8 & 0x03);
out.push(flags);
out.extend_from_slice(&seq.to_be_bytes());
out.extend_from_slice(&(fragment.len() as u16).to_be_bytes());
out.extend_from_slice(fragment);
out
}
#[test]
fn parse_packet_filters_control_records_after_packet_validation() {
let mut packet = Vec::new();
packet.extend_from_slice(&build_plaintext_record(ContentType::Ack, 1, &[0xAA, 0xBB]));
packet.extend_from_slice(&build_ciphertext_record(2, 2, &[0x11, 0x22, 0x33]));
let mut handler = TestHandler::default();
let incoming = Incoming::parse_packet(&packet, &mut handler, None)
.unwrap()
.expect("ciphertext application data record should remain");
assert_eq!(handler.classify_calls, 2);
assert_eq!(handler.dropped_acks, 1);
assert_eq!(incoming.records().len(), 1);
assert_eq!(
incoming.first().record().content_type,
ContentType::ApplicationData
);
assert_eq!(incoming.first().record().sequence.epoch, 2);
}
}
+158
View File
@@ -0,0 +1,158 @@
use super::Asn1Cert;
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, be_u16, be_u24};
use std::ops::Range;
/// TLS 1.3 CertificateEntry (RFC 8446 Section 4.4.2).
#[derive(Debug, PartialEq, Eq)]
pub struct CertificateEntry {
pub cert: Asn1Cert,
pub extensions_range: Range<usize>,
}
/// TLS 1.3 Certificate message (RFC 8446 Section 4.4.2).
#[derive(Debug, PartialEq, Eq)]
pub struct Certificate {
pub context_range: Range<usize>,
pub certificate_list: ArrayVec<CertificateEntry, 32>,
}
impl Certificate {
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Certificate> {
let original_input = input;
// certificate_request_context<0..255>
let (input, context_len) = be_u8(input)?;
let (input, context_slice) = take(context_len)(input)?;
let context_relative = context_slice.as_ptr() as usize - original_input.as_ptr() as usize;
let context_range = (base_offset + context_relative)
..(base_offset + context_relative + context_slice.len());
// certificate_list<0..2^24-1>
let (input, total_len) = be_u24(input)?;
let (input, certs_data) = take(total_len)(input)?;
let certs_base_offset =
base_offset + (certs_data.as_ptr() as usize - original_input.as_ptr() as usize);
let mut certificate_list = ArrayVec::new();
let mut rest = certs_data;
while !rest.is_empty() {
let entry_base =
certs_base_offset + (rest.as_ptr() as usize - certs_data.as_ptr() as usize);
// cert_data<1..2^24-1>
let (r, cert) = Asn1Cert::parse(rest, entry_base)?;
// extensions<0..2^16-1>
let (r, ext_len) = be_u16(r)?;
let (r, ext_slice) = take(ext_len)(r)?;
let ext_relative = ext_slice.as_ptr() as usize - certs_data.as_ptr() as usize;
let extensions_range = (certs_base_offset + ext_relative)
..(certs_base_offset + ext_relative + ext_slice.len());
certificate_list
.try_push(CertificateEntry {
cert,
extensions_range,
})
.map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?;
rest = r;
}
Ok((
input,
Certificate {
context_range,
certificate_list,
},
))
}
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
// certificate_request_context
let context = &buf[self.context_range.clone()];
output.push(context.len() as u8);
output.extend_from_slice(context);
// Calculate total certificate_list length
let total_len: usize = self
.certificate_list
.iter()
.map(|entry| {
let cert_data = entry.cert.as_slice(buf);
let ext_data = &buf[entry.extensions_range.clone()];
3 + cert_data.len() + 2 + ext_data.len()
})
.sum();
output.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]);
for entry in &self.certificate_list {
let cert_data = entry.cert.as_slice(buf);
output.extend_from_slice(&(cert_data.len() as u32).to_be_bytes()[1..]);
output.extend_from_slice(cert_data);
let ext_data = &buf[entry.extensions_range.clone()];
output.extend_from_slice(&(ext_data.len() as u16).to_be_bytes());
output.extend_from_slice(ext_data);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::buffer::Buf;
const MESSAGE: &[u8] = &[
0x02, // context length
0xAA, 0xBB, // context bytes
0x00, 0x00, 0x12, // total certificate_list length (18)
// CertificateEntry 1
0x00, 0x00, 0x04, // cert_data length
0x01, 0x02, 0x03, 0x04, // cert_data
0x00, 0x00, // extensions length (0)
// CertificateEntry 2
0x00, 0x00, 0x02, // cert_data length
0x05, 0x06, // cert_data
0x00, 0x02, // extensions length (2)
0xDE, 0xAD, // extension bytes (opaque)
];
#[test]
fn roundtrip() {
let (rest, parsed) = Certificate::parse(MESSAGE, 0).unwrap();
assert!(rest.is_empty());
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();
message.push(0x00); // empty certificate_request_context
let total_len = 33 * 6;
message.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]);
for _ in 0..33 {
message.extend_from_slice(&[0x00, 0x00, 0x01, 0xAA]); // cert_data
message.extend_from_slice(&[0x00, 0x00]); // empty extensions
}
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,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, 0x03, // SignatureScheme::ECDSA_SECP256R1_SHA256
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);
}
}
+385
View File
@@ -0,0 +1,385 @@
use super::{CompressionMethod, Dtls13CipherSuite, ProtocolVersion};
use super::{Cookie, Extension, 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 crate::buffer::Buf;
use crate::util::{many0, many1};
#[derive(Debug, PartialEq, Eq)]
pub struct ClientHello {
pub legacy_version: ProtocolVersion,
pub random: Random,
pub legacy_session_id: SessionId,
pub legacy_cookie: Cookie,
pub cipher_suites: ArrayVec<Dtls13CipherSuite, 3>,
pub legacy_compression_methods: ArrayVec<CompressionMethod, 1>,
pub extensions: ArrayVec<Extension, 8>,
}
impl ClientHello {
pub fn new(
legacy_version: ProtocolVersion,
random: Random,
legacy_session_id: SessionId,
legacy_cookie: Cookie,
cipher_suites: ArrayVec<Dtls13CipherSuite, 3>,
legacy_compression_methods: ArrayVec<CompressionMethod, 1>,
) -> Self {
ClientHello {
legacy_version,
random,
legacy_session_id,
legacy_cookie,
cipher_suites,
legacy_compression_methods,
extensions: ArrayVec::new(),
}
}
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientHello> {
Self::parse_with_options(input, base_offset, false)
}
pub(crate) fn parse_allow_unknown_suites(
input: &[u8],
base_offset: usize,
) -> IResult<&[u8], ClientHello> {
Self::parse_with_options(input, base_offset, true)
}
fn parse_with_options(
input: &[u8],
base_offset: usize,
allow_unknown_suites: bool,
) -> IResult<&[u8], ClientHello> {
let original_input = input;
let (input, legacy_version) = ProtocolVersion::parse(input)?;
let (input, random) = Random::parse(input)?;
let (input, legacy_session_id) = SessionId::parse(input)?;
let (input, legacy_cookie) = Cookie::parse(input)?;
let (input, cipher_suites_len) = be_u16(input)?;
if cipher_suites_len == 0 || cipher_suites_len % 2 != 0 {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
let (input, input_cipher) = take(cipher_suites_len)(input)?;
let (rest, cipher_suites) = if allow_unknown_suites {
many0(Dtls13CipherSuite::parse, Dtls13CipherSuite::is_supported)(input_cipher)?
} else {
many1(Dtls13CipherSuite::parse, Dtls13CipherSuite::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, legacy_compression_methods) =
many1(CompressionMethod::parse, CompressionMethod::is_supported)(input_compression)?;
if !rest.is_empty() {
return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue)));
}
let consumed = input.as_ptr() as usize - original_input.as_ptr() as usize;
let extensions_base_offset = base_offset + consumed;
let (remaining_input, extensions) = Self::parse_extensions(input, extensions_base_offset)?;
Ok((
remaining_input,
ClientHello {
legacy_version,
random,
legacy_session_id,
legacy_cookie,
cipher_suites,
legacy_compression_methods,
extensions,
},
))
}
fn parse_extensions(
input: &[u8],
base_offset: usize,
) -> IResult<&[u8], ArrayVec<Extension, 8>> {
let mut extensions = ArrayVec::new();
if input.is_empty() {
return Ok((input, extensions));
}
let original_input = input;
let (remaining, extensions_len) = be_u16(input)?;
let (remaining, extensions_data) = take(extensions_len)(remaining)?;
if !remaining.is_empty() {
return Err(Err::Failure(Error::new(remaining, ErrorKind::LengthValue)));
}
let consumed = extensions_data.as_ptr() as usize - original_input.as_ptr() as usize;
let data_base_offset = base_offset + consumed;
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;
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.legacy_version.as_u16().to_be_bytes());
self.random.serialize(output);
output.push(self.legacy_session_id.len() as u8);
output.extend_from_slice(&self.legacy_session_id);
output.push(self.legacy_cookie.len() as u8);
output.extend_from_slice(&self.legacy_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.legacy_compression_methods.len() as u8);
for method in &self.legacy_compression_methods {
output.push(method.as_u8());
}
if !self.extensions.is_empty() {
let mut extensions_len = 0;
for ext in &self.extensions {
let ext_data = ext.extension_data(source_buf);
extensions_len += 4 + ext_data.len();
}
output.extend_from_slice(&(extensions_len as u16).to_be_bytes());
for ext in &self.extensions {
ext.serialize(source_buf, output);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::buffer::Buf;
use crate::dtls13::message::ExtensionType;
const MESSAGE: &[u8] = &[
0xFE, 0xFD, // ProtocolVersion::DTLS1_2 (legacy)
// 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, // CipherSuites length
0x13, 0x01, // AES_128_GCM_SHA256
0x13, 0x02, // AES_256_GCM_SHA384
0x01, // CompressionMethods length
0x00, // 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(Dtls13CipherSuite::AES_128_GCM_SHA256);
cipher_suites.push(Dtls13CipherSuite::AES_256_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 mut serialized = Buf::new();
client_hello.serialize(&[], &mut serialized);
assert_eq!(&*serialized, MESSAGE);
let (rest, parsed) = ClientHello::parse(&serialized, 0).unwrap();
assert_eq!(parsed, client_hello);
assert!(rest.is_empty());
}
#[test]
fn dtls12_only_cipher_suites_parse_for_auto_detection() {
let mut message = MESSAGE.to_vec();
// DTLS 1.2 ECDHE_ECDSA AES-GCM suites are intentionally unknown to
// the DTLS 1.3 suite filter, but the ClientHello is structurally valid.
message[40..44].copy_from_slice(&[0xC0, 0x2B, 0xC0, 0x2C]);
let (rest, parsed) = ClientHello::parse_allow_unknown_suites(&message, 0).unwrap();
assert!(rest.is_empty());
assert!(parsed.cipher_suites.is_empty());
}
#[test]
fn dtls12_only_cipher_suites_are_rejected_by_normal_parse() {
let mut message = MESSAGE.to_vec();
message[40..44].copy_from_slice(&[0xC0, 0x2B, 0xC0, 0x2C]);
assert!(ClientHello::parse(&message, 0).is_err());
}
#[test]
fn empty_cipher_suites_is_malformed_in_both_modes() {
let mut message = Vec::new();
message.extend_from_slice(&MESSAGE[..38]);
message.extend_from_slice(&[0x00, 0x00]);
message.extend_from_slice(&MESSAGE[44..]);
assert!(ClientHello::parse(&message, 0).is_err());
assert!(ClientHello::parse_allow_unknown_suites(&message, 0).is_err());
}
#[test]
fn odd_cipher_suites_is_malformed_in_both_modes() {
let mut message = Vec::new();
message.extend_from_slice(&MESSAGE[..38]);
message.extend_from_slice(&[0x00, 0x03]);
message.extend_from_slice(&[0x13, 0x01, 0x13]);
message.extend_from_slice(&MESSAGE[44..]);
assert!(ClientHello::parse(&message, 0).is_err());
assert!(ClientHello::parse_allow_unknown_suites(&message, 0).is_err());
}
#[test]
fn session_id_too_long() {
let mut message = MESSAGE.to_vec();
message[34] = 0x21; // SessionId length (33, 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, too long for available data)
let result = ClientHello::parse(&message, 0);
assert!(result.is_err());
}
#[test]
fn cipher_suites_capacity_matches_known() {
let client_hello = ClientHello {
legacy_version: ProtocolVersion::DTLS1_2,
random: Random::parse(&MESSAGE[2..34]).unwrap().1,
legacy_session_id: SessionId::empty(),
legacy_cookie: Cookie::empty(),
cipher_suites: ArrayVec::new(),
legacy_compression_methods: ArrayVec::new(),
extensions: ArrayVec::new(),
};
assert_eq!(
client_hello.cipher_suites.capacity(),
Dtls13CipherSuite::supported().len(),
"cipher_suites ArrayVec capacity must match supported Dtls13CipherSuites"
);
}
#[test]
fn extensions_capacity_fits_supported() {
let client_hello = ClientHello {
legacy_version: ProtocolVersion::DTLS1_2,
random: Random::parse(&MESSAGE[2..34]).unwrap().1,
legacy_session_id: SessionId::empty(),
legacy_cookie: Cookie::empty(),
cipher_suites: ArrayVec::new(),
legacy_compression_methods: ArrayVec::new(),
extensions: ArrayVec::new(),
};
assert!(
client_hello.extensions.capacity() >= ExtensionType::supported().len(),
"extensions ArrayVec capacity must fit all supported ExtensionTypes"
);
}
#[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::Cookie.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"
);
}
}
#[test]
fn zero_length_extension_vector_rejects_trailing_bytes() {
let mut message = MESSAGE.to_vec();
message.extend_from_slice(&0u16.to_be_bytes());
message.extend_from_slice(&ExtensionType::Cookie.as_u16().to_be_bytes());
message.extend_from_slice(&0u16.to_be_bytes());
assert!(
ClientHello::parse(&message, 0).is_err(),
"extension vector length 0 must consume the remaining ClientHello body"
);
}
#[test]
fn underdeclared_extension_vector_rejects_trailing_bytes() {
let mut message = MESSAGE.to_vec();
message.extend_from_slice(&4u16.to_be_bytes());
message.extend_from_slice(&ExtensionType::Cookie.as_u16().to_be_bytes());
message.extend_from_slice(&0u16.to_be_bytes());
message.push(0);
assert!(
ClientHello::parse(&message, 0).is_err(),
"declared extension vector length must consume the remaining ClientHello body"
);
}
}
@@ -0,0 +1,68 @@
use crate::buffer::Buf;
use crate::types::SignatureScheme;
use nom::number::complete::be_u16;
use nom::{IResult, bytes::complete::take};
use std::ops::Range;
#[derive(Debug, PartialEq, Eq)]
pub struct DigitallySigned {
pub scheme: SignatureScheme,
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, scheme) = SignatureScheme::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 {
scheme,
signature_range: start..end,
},
))
}
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
output.extend_from_slice(&self.scheme.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, 0x03, // SignatureScheme::ECDSA_SECP256R1_SHA256
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);
}
}
@@ -0,0 +1,129 @@
use super::Extension;
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_u16;
/// EncryptedExtensions message (RFC 8446 Section 4.3.1).
#[derive(Debug, PartialEq, Eq)]
pub struct EncryptedExtensions {
pub extensions: ArrayVec<Extension, 5>,
}
impl EncryptedExtensions {
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], EncryptedExtensions> {
let original_input = input;
let (input, extensions_len) = be_u16(input)?;
let (input, extensions_data) = take(extensions_len)(input)?;
let data_base_offset =
base_offset + (extensions_data.as_ptr() as usize - original_input.as_ptr() as usize);
let mut extensions = ArrayVec::new();
let mut rest = extensions_data;
let mut current_offset = data_base_offset;
while !rest.is_empty() {
let before_len = rest.len();
let (new_rest, ext) = Extension::parse(rest, current_offset)?;
let parsed_len = before_len - new_rest.len();
current_offset += parsed_len;
if ext.extension_type.is_supported() {
if extensions
.iter()
.any(|existing: &Extension| existing.extension_type == ext.extension_type)
{
return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue)));
}
extensions
.try_push(ext)
.map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?;
}
rest = new_rest;
}
Ok((input, EncryptedExtensions { extensions }))
}
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
let mut extensions_len = 0usize;
for ext in &self.extensions {
let ext_data = ext.extension_data(buf);
extensions_len += 4 + ext_data.len();
}
output.extend_from_slice(&(extensions_len as u16).to_be_bytes());
for ext in &self.extensions {
ext.serialize(buf, output);
}
}
}
#[cfg(test)]
mod tests {
use super::super::ExtensionType;
use super::*;
use crate::buffer::Buf;
const MESSAGE: &[u8] = &[
0x00, 0x0C, // Extensions length (12)
0x00, 0x0A, // ExtensionType::SupportedGroups
0x00, 0x08, // Extension data length
0x00, 0x06, 0x00, 0x17, 0x00, 0x18, 0x00, 0x19, // Extension data
];
#[test]
fn roundtrip() {
let (rest, parsed) = EncryptedExtensions::parse(MESSAGE, 0).unwrap();
assert!(rest.is_empty());
let mut serialized = Buf::new();
parsed.serialize(MESSAGE, &mut serialized);
assert_eq!(&*serialized, MESSAGE);
}
#[test]
fn duplicate_supported_extensions_are_rejected() {
let mut message = Vec::new();
let count = 2;
message.extend_from_slice(&(count as u16 * 4).to_be_bytes());
for _ in 0..count {
message.extend_from_slice(&ExtensionType::Cookie.as_u16().to_be_bytes());
message.extend_from_slice(&0u16.to_be_bytes());
}
let result = EncryptedExtensions::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"
);
}
#[test]
fn too_many_distinct_supported_extensions_are_rejected() {
let mut message = Vec::new();
message.extend_from_slice(&(ExtensionType::supported().len() as u16 * 4).to_be_bytes());
for extension_type in ExtensionType::supported() {
message.extend_from_slice(&extension_type.as_u16().to_be_bytes());
message.extend_from_slice(&0u16.to_be_bytes());
}
let result = EncryptedExtensions::parse(&message, 0);
assert!(
matches!(
result,
Err(nom::Err::Failure(error))
if error.code == nom::error::ErrorKind::LengthValue
),
"too many distinct supported extensions should fail with LengthValue"
);
}
}
+244
View File
@@ -0,0 +1,244 @@
use crate::buffer::Buf;
use nom::{IResult, bytes::complete::take, number::complete::be_u16};
use std::{fmt, ops::Range};
#[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 DTLS 1.3 implementation handles.
pub const fn supported() -> &'static [ExtensionType; 6] {
&[
ExtensionType::SupportedVersions,
ExtensionType::SupportedGroups,
ExtensionType::SignatureAlgorithms,
ExtensionType::KeyShare,
ExtensionType::UseSrtp,
ExtensionType::Cookie,
]
}
}
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.3 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,54 @@
use nom::Err;
use nom::IResult;
use nom::error::{Error, ErrorKind};
use nom::number::complete::be_u16;
/// Parse the DTLS 1.3 Cookie extension body.
///
/// RFC 8446 defines the extension payload as `cookie<1..2^16-1>`,
/// so the extension body is a u16 length followed by exactly that many bytes.
pub(crate) fn parse_cookie_extension(input: &[u8]) -> IResult<&[u8], &[u8]> {
if input.len() < 2 {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
let (rest, cookie_len) = be_u16(input)?;
if cookie_len == 0 || rest.len() != cookie_len as usize {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
Ok((&[], rest))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn malformed_cookie_vectors_are_rejected() {
for input in [
&[][..],
&[0x00],
&[0x00, 0x00],
&[0x00, 0x02, 0xAA],
&[0x00, 0x01, 0xAA, 0xBB],
] {
let result = parse_cookie_extension(input);
assert!(
matches!(
result,
Err(nom::Err::Failure(error))
if error.code == nom::error::ErrorKind::LengthValue
),
"malformed cookie vector should fail with LengthValue: {input:02x?}"
);
}
}
#[test]
fn valid_cookie_vector_is_accepted() {
let (rest, cookie) = parse_cookie_extension(&[0x00, 0x02, 0xAA, 0xBB]).unwrap();
assert!(rest.is_empty());
assert_eq!(cookie, &[0xAA, 0xBB]);
}
}
@@ -0,0 +1,296 @@
use crate::buffer::Buf;
use crate::types::NamedGroup;
use arrayvec::ArrayVec;
use nom::Err;
use nom::IResult;
use nom::bytes::complete::take;
use nom::error::{Error, ErrorKind};
use nom::number::complete::be_u16;
use std::ops::Range;
/// A single KeyShareEntry (RFC 8446 Section 4.2.8).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyShareEntry {
pub group: NamedGroup,
pub key_exchange_range: Range<usize>,
}
impl KeyShareEntry {
pub fn key_exchange<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
&buf[self.key_exchange_range.clone()]
}
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], KeyShareEntry> {
let original_input = input;
let (input, group) = NamedGroup::parse(input)?;
let (input, ke_len) = be_u16(input)?;
let (input, ke_slice) = take(ke_len)(input)?;
let relative_offset = ke_slice.as_ptr() as usize - original_input.as_ptr() as usize;
let start = base_offset + relative_offset;
let end = start + ke_slice.len();
Ok((
input,
KeyShareEntry {
group,
key_exchange_range: start..end,
},
))
}
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
output.extend_from_slice(&self.group.as_u16().to_be_bytes());
let ke = self.key_exchange(buf);
output.extend_from_slice(&(ke.len() as u16).to_be_bytes());
output.extend_from_slice(ke);
}
}
/// KeyShare extension in ClientHello (RFC 8446 Section 4.2.8).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyShareClientHello {
pub entries: ArrayVec<KeyShareEntry, { NamedGroup::supported().len() }>,
}
impl KeyShareClientHello {
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], KeyShareClientHello> {
let original_input = input;
let (input, list_len) = be_u16(input)?;
let (input, entries_data) = take(list_len)(input)?;
if !input.is_empty() {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
let entries_base_offset =
base_offset + (entries_data.as_ptr() as usize - original_input.as_ptr() as usize);
let mut entries = ArrayVec::new();
let mut rest = entries_data;
while !rest.is_empty() {
let entry_offset =
entries_base_offset + (rest.as_ptr() as usize - entries_data.as_ptr() as usize);
let (r, entry) = KeyShareEntry::parse(rest, entry_offset)?;
if entry.group.is_supported() {
entries
.try_push(entry)
.map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?;
}
rest = r;
}
Ok((input, KeyShareClientHello { entries }))
}
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
// Calculate total length of entries
let total_len: usize = self
.entries
.iter()
.map(|e| 2 + 2 + e.key_exchange(buf).len())
.sum();
output.extend_from_slice(&(total_len as u16).to_be_bytes());
for entry in &self.entries {
entry.serialize(buf, output);
}
}
}
/// KeyShare extension in ServerHello (RFC 8446 Section 4.2.8).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyShareServerHello {
pub entry: KeyShareEntry,
}
impl KeyShareServerHello {
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], KeyShareServerHello> {
let (input, entry) = KeyShareEntry::parse(input, base_offset)?;
if !input.is_empty() {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
Ok((input, KeyShareServerHello { entry }))
}
pub fn serialize(&self, buf: &[u8], output: &mut Buf) {
self.entry.serialize(buf, output);
}
}
/// KeyShare extension in HelloRetryRequest (RFC 8446 Section 4.2.8).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyShareHelloRetryRequest {
pub selected_group: NamedGroup,
}
impl KeyShareHelloRetryRequest {
pub fn parse(input: &[u8]) -> IResult<&[u8], KeyShareHelloRetryRequest> {
let (input, selected_group) = NamedGroup::parse(input)?;
if !input.is_empty() {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
Ok((input, KeyShareHelloRetryRequest { selected_group }))
}
pub fn serialize(&self, output: &mut Buf) {
output.extend_from_slice(&self.selected_group.as_u16().to_be_bytes());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::buffer::Buf;
#[test]
fn key_share_client_hello_roundtrip() {
let message: &[u8] = &[
0x00, 0x08, // client_shares length (8)
0x00, 0x1D, // NamedGroup::X25519
0x00, 0x04, // key_exchange length
0x01, 0x02, 0x03, 0x04, // key_exchange data
];
let (rest, parsed) = KeyShareClientHello::parse(message, 0).unwrap();
assert!(rest.is_empty());
let mut serialized = Buf::new();
parsed.serialize(message, &mut serialized);
assert_eq!(&*serialized, message);
}
#[test]
fn key_share_server_hello_roundtrip() {
let message: &[u8] = &[
0x00, 0x1D, // NamedGroup::X25519
0x00, 0x04, // key_exchange length
0x01, 0x02, 0x03, 0x04, // key_exchange data
];
let (rest, parsed) = KeyShareServerHello::parse(message, 0).unwrap();
assert!(rest.is_empty());
let mut serialized = Buf::new();
parsed.serialize(message, &mut serialized);
assert_eq!(&*serialized, message);
}
#[test]
fn key_share_hrr_roundtrip() {
let message: &[u8] = &[
0x00, 0x17, // NamedGroup::Secp256r1
];
let (rest, parsed) = KeyShareHelloRetryRequest::parse(message).unwrap();
assert!(rest.is_empty());
let mut serialized = Buf::new();
parsed.serialize(&mut serialized);
assert_eq!(&*serialized, message);
}
#[test]
fn distinct_supported_key_shares_are_accepted() {
let mut message = Vec::new();
message.extend_from_slice(&(NamedGroup::supported().len() as u16 * 5).to_be_bytes());
for group in NamedGroup::supported() {
message.extend_from_slice(&group.as_u16().to_be_bytes());
message.extend_from_slice(&1u16.to_be_bytes());
message.push(0x42);
}
let (rest, parsed) = KeyShareClientHello::parse(&message, 0).unwrap();
assert!(rest.is_empty());
assert_eq!(parsed.entries.len(), NamedGroup::supported().len());
let mut serialized = Buf::new();
parsed.serialize(&message, &mut serialized);
assert_eq!(&*serialized, message);
}
#[test]
fn too_many_duplicate_supported_key_shares_are_rejected() {
let mut message = Vec::new();
let count = NamedGroup::supported().len() + 1;
message.extend_from_slice(&(count as u16 * 5).to_be_bytes());
for _ in 0..count {
message.extend_from_slice(&NamedGroup::X25519.as_u16().to_be_bytes());
message.extend_from_slice(&1u16.to_be_bytes());
message.push(0x42);
}
let result = KeyShareClientHello::parse(&message, 0);
assert!(
matches!(
result,
Err(nom::Err::Failure(error))
if error.code == nom::error::ErrorKind::LengthValue
),
"too many duplicate key shares should fail with LengthValue"
);
}
#[test]
fn trailing_client_key_share_bytes_are_rejected() {
let result = KeyShareClientHello::parse(
&[
0x00, 0x08, // client_shares length (8)
0x00, 0x1D, // NamedGroup::X25519
0x00, 0x04, // key_exchange length
0x01, 0x02, 0x03, 0x04, // key_exchange data
0xFF, // Extension body has a trailing byte beyond the vector.
],
0,
);
assert!(
matches!(
result,
Err(nom::Err::Failure(error))
if error.code == nom::error::ErrorKind::LengthValue
),
"trailing key_share client bytes should fail with LengthValue"
);
}
#[test]
fn trailing_server_key_share_bytes_are_rejected() {
let result = KeyShareServerHello::parse(
&[
0x00, 0x1D, // NamedGroup::X25519
0x00, 0x04, // key_exchange length
0x01, 0x02, 0x03, 0x04, // key_exchange data
0xFF, // Extension body has a trailing byte after the entry.
],
0,
);
assert!(
matches!(
result,
Err(nom::Err::Failure(error))
if error.code == nom::error::ErrorKind::LengthValue
),
"trailing key_share server bytes should fail with LengthValue"
);
}
#[test]
fn trailing_hello_retry_request_key_share_bytes_are_rejected() {
let result = KeyShareHelloRetryRequest::parse(&[
0x00, 0x1D, // NamedGroup::X25519
0xFF, // Extension body has a trailing byte after selected_group.
]);
assert!(
matches!(
result,
Err(nom::Err::Failure(error))
if error.code == nom::error::ErrorKind::LengthValue
),
"trailing key_share HRR bytes should fail with LengthValue"
);
}
}
@@ -0,0 +1,6 @@
pub mod cookie;
pub mod key_share;
pub mod signature_algorithms;
pub mod supported_groups;
pub mod supported_versions;
pub mod use_srtp;
@@ -0,0 +1,187 @@
use crate::buffer::Buf;
use crate::types::SignatureScheme;
use arrayvec::ArrayVec;
use nom::Err;
use nom::IResult;
use nom::bytes::complete::take;
use nom::error::{Error, ErrorKind};
/// SignatureAlgorithms extension for TLS 1.3 (RFC 8446 Section 4.2.3).
///
/// Uses `SignatureScheme` (u16) instead of the TLS 1.2 `SignatureAndHashAlgorithm`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignatureAlgorithmsExtension {
pub supported_signature_algorithms: ArrayVec<SignatureScheme, 2>,
}
impl SignatureAlgorithmsExtension {
/// Create a default SignatureAlgorithmsExtension with supported schemes.
pub fn default() -> Self {
SignatureAlgorithmsExtension {
supported_signature_algorithms: SignatureScheme::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: ArrayVec<SignatureScheme, 2> = ArrayVec::new();
let (input, mut current_input) = take(list_len)(input)?;
if !input.is_empty() {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
while !current_input.is_empty() {
let (rest, scheme) = SignatureScheme::parse(current_input)?;
if scheme.is_supported() {
algorithms
.try_push(scheme)
.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) {
output.extend_from_slice(
&((self.supported_signature_algorithms.len() * 2) as u16).to_be_bytes(),
);
for scheme in &self.supported_signature_algorithms {
output.extend_from_slice(&scheme.as_u16().to_be_bytes());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_signature_algorithms_extension() {
let mut algorithms: ArrayVec<SignatureScheme, 2> = ArrayVec::new();
algorithms.push(SignatureScheme::ECDSA_SECP256R1_SHA256);
algorithms.push(SignatureScheme::ECDSA_SECP384R1_SHA384);
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, // ECDSA_SECP256R1_SHA256
0x05, 0x03, // ECDSA_SECP384R1_SHA384
];
assert_eq!(&*serialized, expected);
let (_, parsed) = SignatureAlgorithmsExtension::parse(&serialized).unwrap();
assert_eq!(parsed.supported_signature_algorithms, algorithms);
}
#[test]
fn capacity_matches_supported() {
let ext = SignatureAlgorithmsExtension::default();
assert_eq!(
ext.supported_signature_algorithms.capacity(),
SignatureScheme::supported().len(),
"SignatureAlgorithmsExtension capacity must match supported schemes count"
);
}
#[test]
fn too_many_supported_signature_algorithms_are_rejected() {
let mut bytes = Vec::new();
let supported = SignatureScheme::supported();
let count = supported.len() + 1;
bytes.extend_from_slice(&(count as u16 * 2).to_be_bytes());
for _ in 0..count {
bytes.extend_from_slice(
&SignatureScheme::ECDSA_SECP256R1_SHA256
.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, // ECDSA_SECP256R1_SHA256
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,169 @@
use crate::buffer::Buf;
use crate::types::NamedGroup;
use arrayvec::ArrayVec;
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: ArrayVec<NamedGroup, 4>,
}
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: ArrayVec<NamedGroup, 4> = ArrayVec::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 = ArrayVec::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() {
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());
assert_eq!(
parsed.groups.as_slice(),
&[
NamedGroup::X25519,
NamedGroup::Secp256r1,
NamedGroup::Secp384r1
]
);
}
#[test]
fn capacity_matches_supported() {
let ext = SupportedGroupsExtension {
groups: ArrayVec::new(),
};
assert_eq!(
ext.groups.capacity(),
NamedGroup::supported().len(),
"SupportedGroupsExtension capacity must match all supported NamedGroups"
);
}
#[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,201 @@
use crate::buffer::Buf;
use crate::types::ProtocolVersion;
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;
/// SupportedVersions extension in ClientHello (RFC 8446 Section 4.2.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SupportedVersionsClientHello {
pub versions: ArrayVec<ProtocolVersion, 3>,
}
impl SupportedVersionsClientHello {
pub fn parse(input: &[u8]) -> IResult<&[u8], SupportedVersionsClientHello> {
let (input, list_len) = be_u8(input)?;
if list_len == 0 || list_len % 2 != 0 {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
let (input, versions_data) = take(list_len)(input)?;
if !input.is_empty() {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
let mut versions = ArrayVec::new();
let mut rest = versions_data;
while !rest.is_empty() {
let (r, version) = ProtocolVersion::parse(rest)?;
if !version.is_unknown() {
versions
.try_push(version)
.map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?;
}
rest = r;
}
Ok((input, SupportedVersionsClientHello { versions }))
}
pub fn serialize(&self, output: &mut Buf) {
output.push((self.versions.len() * 2) as u8);
for version in &self.versions {
output.extend_from_slice(&version.as_u16().to_be_bytes());
}
}
}
/// SupportedVersions extension in ServerHello (RFC 8446 Section 4.2.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SupportedVersionsServerHello {
pub selected_version: ProtocolVersion,
}
impl SupportedVersionsServerHello {
pub fn parse(input: &[u8]) -> IResult<&[u8], SupportedVersionsServerHello> {
let (input, selected_version) = ProtocolVersion::parse(input)?;
if !input.is_empty() {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
Ok((input, SupportedVersionsServerHello { selected_version }))
}
pub fn serialize(&self, output: &mut Buf) {
output.extend_from_slice(&self.selected_version.as_u16().to_be_bytes());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::buffer::Buf;
#[test]
fn client_hello_roundtrip() {
let message: &[u8] = &[
0x04, // list length (4 bytes = 2 versions)
0xFE, 0xFC, // DTLS 1.3
0xFE, 0xFD, // DTLS 1.2
];
let (rest, parsed) = SupportedVersionsClientHello::parse(message).unwrap();
assert!(rest.is_empty());
let mut serialized = Buf::new();
parsed.serialize(&mut serialized);
assert_eq!(&*serialized, message);
}
#[test]
fn server_hello_roundtrip() {
let message: &[u8] = &[
0xFE, 0xFC, // DTLS 1.3
];
let (rest, parsed) = SupportedVersionsServerHello::parse(message).unwrap();
assert!(rest.is_empty());
let mut serialized = Buf::new();
parsed.serialize(&mut serialized);
assert_eq!(&*serialized, message);
}
#[test]
fn unknown_client_hello_versions_are_ignored() {
let message: &[u8] = &[
0x08, // list length (8 bytes = 4 versions)
0xFE, 0xFC, // DTLS 1.3
0xFE, 0xFD, // DTLS 1.2
0xFE, 0xFF, // DTLS 1.0
0xFE, 0xFE, // Unknown
];
let (rest, parsed) = SupportedVersionsClientHello::parse(message).unwrap();
assert!(rest.is_empty());
assert_eq!(
parsed.versions.as_slice(),
&[
ProtocolVersion::DTLS1_3,
ProtocolVersion::DTLS1_2,
ProtocolVersion::DTLS1_0,
]
);
}
#[test]
fn too_many_duplicate_client_hello_versions_are_rejected() {
let message: &[u8] = &[
0x08, // list length (8 bytes = 4 versions)
0xFE, 0xFC, // DTLS 1.3
0xFE, 0xFC, // DTLS 1.3
0xFE, 0xFC, // DTLS 1.3
0xFE, 0xFC, // DTLS 1.3
];
let result = SupportedVersionsClientHello::parse(message);
assert!(
matches!(
result,
Err(nom::Err::Failure(error))
if error.code == nom::error::ErrorKind::LengthValue
),
"too many supported versions should fail with LengthValue"
);
}
#[test]
fn odd_client_hello_versions_are_rejected() {
let result = SupportedVersionsClientHello::parse(&[
0x03, // Declared vector length is not divisible by 2.
0xFE, 0xFC, 0xFF,
]);
assert!(
matches!(
result,
Err(nom::Err::Failure(error))
if error.code == nom::error::ErrorKind::LengthValue
),
"odd supported_versions vector should fail with LengthValue"
);
}
#[test]
fn trailing_client_hello_versions_bytes_are_rejected() {
let result = SupportedVersionsClientHello::parse(&[
0x02, // One protocol version.
0xFE, 0xFC, // DTLS 1.3.
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_versions bytes should fail with LengthValue"
);
}
#[test]
fn trailing_server_hello_version_bytes_are_rejected() {
let result = SupportedVersionsServerHello::parse(&[
0xFE, 0xFC, // DTLS 1.3.
0xFF, // Extension body has a trailing byte after selected_version.
]);
assert!(
matches!(
result,
Err(nom::Err::Failure(error))
if error.code == nom::error::ErrorKind::LengthValue
),
"trailing selected_version bytes should fail with LengthValue"
);
}
}
@@ -0,0 +1,295 @@
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};
/// 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: ArrayVec<SrtpProfileId, 3>,
pub mki: ArrayVec<u8, 255>, // MKI value (usually empty)
}
impl UseSrtpExtension {
pub fn new(profiles: ArrayVec<SrtpProfileId, 3>, mki: ArrayVec<u8, 255>) -> Self {
UseSrtpExtension { profiles, mki }
}
/// Create a default UseSrtpExtension with standard profiles
pub fn default() -> Self {
let mut profiles = ArrayVec::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: ArrayVec<SrtpProfileId, 3> = ArrayVec::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 = ArrayVec::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() {
let bytes = [0, 8, 0, 7, 0, 8, 0, 1, 0, 2, 0];
let (_, parsed) = UseSrtpExtension::parse(&bytes).expect("parse UseSrtpExtension");
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 capacity_matches_profile_count() {
let ext = UseSrtpExtension::default();
assert_eq!(
ext.profiles.capacity(),
SrtpProfileId::supported().len(),
"UseSrtpExtension capacity must match supported profile IDs"
);
}
#[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,
..
})
));
}
}
+56
View File
@@ -0,0 +1,56 @@
use crate::buffer::Buf;
use crate::types::Dtls13CipherSuite;
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: Dtls13CipherSuite) -> 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
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::*;
use crate::buffer::Buf;
#[test]
fn roundtrip() {
// SHA-256 verify_data is 32 bytes
let verify_data: Vec<u8> = (0..32).collect();
let (rest, parsed) =
Finished::parse(&verify_data, Dtls13CipherSuite::AES_128_GCM_SHA256).unwrap();
assert!(rest.is_empty());
let mut serialized = Buf::new();
parsed.serialize(&verify_data, &mut serialized);
assert_eq!(&*serialized, &verify_data[..]);
}
}
+752
View File
@@ -0,0 +1,752 @@
use std::fmt;
use std::ops::Range;
use std::sync::atomic::{AtomicBool, Ordering};
use super::{Certificate, CertificateVerify, ClientHello, Dtls13CipherSuite};
use super::{EncryptedExtensions, Finished, ServerHello};
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<Dtls13CipherSuite>,
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>(
iter: impl Iterator<Item = (&'b Handshake, &'b [u8])>,
buffer: &mut Buf,
cipher_suite: Option<Dtls13CipherSuite>,
transcript: Option<&mut Buf>,
) -> Result<Handshake, crate::InternalError> {
Self::defragment_with_options(iter, buffer, cipher_suite, transcript, false)
}
pub(crate) fn defragment_allow_unknown_client_hello_suites<'b>(
iter: impl Iterator<Item = (&'b Handshake, &'b [u8])>,
buffer: &mut Buf,
cipher_suite: Option<Dtls13CipherSuite>,
transcript: Option<&mut Buf>,
) -> Result<Handshake, crate::InternalError> {
Self::defragment_with_options(iter, buffer, cipher_suite, transcript, true)
}
fn defragment_with_options<'b>(
mut iter: impl Iterator<Item = (&'b Handshake, &'b [u8])>,
buffer: &mut Buf,
cipher_suite: Option<Dtls13CipherSuite>,
transcript: Option<&mut Buf>,
allow_unknown_client_hello_suites: bool,
) -> 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()]);
let mut assembled_end =
first_handshake.header.fragment_offset + first_handshake.header.fragment_length;
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())?;
// Handle overlapping fragment data: skip bytes already assembled
let frag_start = handshake.header.fragment_offset as usize;
let frag_len = handshake.header.fragment_length as usize;
let skip = (assembled_end as usize).saturating_sub(frag_start);
if skip < frag_len {
buffer.extend_from_slice(&source_buf[range.start + skip..range.end]);
}
let end = handshake.header.fragment_offset + handshake.header.fragment_length;
if end > assembled_end {
assembled_end = end;
}
}
if buffer.len() != first_handshake.header.length as usize {
debug!("Defragmentation failed. Fragment length mismatch");
return Err(crate::InternalError::parse_incomplete());
}
let (rest, body) = if allow_unknown_client_hello_suites {
match Body::parse_allow_unknown_client_hello_suites(
buffer,
0,
first_handshake.header.msg_type,
cipher_suite,
) {
Ok(parsed) => parsed,
Err(err) => {
mark_handled(handled);
return Err(err.into());
}
}
} else {
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 TLS 1.3-style header + body after parsing succeeds.
// Per RFC 9147 Section 5.2, the transcript uses msg_type(1) + length(3)
// WITHOUT the DTLS-specific message_seq, fragment_offset, fragment_length.
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(&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)
}
// These handshakes trigger a resend of the entire flight when detected as
// duplicates.
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
| MessageType::Finished // client final flight
);
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 ClientHello: Self = Self(1);
pub const ServerHello: Self = Self(2);
pub const EncryptedExtensions: Self = Self(8);
pub const Certificate: Self = Self(11);
pub const CertificateRequest: Self = Self(13);
pub const CertificateVerify: Self = Self(15);
pub const Finished: Self = Self(20);
pub const KeyUpdate: Self = Self(24);
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(1..=2 | 8 | 11 | 13 | 15 | 20 | 24))
}
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)))
}
}
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::ClientHello => "ClientHello",
MessageType::ServerHello => "ServerHello",
MessageType::EncryptedExtensions => "EncryptedExtensions",
MessageType::Certificate => "Certificate",
MessageType::CertificateRequest => "CertificateRequest",
MessageType::CertificateVerify => "CertificateVerify",
MessageType::Finished => "Finished",
MessageType::KeyUpdate => "KeyUpdate",
_ => unreachable!("known DTLS 1.3 handshake message type missing Debug label"),
};
f.write_str(name)
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, PartialEq, Eq)]
pub enum Body {
ClientHello(ClientHello),
ServerHello(ServerHello),
EncryptedExtensions(EncryptedExtensions),
Certificate(Certificate),
CertificateRequest(Range<usize>),
CertificateVerify(CertificateVerify),
Finished(Finished),
KeyUpdate(KeyUpdateRequest),
Unknown(u8),
Fragment(Range<usize>),
}
/// RFC 8446 Section 4.6.3 KeyUpdate request type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyUpdateRequest {
/// Peer does not need to respond with its own KeyUpdate.
UpdateNotRequested = 0,
/// Peer MUST respond with its own KeyUpdate (update_not_requested).
UpdateRequested = 1,
}
impl KeyUpdateRequest {
/// Parse from a single byte.
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(KeyUpdateRequest::UpdateNotRequested),
1 => Some(KeyUpdateRequest::UpdateRequested),
_ => None,
}
}
/// Serialize to a single byte.
pub fn as_u8(self) -> u8 {
self as u8
}
}
impl Default for Body {
fn default() -> Self {
Self::Unknown(0)
}
}
impl Body {
pub fn parse(
input: &[u8],
base_offset: usize,
m: MessageType,
c: Option<Dtls13CipherSuite>,
) -> IResult<&[u8], Body> {
Self::parse_with_options(input, base_offset, m, c, false)
}
pub(crate) fn parse_allow_unknown_client_hello_suites(
input: &[u8],
base_offset: usize,
m: MessageType,
c: Option<Dtls13CipherSuite>,
) -> IResult<&[u8], Body> {
Self::parse_with_options(input, base_offset, m, c, true)
}
fn parse_with_options(
input: &[u8],
base_offset: usize,
m: MessageType,
c: Option<Dtls13CipherSuite>,
allow_unknown_client_hello_suites: bool,
) -> IResult<&[u8], Body> {
match m {
MessageType::ClientHello => {
let (input, client_hello) = if allow_unknown_client_hello_suites {
ClientHello::parse_allow_unknown_suites(input, base_offset)?
} else {
ClientHello::parse(input, base_offset)?
};
Ok((input, Body::ClientHello(client_hello)))
}
MessageType::ServerHello => {
let (input, server_hello) = ServerHello::parse(input, base_offset)?;
Ok((input, Body::ServerHello(server_hello)))
}
MessageType::EncryptedExtensions => {
let (input, ee) = EncryptedExtensions::parse(input, base_offset)?;
Ok((input, Body::EncryptedExtensions(ee)))
}
MessageType::Certificate => {
let (input, certificate) = Certificate::parse(input, base_offset)?;
Ok((input, Body::Certificate(certificate)))
}
MessageType::CertificateRequest => {
let range = base_offset..(base_offset + input.len());
Ok((&[], Body::CertificateRequest(range)))
}
MessageType::CertificateVerify => {
let (input, cv) = CertificateVerify::parse(input, base_offset)?;
Ok((input, Body::CertificateVerify(cv)))
}
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)))
}
MessageType::KeyUpdate => {
let (input, byte) = be_u8(input)?;
if !input.is_empty() {
return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue)));
}
let request = KeyUpdateRequest::from_u8(byte)
.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?;
Ok((input, Body::KeyUpdate(request)))
}
_ => Ok((input, Body::Unknown(m.as_u8()))),
}
}
pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) {
match self {
Body::ClientHello(client_hello) => {
client_hello.serialize(source_buf, output);
}
Body::ServerHello(server_hello) => {
server_hello.serialize(source_buf, output);
}
Body::EncryptedExtensions(ee) => {
ee.serialize(source_buf, output);
}
Body::Certificate(certificate) => {
certificate.serialize(source_buf, output);
}
Body::CertificateRequest(range) => {
output.extend_from_slice(&source_buf[range.clone()]);
}
Body::CertificateVerify(cv) => {
cv.serialize(source_buf, output);
}
Body::Finished(finished) => {
finished.serialize(source_buf, output);
}
Body::KeyUpdate(request) => {
output.push(request.as_u8());
}
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 super::*;
use crate::buffer::Buf;
use crate::dtls13::message::{CompressionMethod, Cookie, Dtls13CipherSuite};
use crate::dtls13::message::{ProtocolVersion, Random, 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 (legacy)
// 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, // CipherSuites length
0x13, 0x01, // AES_128_GCM_SHA256
0x13, 0x02, // AES_256_GCM_SHA384
0x01, // CompressionMethods length
0x00, // Null
];
#[test]
fn message_type_newtype_shape() {
assert_eq!(std::mem::size_of::<MessageType>(), 1);
assert_eq!(MessageType::default().as_u8(), 0);
assert!(MessageType::default().is_unknown());
}
#[test]
fn message_type_wire_roundtrip() {
for message_type in [
MessageType::ClientHello,
MessageType::ServerHello,
MessageType::EncryptedExtensions,
MessageType::Certificate,
MessageType::CertificateRequest,
MessageType::CertificateVerify,
MessageType::Finished,
MessageType::KeyUpdate,
] {
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(
MessageType::EncryptedExtensions,
2,
0,
0,
2,
Body::EncryptedExtensions(EncryptedExtensions {
extensions: ArrayVec::new(),
}),
);
let mut v = Buf::new();
h.serialize(&[], &mut v);
// 12 bytes header + 2 bytes (empty extensions length)
assert_eq!(v.len(), 14);
}
#[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(Dtls13CipherSuite::AES_128_GCM_SHA256);
cipher_suites.push(Dtls13CipherSuite::AES_256_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 key_update_body_rejects_trailing_bytes() {
let source = [KeyUpdateRequest::UpdateRequested.as_u8(), 0];
let handshake = Handshake::new(
MessageType::KeyUpdate,
source.len() as u32,
0,
0,
source.len() as u32,
Body::Fragment(0..source.len()),
);
let mut buffer = Buf::new();
let mut transcript = Buf::new();
let result = Handshake::defragment(
std::iter::once((&handshake, source.as_slice())),
&mut buffer,
None,
Some(&mut transcript),
);
assert!(
result.is_err(),
"KeyUpdate bodies with trailing bytes must be rejected"
);
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 source = [0, 0, 0];
let handshake = Handshake::new(
MessageType::EncryptedExtensions,
source.len() as u32,
0,
0,
source.len() as u32,
Body::Fragment(0..source.len()),
);
let mut buffer = Buf::new();
let mut transcript = Buf::new();
let result = Handshake::defragment(
std::iter::once((&handshake, source.as_slice())),
&mut buffer,
None,
Some(&mut transcript),
);
assert!(result.is_err());
assert!(handshake.is_handled());
assert!(transcript.is_empty());
}
}
+128
View File
@@ -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);
+47
View File
@@ -0,0 +1,47 @@
//! Low-level DTLS 1.3 message parsing and serialization types.
//!
//! This module exposes enums and helpers used for parsing TLS 1.3 handshake
//! messages over DTLS 1.3 (RFC 9147).
mod certificate;
mod certificate_verify;
mod client_hello;
mod digitally_signed;
mod encrypted_extensions;
mod extension;
mod extensions;
mod finished;
mod handshake;
mod id;
mod record;
mod server_hello;
mod wrapped;
pub use certificate::{Certificate, CertificateEntry};
pub use certificate_verify::CertificateVerify;
pub use client_hello::ClientHello;
pub use digitally_signed::DigitallySigned;
pub use encrypted_extensions::EncryptedExtensions;
pub use extension::{Extension, ExtensionType};
pub(crate) use extensions::cookie::parse_cookie_extension;
pub use extensions::key_share::{
KeyShareClientHello, KeyShareEntry, KeyShareHelloRetryRequest, KeyShareServerHello,
};
pub use extensions::signature_algorithms::SignatureAlgorithmsExtension;
pub use extensions::supported_groups::SupportedGroupsExtension;
pub use extensions::supported_versions::{
SupportedVersionsClientHello, SupportedVersionsServerHello,
};
pub use extensions::use_srtp::{SrtpProfileId, UseSrtpExtension};
pub use finished::Finished;
pub use handshake::{Body, Handshake, Header, KeyUpdateRequest, MessageType};
pub use id::{Cookie, SessionId};
pub use record::Dtls13Record;
pub use server_hello::ServerHello;
pub use wrapped::{Asn1Cert, DistinguishedName};
// Re-export shared types
pub use crate::types::{
CompressionMethod, ContentType, Dtls13CipherSuite, NamedGroup, ProtocolVersion, Random,
Sequence, SignatureScheme,
};
+354
View File
@@ -0,0 +1,354 @@
//! DTLS 1.3 record layer types.
//!
//! Supports both DTLSPlaintext (epoch 0) and DTLSCiphertext (unified header)
//! record formats per RFC 9147 Section 4.
use std::fmt;
use std::ops::Range;
use crate::buffer::Buf;
use crate::types::{ContentType, ProtocolVersion, Sequence};
use crate::util::be_u48;
use nom::bytes::complete::take;
use nom::number::complete::{be_u8, be_u16};
use nom::{Err, IResult};
/// DTLS 1.3 record structure.
///
/// Represents both DTLSPlaintext (epoch 0) and DTLSCiphertext (unified header)
/// records. The format is determined during parsing based on the first byte.
#[derive(PartialEq, Eq, Default)]
pub struct Dtls13Record {
/// The content type of this record.
/// For plaintext records, this is the actual content type.
/// For ciphertext records before decryption, this is ApplicationData.
pub content_type: ContentType,
/// The epoch and sequence number.
/// For ciphertext records, epoch holds only the low 2 bits and
/// sequence_number holds the 8- or 16-bit partial value until resolved.
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 Dtls13Record {
/// DTLSPlaintext header length: content_type(1) + version(2) + epoch(2) + seq(6) + length(2)
pub const PLAINTEXT_HEADER_LEN: usize = 13;
/// Byte offset in the plaintext record header where the 2-byte length field is
pub const PLAINTEXT_LENGTH_OFFSET: Range<usize> = 11..13;
/// Returns true if the first byte indicates a unified (ciphertext) header.
///
/// The fixed bit pattern `001` in the top 3 bits distinguishes ciphertext
/// records from plaintext ContentType values (all < 0x20).
pub fn is_ciphertext_header(byte: u8) -> bool {
byte & 0b1110_0000 == 0b0010_0000
}
/// Parse a DTLS 1.3 record from the input buffer.
///
/// Detects plaintext vs ciphertext format from the first byte.
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Dtls13Record> {
if input.is_empty() {
return Err(Err::Error(nom::error::Error::new(
input,
nom::error::ErrorKind::Eof,
)));
}
if Self::is_ciphertext_header(input[0]) {
Self::parse_ciphertext(input, base_offset)
} else {
Self::parse_plaintext(input, base_offset)
}
}
/// Parse a DTLSPlaintext record (epoch 0).
fn parse_plaintext(input: &[u8], base_offset: usize) -> IResult<&[u8], Dtls13Record> {
let original_input = input;
let (input, content_type) = ContentType::parse(input)?; // u8
let (input, version) = ProtocolVersion::parse(input)?; // u16
// RFC 9147 §4.1: Only alert(21), handshake(22), and ack(26) are valid
// plaintext content types in DTLS 1.3. Reject all others.
match content_type {
ContentType::Alert | ContentType::Handshake | ContentType::Ack => {}
_ => {
return Err(Err::Failure(nom::error::Error::new(
input,
nom::error::ErrorKind::Tag,
)));
}
}
// Accept DTLS 1.0 or 1.2 in record layer per RFC 9147 §5.1
// (same legacy version handling as DTLS 1.2)
match version {
ProtocolVersion::DTLS1_0 | ProtocolVersion::DTLS1_2 => {}
_ => {
return Err(Err::Failure(nom::error::Error::new(
input,
nom::error::ErrorKind::Tag,
)));
}
}
let (input, epoch) = be_u16(input)?; // u16
// RFC 9147 §4.1: DTLSPlaintext records must use epoch 0.
// Epoch values other than 0 in plaintext format are invalid.
if epoch != 0 {
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
let (rest, fragment_slice) = take(length as usize)(input)?;
// Calculate absolute range in root buffer
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,
Dtls13Record {
content_type,
sequence,
length,
fragment_range: start..end,
},
))
}
/// Parse a DTLSCiphertext record (unified header, epoch >= 2).
///
/// The unified header flags byte layout:
/// ```text
/// 0 1 2 3 4 5 6 7
/// +-+-+-+-+-+-+-+-+
/// |0|0|1|C|S|L|E E|
/// +-+-+-+-+-+-+-+-+
/// ```
/// C=0 always (no CID support), S=seq length, L=length present, EE=epoch low bits.
fn parse_ciphertext(input: &[u8], base_offset: usize) -> IResult<&[u8], Dtls13Record> {
let original_input = input;
let (input, flags) = be_u8(input)?;
let c_flag = flags & 0b0001_0000 != 0;
if c_flag {
// CID not supported
return Err(Err::Failure(nom::error::Error::new(
input,
nom::error::ErrorKind::Tag,
)));
}
let s_flag = flags & 0b0000_1000 != 0;
let l_flag = flags & 0b0000_0100 != 0;
let epoch_bits = (flags & 0b0000_0011) as u16;
let (input, sequence_number) = if s_flag {
let (input, seq) = be_u16(input)?;
(input, seq as u64)
} else {
let (input, seq) = be_u8(input)?;
(input, seq as u64)
};
let (rest, length, fragment_slice) = if l_flag {
let (input, length) = be_u16(input)?;
let (rest, fragment) = take(length as usize)(input)?;
(rest, length, fragment)
} else {
// No length field: record consumes the rest of the datagram
let length = input.len() as u16;
let (rest, fragment) = take(length as usize)(input)?;
(rest, length, fragment)
};
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: epoch_bits,
sequence_number,
};
Ok((
rest,
Dtls13Record {
content_type: ContentType::ApplicationData,
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) {
if self.sequence.epoch == 0 {
self.serialize_plaintext(buf, output);
} else {
self.serialize_ciphertext(buf, output);
}
}
fn serialize_plaintext(&self, buf: &[u8], output: &mut Buf) {
output.push(self.content_type.as_u8());
ProtocolVersion::DTLS1_2.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));
}
fn serialize_ciphertext(&self, buf: &[u8], output: &mut Buf) {
// Always use S=1 (2-byte sequence) and L=1 (length present)
let flags: u8 = 0b0010_0000
| 0b0000_1000 // S=1
| 0b0000_0100 // L=1
| (self.sequence.epoch as u8 & 0x03);
output.push(flags);
output.extend_from_slice(&(self.sequence.sequence_number as u16).to_be_bytes());
output.extend_from_slice(&self.length.to_be_bytes());
output.extend_from_slice(self.fragment(buf));
}
}
impl fmt::Debug for Dtls13Record {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Dtls13Record")
.field("content_type", &self.content_type)
.field("sequence", &self.sequence)
.field("length", &self.length)
.field("fragment_range", &self.fragment_range)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plaintext_content_type_whitelist() {
// RFC 9147 §4.1: Only alert(21), handshake(22), and ack(26) are valid
// plaintext content types in DTLS 1.3. Plaintext records must use epoch 0.
// ApplicationData and other invalid types are rejected at parse time.
fn build_plaintext_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
]
}
fn build_plaintext_record_with_epoch(content_type: u8, epoch: u16) -> Vec<u8> {
vec![
content_type, // ContentType
0xFE,
0xFD, // version: DTLS 1.2
(epoch >> 8) as u8,
(epoch & 0xFF) as u8, // epoch
0x00,
0x00,
0x00,
0x00,
0x00,
0x01, // sequence_number
0x00,
0x02, // length: 2
0xAA,
0xBB, // fragment payload
]
}
// ALLOWED: Alert (21) with epoch 0
let alert = build_plaintext_record(0x15);
assert!(
Dtls13Record::parse(&alert, 0).is_ok(),
"Alert should be allowed in plaintext DTLS 1.3"
);
// ALLOWED: Handshake (22) with epoch 0
let handshake = build_plaintext_record(0x16);
assert!(
Dtls13Record::parse(&handshake, 0).is_ok(),
"Handshake should be allowed in plaintext DTLS 1.3"
);
// ALLOWED: Ack (26) with epoch 0
let ack = build_plaintext_record(0x1A);
assert!(
Dtls13Record::parse(&ack, 0).is_ok(),
"Ack should be allowed in plaintext DTLS 1.3"
);
// REJECTED: ApplicationData (23)
let app_data = build_plaintext_record(0x17);
assert!(
Dtls13Record::parse(&app_data, 0).is_err(),
"ApplicationData must be rejected in plaintext DTLS 1.3"
);
// REJECTED: ChangeCipherSpec (20) - valid in DTLS 1.2 but not DTLS 1.3
let ccs = build_plaintext_record(0x14);
assert!(
Dtls13Record::parse(&ccs, 0).is_err(),
"ChangeCipherSpec must be rejected in DTLS 1.3"
);
// REJECTED: Unknown ContentType (0xFF)
let unknown = build_plaintext_record(0xFF);
assert!(
Dtls13Record::parse(&unknown, 0).is_err(),
"Unknown ContentType must be rejected in plaintext DTLS 1.3"
);
// REJECTED: Plaintext format with epoch 1 (invalid per RFC 9147 §4.1)
let epoch_1_handshake = build_plaintext_record_with_epoch(0x16, 1);
assert!(
Dtls13Record::parse(&epoch_1_handshake, 0).is_err(),
"Plaintext format with epoch 1 must be rejected"
);
// REJECTED: Plaintext format with epoch 2 (should use unified header)
let epoch_2_handshake = build_plaintext_record_with_epoch(0x16, 2);
assert!(
Dtls13Record::parse(&epoch_2_handshake, 0).is_err(),
"Plaintext format with epoch 2 must be rejected"
);
}
}
+250
View File
@@ -0,0 +1,250 @@
use super::{CompressionMethod, Dtls13CipherSuite, Extension};
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};
/// Magic random value indicating HelloRetryRequest (RFC 8446 Section 4.1.3).
const HRR_RANDOM: [u8; 32] = [
0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
];
#[derive(Debug, PartialEq, Eq)]
pub struct ServerHello {
pub legacy_version: ProtocolVersion,
pub random: Random,
pub legacy_session_id: SessionId,
pub cipher_suite: Dtls13CipherSuite,
pub legacy_compression_method: CompressionMethod,
pub extensions: Option<ArrayVec<Extension, 5>>,
}
impl ServerHello {
pub fn new(
legacy_version: ProtocolVersion,
random: Random,
legacy_session_id: SessionId,
cipher_suite: Dtls13CipherSuite,
legacy_compression_method: CompressionMethod,
extensions: Option<ArrayVec<Extension, 5>>,
) -> Self {
ServerHello {
legacy_version,
random,
legacy_session_id,
cipher_suite,
legacy_compression_method,
extensions,
}
}
/// Returns true if this ServerHello is actually a HelloRetryRequest.
pub fn is_hello_retry_request(&self) -> bool {
self.random.bytes == HRR_RANDOM
}
pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ServerHello> {
let original_input = input;
let (input, legacy_version) = ProtocolVersion::parse(input)?;
let (input, random) = Random::parse(input)?;
let (input, legacy_session_id) = SessionId::parse(input)?;
let (input, cipher_suite) = Dtls13CipherSuite::parse(input)?;
let (input, legacy_compression_method) = CompressionMethod::parse(input)?;
let (input, extensions) = if !input.is_empty() {
if input.len() < 2 {
return Err(Err::Failure(Error::new(input, ErrorKind::Eof)));
}
let (input, extensions_len) = be_u16(input)?;
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;
let mut extensions_vec: ArrayVec<Extension, 5> = ArrayVec::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;
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 {
legacy_version,
random,
legacy_session_id,
cipher_suite,
legacy_compression_method,
extensions,
},
))
}
pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) {
output.extend_from_slice(&self.legacy_version.as_u16().to_be_bytes());
self.random.serialize(output);
output.push(self.legacy_session_id.len() as u8);
output.extend_from_slice(&self.legacy_session_id);
output.extend_from_slice(&self.cipher_suite.as_u16().to_be_bytes());
output.push(self.legacy_compression_method.as_u8());
if let Some(extensions) = &self.extensions {
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();
}
output.extend_from_slice(&(extensions_len as u16).to_be_bytes());
for ext in extensions {
ext.serialize(source_buf, output);
}
}
}
}
#[cfg(test)]
mod test {
use super::super::ExtensionType;
use super::*;
use crate::buffer::Buf;
const MESSAGE: &[u8] = &[
0xFE, 0xFD, // ProtocolVersion::DTLS1_2 (legacy)
// 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
0x13, 0x01, // Dtls13CipherSuite::AES_128_GCM_SHA256
0x00, // CompressionMethod::Null
0x00, 0x0C, // Extensions length (12 bytes)
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() {
let (rest, parsed) = ServerHello::parse(MESSAGE, 0).unwrap();
assert!(rest.is_empty());
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, too long)
let result = ServerHello::parse(&message, 0);
assert!(result.is_err());
}
#[test]
fn hello_retry_request_detection() {
let hrr_random = Random { bytes: HRR_RANDOM };
let sh = ServerHello::new(
ProtocolVersion::DTLS1_2,
hrr_random,
SessionId::empty(),
Dtls13CipherSuite::AES_128_GCM_SHA256,
CompressionMethod::Null,
None,
);
assert!(sh.is_hello_retry_request());
}
#[test]
fn normal_server_hello_not_hrr() {
let (_, parsed) = ServerHello::parse(MESSAGE, 0).unwrap();
assert!(!parsed.is_hello_retry_request());
}
#[test]
fn duplicate_supported_extensions_are_rejected() {
let mut message = MESSAGE[..39].to_vec();
let count = 2;
message.extend_from_slice(&(count as u16 * 4).to_be_bytes());
for _ in 0..count {
message.extend_from_slice(&ExtensionType::Cookie.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"
);
}
#[test]
fn too_many_distinct_supported_extensions_are_rejected() {
let mut message = MESSAGE[..39].to_vec();
message.extend_from_slice(&(ExtensionType::supported().len() as u16 * 4).to_be_bytes());
for extension_type in ExtensionType::supported() {
message.extend_from_slice(&extension_type.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
),
"too many distinct supported extensions should fail with LengthValue"
);
}
}
+42
View File
@@ -0,0 +1,42 @@
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)))
}
}
};
}
wrapped_slice!(Asn1Cert, be_u24, 0);
wrapped_slice!(DistinguishedName, be_u16, 1);
impl Asn1Cert {
pub fn as_slice<'a>(&self, buf: &'a [u8]) -> &'a [u8] {
&buf[self.0.clone()]
}
}
+39
View File
@@ -0,0 +1,39 @@
//! DTLS 1.3 protocol implementation.
//!
// This is the full DTLS 1.3 handshake flow (RFC 9147)
//
// Client Server
//
// ClientHello
// + supported_versions
// + supported_groups
// + key_share
// + signature_algorithms -------->
// ServerHello
// + key_share
// + supported_versions
// {EncryptedExtensions}
// {CertificateRequest*}
// {Certificate}
// {CertificateVerify}
// <-------- {Finished}
// {Certificate*}
// {CertificateVerify*}
// {Finished} -------->
// [Application Data] <-------> [Application Data]
//
// {} = encrypted with handshake keys (epoch 2)
// [] = encrypted with application keys (epoch 3)
// * = optional (client auth)
pub mod incoming;
pub mod message;
mod client;
mod engine;
mod queue;
mod server;
pub use client::Client;
pub use server::Server;
+115
View File
@@ -0,0 +1,115 @@
//! Queue wrapper types with safe Debug implementations.
//!
//! These wrappers ensure that debug output only shows metadata,
//! not potentially sensitive payload data.
use std::collections::VecDeque;
use std::fmt;
use std::ops::{Deref, DerefMut};
use crate::buffer::Buf;
use crate::dtls13::incoming::Incoming;
use crate::types::ContentType;
/// Wrapper around the receive queue that provides safe Debug output.
///
/// The Debug implementation only shows metadata (counts by content type),
/// not potentially sensitive payload data.
pub(crate) struct QueueRx(VecDeque<Incoming>);
impl QueueRx {
pub fn new() -> Self {
Self(VecDeque::new())
}
}
impl Deref for QueueRx {
type Target = VecDeque<Incoming>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for QueueRx {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl fmt::Debug for QueueRx {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut handshake = 0;
let mut app_data = 0;
let mut alert = 0;
let mut other = 0;
let mut min_seq: Option<(u16, u64)> = None;
let mut max_seq: Option<(u16, u64)> = None;
for item in &self.0 {
let record = item.first().record();
match record.content_type {
ContentType::Handshake => handshake += 1,
ContentType::ApplicationData => app_data += 1,
ContentType::Alert => alert += 1,
_ => other += 1,
}
let seq = (record.sequence.epoch, record.sequence.sequence_number);
min_seq = Some(min_seq.map_or(seq, |m| m.min(seq)));
max_seq = Some(max_seq.map_or(seq, |m| m.max(seq)));
}
let mut s = f.debug_struct("QueueRx");
s.field("len", &self.0.len())
.field("handshake", &handshake)
.field("app_data", &app_data)
.field("alert", &alert)
.field("other", &other);
if let (Some(min), Some(max)) = (min_seq, max_seq) {
s.field(
"seq_range",
&format_args!("{}:{} - {}:{}", min.0, min.1, max.0, max.1),
);
}
s.finish()
}
}
/// Wrapper around the transmit queue that provides safe Debug output.
///
/// The Debug implementation only shows metadata (datagram count and total bytes),
/// not potentially sensitive payload data.
pub(crate) struct QueueTx(VecDeque<Buf>);
impl QueueTx {
pub fn new() -> Self {
Self(VecDeque::new())
}
}
impl Deref for QueueTx {
type Target = VecDeque<Buf>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for QueueTx {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl fmt::Debug for QueueTx {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let total_bytes: usize = self.0.iter().map(|b| b.len()).sum();
f.debug_struct("QueueTx")
.field("datagrams", &self.0.len())
.field("total_bytes", &total_bytes)
.finish()
}
}
File diff suppressed because it is too large. Load diff