use crate::model::technique::SctpReply;
use crate::protocols::craft;
use crate::protocols::error::{PacketError, Result};
use crate::protocols::sizes::{SCTP_CHUNK_HDR_LEN, SCTP_COMMON_HDR_LEN};
pub const IP_PROTOCOL_NUMBER: u8 = 132;
pub mod chunk_type {
pub const INIT: u8 = 1;
pub const INIT_ACK: u8 = 2;
pub const ABORT: u8 = 6;
pub const COOKIE_ECHO: u8 = 10;
}
const ADVERTISED_RWND: u32 = 65_535;
const OUTBOUND_STREAMS: u16 = 10;
const INBOUND_STREAMS: u16 = 65_535;
pub fn build_init_probe(src_port: u16, dst_port: u16, initiate_tag: u32) -> Vec<u8> {
craft::Sctp::new(src_port, dst_port)
.with_chunks(init_chunk(initiate_tag))
.to_bytes()
}
fn init_chunk(initiate_tag: u32) -> Vec<u8> {
let mut value = Vec::with_capacity(16);
value.extend_from_slice(&initiate_tag.to_be_bytes());
value.extend_from_slice(&ADVERTISED_RWND.to_be_bytes());
value.extend_from_slice(&OUTBOUND_STREAMS.to_be_bytes());
value.extend_from_slice(&INBOUND_STREAMS.to_be_bytes());
value.extend_from_slice(&rand::random::<u32>().to_be_bytes());
chunk(chunk_type::INIT, 0, &value).expect("a sixteen-byte value fits the length field")
}
pub fn build_cookie_echo_probe(src_port: u16, dst_port: u16, verification_tag: u32) -> Vec<u8> {
craft::Sctp::new(src_port, dst_port)
.with_verification_tag(verification_tag)
.with_chunks(cookie_echo_chunk())
.to_bytes()
}
const COOKIE_LEN: usize = 32;
fn cookie_echo_chunk() -> Vec<u8> {
let cookie: [u8; COOKIE_LEN] = rand::random();
chunk(chunk_type::COOKIE_ECHO, 0, &cookie).expect("a fixed short cookie fits the length field")
}
pub const MAX_CHUNK_VALUE: usize = u16::MAX as usize - SCTP_CHUNK_HDR_LEN;
pub fn chunk(chunk_type: u8, flags: u8, value: &[u8]) -> Result<Vec<u8>> {
if value.len() > MAX_CHUNK_VALUE {
return Err(PacketError::too_long(
"an SCTP chunk length",
SCTP_CHUNK_HDR_LEN,
value.len(),
));
}
let length = SCTP_CHUNK_HDR_LEN + value.len();
let mut bytes = Vec::with_capacity(round_up_to_4(length));
bytes.push(chunk_type);
bytes.push(flags);
bytes.extend_from_slice(&(length as u16).to_be_bytes());
bytes.extend_from_slice(value);
bytes.resize(round_up_to_4(length), 0);
Ok(bytes)
}
#[derive(Debug, Clone, Copy)]
pub struct Segment<'a> {
bytes: &'a [u8],
}
impl<'a> Segment<'a> {
pub fn source_port(&self) -> u16 {
u16::from_be_bytes([self.bytes[0], self.bytes[1]])
}
pub fn destination_port(&self) -> u16 {
u16::from_be_bytes([self.bytes[2], self.bytes[3]])
}
pub fn verification_tag(&self) -> u32 {
u32::from_be_bytes([self.bytes[4], self.bytes[5], self.bytes[6], self.bytes[7]])
}
pub fn chunks(&self) -> Chunks<'a> {
Chunks {
rest: &self.bytes[SCTP_COMMON_HDR_LEN..],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Chunk<'a> {
pub chunk_type: u8,
pub flags: u8,
pub value: &'a [u8],
}
#[derive(Debug, Clone, Copy)]
pub struct Chunks<'a> {
rest: &'a [u8],
}
impl<'a> Iterator for Chunks<'a> {
type Item = Chunk<'a>;
fn next(&mut self) -> Option<Chunk<'a>> {
if self.rest.len() < SCTP_CHUNK_HDR_LEN {
return None;
}
let chunk_type = self.rest[0];
let flags = self.rest[1];
let length = usize::from(u16::from_be_bytes([self.rest[2], self.rest[3]]));
if length < SCTP_CHUNK_HDR_LEN {
return None;
}
let value_end = length.min(self.rest.len());
let value = &self.rest[SCTP_CHUNK_HDR_LEN..value_end];
let advance = round_up_to_4(length).min(self.rest.len());
self.rest = &self.rest[advance..];
Some(Chunk {
chunk_type,
flags,
value,
})
}
}
pub fn parse(bytes: &'_ [u8]) -> Result<Segment<'_>> {
if bytes.len() < SCTP_COMMON_HDR_LEN {
return Err(PacketError::truncated(
"an SCTP packet",
SCTP_COMMON_HDR_LEN,
bytes.len(),
));
}
Ok(Segment { bytes })
}
pub fn classify_probe_response(segment: &Segment<'_>) -> Option<SctpReply> {
for chunk in segment.chunks() {
match chunk.chunk_type {
chunk_type::INIT_ACK => return Some(SctpReply::InitAck),
chunk_type::ABORT => return Some(SctpReply::Abort),
_ => {}
}
}
None
}
pub fn echoed_nonce(reply: &Segment<'_>) -> u32 {
reply.verification_tag()
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QuotedProbe {
pub source: u16,
pub destination: u16,
pub verification_tag: u32,
}
pub fn quoted_probe(quoted: &[u8]) -> Option<QuotedProbe> {
let head: &[u8; 8] = quoted.first_chunk()?;
Some(QuotedProbe {
source: u16::from_be_bytes([head[0], head[1]]),
destination: u16::from_be_bytes([head[2], head[3]]),
verification_tag: u32::from_be_bytes([head[4], head[5], head[6], head[7]]),
})
}
pub fn quoted_init_tag(quoted: &[u8]) -> Option<u32> {
let head: &[u8; 20] = quoted.first_chunk()?;
(head[SCTP_COMMON_HDR_LEN] == chunk_type::INIT)
.then(|| u32::from_be_bytes([head[16], head[17], head[18], head[19]]))
}
const fn round_up_to_4(n: usize) -> usize {
(n + 3) & !3
}
#[cfg(test)]
mod tests {
use super::*;
const SRC_PORT: u16 = 50_000;
const DST_PORT: u16 = 9;
const NONCE: u32 = 0xDEAD_BEEF;
fn reply(vtag: u32, chunk_type: u8) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.extend_from_slice(&DST_PORT.to_be_bytes()); bytes.extend_from_slice(&SRC_PORT.to_be_bytes()); bytes.extend_from_slice(&vtag.to_be_bytes());
bytes.extend_from_slice(&[0; 4]); bytes.extend_from_slice(&chunk(chunk_type, 0, &[]).expect("an empty value fits"));
bytes
}
#[test]
fn an_init_probe_is_framed_the_way_a_peer_expects() {
let bytes = build_init_probe(SRC_PORT, DST_PORT, NONCE);
let segment = parse(&bytes).expect("the probe parses");
assert_eq!(segment.source_port(), SRC_PORT);
assert_eq!(segment.destination_port(), DST_PORT);
assert_eq!(
segment.verification_tag(),
0,
"a packet carrying an INIT must have a zero verification tag"
);
let mut chunks = segment.chunks();
let init = chunks.next().expect("one chunk");
assert_eq!(init.chunk_type, chunk_type::INIT);
assert_eq!(init.value.len(), 16, "INIT has a sixteen-byte fixed part");
assert_eq!(
u32::from_be_bytes(init.value[0..4].try_into().unwrap()),
NONCE,
"the Initiate Tag carries the nonce"
);
assert!(chunks.next().is_none(), "the probe sends nothing else");
assert_eq!(bytes.len(), SCTP_COMMON_HDR_LEN + 20);
}
#[test]
fn a_cookie_echo_probe_carries_its_nonce_in_the_common_header() {
let bytes = build_cookie_echo_probe(SRC_PORT, DST_PORT, NONCE);
let segment = parse(&bytes).expect("the probe parses");
assert_eq!(segment.source_port(), SRC_PORT);
assert_eq!(segment.destination_port(), DST_PORT);
assert_eq!(
segment.verification_tag(),
NONCE,
"the verification tag carries the nonce a refusal reflects"
);
let mut chunks = segment.chunks();
let cookie = chunks.next().expect("one chunk");
assert_eq!(cookie.chunk_type, chunk_type::COOKIE_ECHO);
assert_eq!(cookie.value.len(), COOKIE_LEN);
assert!(chunks.next().is_none(), "the probe sends nothing else");
}
#[test]
fn two_cookie_echo_probes_do_not_carry_the_same_cookie() {
let first = build_cookie_echo_probe(SRC_PORT, DST_PORT, NONCE);
let second = build_cookie_echo_probe(SRC_PORT, DST_PORT, NONCE);
assert_ne!(first, second);
}
#[test]
fn a_cookie_echo_probe_carries_a_cookie_worth_authenticating() {
let bytes = build_cookie_echo_probe(SRC_PORT, DST_PORT, NONCE);
let segment = parse(&bytes).expect("parses");
let cookie = segment.chunks().next().expect("one chunk");
assert!(!cookie.value.is_empty());
}
#[test]
fn a_cookie_echo_probe_carries_a_valid_crc32c() {
let bytes = build_cookie_echo_probe(SRC_PORT, DST_PORT, NONCE);
let mut zeroed = bytes.clone();
zeroed[8..12].copy_from_slice(&[0; 4]);
assert_eq!(&bytes[8..12], &craft::crc32c(&zeroed).to_le_bytes());
}
#[test]
fn an_init_probe_carries_a_valid_crc32c() {
let bytes = build_init_probe(SRC_PORT, DST_PORT, NONCE);
let mut zeroed = bytes.clone();
zeroed[8..12].copy_from_slice(&[0; 4]);
let expected = craft::crc32c(&zeroed);
assert_eq!(
&bytes[8..12],
&expected.to_le_bytes(),
"the checksum verifies, and is little-endian on the wire"
);
}
#[test]
fn an_init_ack_reads_as_open_and_an_abort_as_closed() {
let init_ack_bytes = reply(NONCE, chunk_type::INIT_ACK);
let init_ack = parse(&init_ack_bytes).expect("parses");
assert_eq!(classify_probe_response(&init_ack), Some(SctpReply::InitAck));
assert_eq!(echoed_nonce(&init_ack), NONCE);
let abort_bytes = reply(NONCE, chunk_type::ABORT);
let abort = parse(&abort_bytes).expect("parses");
assert_eq!(classify_probe_response(&abort), Some(SctpReply::Abort));
assert_eq!(echoed_nonce(&abort), NONCE);
}
#[test]
fn a_reply_to_another_association_yields_a_different_nonce() {
let theirs_bytes = reply(NONCE ^ 0x1234, chunk_type::INIT_ACK);
let theirs = parse(&theirs_bytes).expect("parses");
assert_ne!(echoed_nonce(&theirs), NONCE);
}
#[test]
fn an_unrelated_chunk_answers_no_probe() {
for chunk_type in [4u8, 11] {
let bytes = reply(NONCE, chunk_type);
let other = parse(&bytes).expect("parses");
assert_eq!(classify_probe_response(&other), None, "chunk {chunk_type}");
}
}
#[test]
fn a_chunk_length_that_cannot_advance_stops_iteration() {
let mut bytes = reply(NONCE, chunk_type::ABORT);
let length_at = SCTP_COMMON_HDR_LEN + 2;
bytes[length_at..length_at + 2].copy_from_slice(&1u16.to_be_bytes());
let segment = parse(&bytes).expect("parses");
assert_eq!(segment.chunks().count(), 0, "the walk terminates");
assert_eq!(classify_probe_response(&segment), None);
}
#[test]
fn a_quoted_probe_needs_a_generous_quotation_to_name_its_attempt() {
let bytes = build_init_probe(SRC_PORT, DST_PORT, NONCE);
let quoted = quoted_probe(&bytes[..8]).expect("eight bytes are enough");
assert_eq!(quoted.source, SRC_PORT);
assert_eq!(quoted.destination, DST_PORT);
assert_eq!(quoted.verification_tag, 0);
assert_eq!(
quoted_init_tag(&bytes[..8]),
None,
"the tag is past the eight"
);
assert_eq!(
quoted_init_tag(&bytes),
Some(NONCE),
"a full quote names it"
);
}
#[test]
fn a_quoted_cookie_echo_names_its_attempt_from_the_guaranteed_eight() {
let bytes = build_cookie_echo_probe(SRC_PORT, DST_PORT, NONCE);
let quoted = quoted_probe(&bytes[..8]).expect("eight bytes are enough");
assert_eq!(quoted.source, SRC_PORT);
assert_eq!(quoted.destination, DST_PORT);
assert_eq!(
quoted.verification_tag, NONCE,
"the attempt is named without a generous quotation"
);
assert_eq!(
quoted_init_tag(&bytes),
None,
"the INIT reader must not claim a tag from another chunk"
);
}
#[test]
fn a_quotation_too_short_for_the_common_header_names_nothing() {
let bytes = build_init_probe(SRC_PORT, DST_PORT, NONCE);
assert_eq!(quoted_probe(&bytes[..7]), None);
}
#[test]
fn a_chunk_value_too_large_for_the_length_field_is_refused_rather_than_wrapped() {
let largest = vec![0u8; MAX_CHUNK_VALUE];
let encoded = chunk(chunk_type::INIT, 0, &largest).expect("the largest describable value");
assert_eq!(
u16::from_be_bytes([encoded[2], encoded[3]]),
u16::MAX,
"the largest value fills the field exactly"
);
for oversize in [MAX_CHUNK_VALUE + 1, u16::MAX as usize] {
let refused = chunk(chunk_type::INIT, 0, &vec![0u8; oversize]);
assert!(
matches!(refused, Err(PacketError::TooLong { .. })),
"a value of {oversize} produced {refused:?}"
);
}
}
#[test]
fn a_packet_too_short_for_the_common_header_is_rejected() {
assert!(matches!(
parse(&[0u8; SCTP_COMMON_HDR_LEN - 1]),
Err(PacketError::Truncated { .. })
));
}
}