rtci-dtls 0.5.0

Sans-I/O DTLS 1.2 and 1.3 (RFC 6347, RFC 9147) with DTLS-SRTP key export, for WebRTC
Documentation
//! The checks the DTLS 1.2 parser fuzz targets run, one function per target of the same name.
//!
//! They live in the crate so that two callers share them: the cargo-fuzz targets in `fuzz/`
//! (built with `--cfg fuzzing`) and the replay test (`fuzz_regressions_test`), which runs every
//! committed input in `fuzz/regressions/<target>/` through the same function in the ordinary
//! test job. Each function panics when its oracle is violated. Not part of the supported API.
#![allow(missing_docs)]

use std::io::Cursor;

use crate::content::Content;
use crate::handshake::handshake_header::{HANDSHAKE_HEADER_LENGTH, HandshakeHeader};
use crate::handshake::handshake_message_certificate::HandshakeMessageCertificate;
use crate::handshake::{Handshake, HandshakeMessage};
use crate::record_layer::RecordLayer;
use crate::record_layer::record_layer_header::{RECORD_LAYER_HEADER_SIZE, RecordLayerHeader};

/// A record parsed from the start of the input: no panic.
pub fn record_layer_mod_unmarshal(data: &[u8]) {
    let _ = RecordLayer::unmarshal(&mut Cursor::new(data));
}

/// A handshake message parsed from the start of the input: no panic.
pub fn handshake_mod_unmarshal(data: &[u8]) {
    let _ = Handshake::unmarshal(&mut Cursor::new(data));
}

/// A Certificate message body parsed: no panic.
pub fn handshake_handshake_message_certificate_unmarshal(data: &[u8]) {
    let _ = HandshakeMessageCertificate::unmarshal(&mut Cursor::new(data));
}

/// The message re-framed the way a sender frames it (`Handshake::new`): an unfragmented
/// message whose header's length and fragment length are the message's own size. A parsed
/// handshake keeps the header it arrived with, which no longer describes the message once a
/// parser has dropped what it ignores (an unsupported compression method, say).
fn reframed(handshake: &Handshake) -> Handshake {
    let size = handshake.handshake_message.size() as u32;
    Handshake {
        handshake_header: HandshakeHeader {
            handshake_type: handshake.handshake_message.handshake_type(),
            length: size,
            message_sequence: handshake.handshake_header.message_sequence,
            fragment_offset: 0,
            fragment_length: size,
        },
        handshake_message: handshake.handshake_message.clone(),
    }
}

/// A ServerKeyExchange is read as the PSK form whenever its first two octets, as a length,
/// cover the rest (RFC 4279 2 against RFC 8422 5.4); which form it is depends on the suite,
/// which a context-free parser does not know. Its value is compared as bytes only.
fn context_free(message: &HandshakeMessage) -> bool {
    !matches!(message, HandshakeMessage::ServerKeyExchange(_))
}

/// Writes `handshake` and checks that what it declares is what it writes and that the bytes
/// read back to the same message; returns the bytes.
fn handshake_written_and_read(handshake: &Handshake) -> Option<Vec<u8>> {
    let mut written = vec![];
    // A value the writer refuses (a field longer than its length prefix allows) is not
    // written; the oracle is about what is.
    handshake.marshal(&mut written).ok()?;
    assert_eq!(
        written.len(),
        handshake.size(),
        "a handshake writes the size it declares"
    );
    assert_eq!(
        written.len() - HANDSHAKE_HEADER_LENGTH,
        handshake.handshake_header.length as usize,
        "the header's length is the body written: {:?}",
        handshake.handshake_message.handshake_type()
    );
    let again = Handshake::unmarshal(&mut Cursor::new(&written[..]))
        .expect("a handshake message that was written parses");
    if context_free(&handshake.handshake_message) {
        assert_eq!(&again, handshake, "parse(marshal(m)) == m");
    }
    let mut rewritten = vec![];
    again.marshal(&mut rewritten).expect("and is written again");
    assert_eq!(rewritten, written, "marshal(parse(.)) is a fixed point");
    Some(written)
}

/// Round trip of a DTLS 1.2 handshake message (RFC 6347 4.2.2, RFC 5246 7.4), as the
/// reassembly buffer hands one to the parser: the 12-octet header and the `length` octets it
/// announces. A message that parses, re-framed as a sender frames it, writes the size it
/// declares, reads back as the same message, and writes again as the same bytes.
pub fn handshake_roundtrip(data: &[u8]) {
    let Ok(header) = HandshakeHeader::unmarshal(&mut Cursor::new(data)) else {
        return;
    };
    let Some(message) = data.get(..HANDSHAKE_HEADER_LENGTH + header.length as usize) else {
        return;
    };
    let Ok(first) = Handshake::unmarshal(&mut Cursor::new(message)) else {
        return;
    };
    handshake_written_and_read(&reframed(&first));
}

/// Round trip of a DTLS 1.2 record (RFC 6347 4.1), as a datagram is split into records: the
/// 13-octet header and the `length` octets it announces. A record that parses, with a
/// handshake body re-framed as a sender frames it and the record length set to the body's
/// size, writes 13 octets plus that size, reads back as the same record, and writes again as
/// the same bytes.
pub fn record_roundtrip(data: &[u8]) {
    let Ok(header) = RecordLayerHeader::unmarshal(&mut Cursor::new(data)) else {
        return;
    };
    let Some(record) = data.get(..RECORD_LAYER_HEADER_SIZE + usize::from(header.content_len))
    else {
        return;
    };
    let Ok(first) = RecordLayer::unmarshal(&mut Cursor::new(record)) else {
        return;
    };
    let content = match &first.content {
        Content::Handshake(handshake) => {
            let handshake = reframed(handshake);
            if handshake_written_and_read(&handshake).is_none() {
                return;
            }
            Content::Handshake(handshake)
        }
        other => other.clone(),
    };
    let Ok(content_len) = u16::try_from(content.size()) else {
        return;
    };
    let normalised = RecordLayer {
        record_layer_header: RecordLayerHeader {
            content_len,
            ..first.record_layer_header
        },
        content,
    };

    let mut written = vec![];
    if normalised.marshal(&mut written).is_err() {
        return;
    }
    assert_eq!(
        written.len(),
        RECORD_LAYER_HEADER_SIZE + usize::from(content_len),
        "a record writes the length its header declares"
    );
    let again =
        RecordLayer::unmarshal(&mut Cursor::new(&written[..])).expect("a written record parses");
    let comparable = match &normalised.content {
        Content::Handshake(h) => context_free(&h.handshake_message),
        _ => true,
    };
    if comparable {
        assert_eq!(again, normalised, "parse(marshal(r)) == r");
    }
    let mut rewritten = vec![];
    again.marshal(&mut rewritten).expect("and is written again");
    assert_eq!(rewritten, written, "marshal(parse(.)) is a fixed point");
}