use pnet_packet::tcp::TcpPacket;
use crate::model::capture::IpObservation;
const MAX_OPTIONS: usize = 20;
const TIMESTAMP_OVERHEAD: u16 = 12;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum TcpOptionKind {
EndOfList,
NoOp,
MaximumSegmentSize,
WindowScale,
SackPermitted,
Sack,
Timestamp,
Other(u8),
}
impl TcpOptionKind {
fn from_kind(kind: u8) -> Self {
match kind {
0 => TcpOptionKind::EndOfList,
1 => TcpOptionKind::NoOp,
2 => TcpOptionKind::MaximumSegmentSize,
3 => TcpOptionKind::WindowScale,
4 => TcpOptionKind::SackPermitted,
5 => TcpOptionKind::Sack,
8 => TcpOptionKind::Timestamp,
other => TcpOptionKind::Other(other),
}
}
pub fn letter(self) -> char {
match self {
TcpOptionKind::EndOfList => 'E',
TcpOptionKind::NoOp => 'N',
TcpOptionKind::MaximumSegmentSize => 'M',
TcpOptionKind::WindowScale => 'W',
TcpOptionKind::SackPermitted => 'S',
TcpOptionKind::Sack => 'K',
TcpOptionKind::Timestamp => 'T',
TcpOptionKind::Other(_) => '?',
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamps {
pub value: u32,
pub echo: u32,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Quirks {
pub reserved_bits_set: bool,
pub urgent_pointer_without_urg: bool,
pub acknowledgement_without_ack: bool,
pub zero_sequence: bool,
pub malformed_options: bool,
pub data_after_end_of_list: bool,
pub options_truncated: bool,
}
impl Quirks {
pub fn any(self) -> bool {
self != Quirks::default()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StackObservation {
pub flags: u8,
pub ip: IpObservation,
pub window: u16,
pub option_layout: Vec<TcpOptionKind>,
pub mss: Option<u16>,
pub window_scale: Option<u8>,
pub timestamps: Option<Timestamps>,
pub sack_permitted: bool,
pub quirks: Quirks,
}
impl StackObservation {
pub fn from_tcp(ip: IpObservation, segment: &[u8]) -> Option<Self> {
let packet = TcpPacket::new(segment)?;
let header_len = usize::from(packet.get_data_offset()) * 4;
if header_len < 20 || header_len > segment.len() {
return None;
}
let flags = packet.get_flags();
let walked = walk_options(packet.get_options_raw());
Some(Self {
flags,
ip,
window: packet.get_window(),
option_layout: walked.layout,
mss: walked.mss,
window_scale: walked.window_scale,
timestamps: walked.timestamps,
sack_permitted: walked.sack_permitted,
quirks: Quirks {
reserved_bits_set: packet.get_reserved() != 0,
urgent_pointer_without_urg: packet.get_urgent_ptr() != 0
&& flags & crate::protocols::tcp::flags::URG == 0,
acknowledgement_without_ack: packet.get_acknowledgement() != 0
&& flags & crate::protocols::tcp::flags::ACK == 0,
zero_sequence: packet.get_sequence() == 0
&& flags & crate::protocols::tcp::flags::SYN != 0,
malformed_options: walked.malformed,
data_after_end_of_list: walked.data_after_end,
options_truncated: walked.truncated,
},
})
}
pub fn from_ip_packet(packet: &[u8]) -> Option<Self> {
let parsed = crate::transport::frame::parse_ip_segment(packet)?;
if parsed.protocol != pnet_packet::ip::IpNextHeaderProtocols::Tcp {
return None;
}
Self::from_tcp(parsed.observation, parsed.payload)
}
pub fn is_syn_ack(&self) -> bool {
use crate::protocols::tcp::flags;
self.flags & flags::SYN != 0 && self.flags & flags::ACK != 0
}
pub fn is_reset(&self) -> bool {
self.flags & crate::protocols::tcp::flags::RST != 0
}
pub fn effective_mss(&self) -> Option<u16> {
let mss = self.mss?;
Some(if self.timestamps.is_some() {
mss.saturating_sub(TIMESTAMP_OVERHEAD)
} else {
mss
})
}
pub fn window_in_units(&self) -> Option<(u16, u16)> {
let unit = self.effective_mss()?;
if unit == 0 {
return None;
}
Some((self.window / unit, self.window % unit))
}
pub fn initial_hops_at_least(&self) -> u8 {
initial_hops_at_least(self.ip.remaining_hops())
}
pub fn summary(&self) -> String {
let mut out = String::with_capacity(96);
out.push_str(if self.is_syn_ack() {
"syn-ack"
} else if self.is_reset() {
"reset"
} else {
"other"
});
out.push_str(&format!(" hops>={}", self.initial_hops_at_least()));
if !self.option_layout.is_empty() {
out.push_str(&format!(" opts={}", self.layout_string()));
}
match self.window_in_units() {
Some((units, 0)) => out.push_str(&format!(
" win={}={}x{}",
self.window,
units,
self.effective_mss().unwrap_or_default()
)),
Some((units, remainder)) => out.push_str(&format!(
" win={}={}x{}+{remainder}",
self.window,
units,
self.effective_mss().unwrap_or_default()
)),
None => out.push_str(&format!(" win={}", self.window)),
}
if let Some(scale) = self.window_scale {
out.push_str(&format!(" ws={scale}"));
}
if let Some(mss) = self.mss {
out.push_str(&format!(" mss={mss}"));
}
if self.quirks.any() {
out.push_str(" quirks");
}
out
}
pub fn layout_string(&self) -> String {
let mut out = String::with_capacity(self.option_layout.len() * 2);
for (index, kind) in self.option_layout.iter().enumerate() {
if index > 0 {
out.push(',');
}
match kind {
TcpOptionKind::Other(number) => out.push_str(&format!("?{number}")),
named => out.push(named.letter()),
}
}
out
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EchoObservation {
pub ip: IpObservation,
pub code: u8,
pub payload_len: usize,
pub payload_intact: bool,
}
impl EchoObservation {
pub fn from_echo_reply(ip: IpObservation, message: &[u8], sent_payload: &[u8]) -> Option<Self> {
let header: &[u8; 8] = message.first_chunk()?;
let payload = &message[8..];
Some(Self {
ip,
code: header[1],
payload_len: payload.len(),
payload_intact: payload == sent_payload,
})
}
}
impl EchoObservation {
pub fn summary(&self) -> String {
let mut out = format!(
"echo hops>={}",
initial_hops_at_least(self.ip.remaining_hops())
);
if let IpObservation::V4(v4) = self.ip
&& v4.dont_fragment
{
out.push_str(" df");
}
out.push_str(&format!(" code={}", self.code));
out.push_str(&format!(" payload={}", self.payload_len));
if !self.payload_intact {
out.push_str(" altered");
}
out
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum StackReply {
Tcp(StackObservation),
Echo(EchoObservation),
}
impl StackReply {
pub fn ip(&self) -> IpObservation {
match self {
StackReply::Tcp(observed) => observed.ip,
StackReply::Echo(observed) => observed.ip,
}
}
pub fn summary(&self) -> String {
match self {
StackReply::Tcp(observed) => observed.summary(),
StackReply::Echo(observed) => observed.summary(),
}
}
pub fn initial_hops_at_least(&self) -> u8 {
initial_hops_at_least(self.ip().remaining_hops())
}
}
fn initial_hops_at_least(arrived: u8) -> u8 {
const COMMON: [u8; 4] = [32, 64, 128, 255];
COMMON
.into_iter()
.find(|start| *start >= arrived)
.unwrap_or(u8::MAX)
}
impl From<StackObservation> for StackReply {
fn from(observed: StackObservation) -> Self {
StackReply::Tcp(observed)
}
}
impl From<EchoObservation> for StackReply {
fn from(observed: EchoObservation) -> Self {
StackReply::Echo(observed)
}
}
struct Walked {
layout: Vec<TcpOptionKind>,
mss: Option<u16>,
window_scale: Option<u8>,
timestamps: Option<Timestamps>,
sack_permitted: bool,
malformed: bool,
data_after_end: bool,
truncated: bool,
}
fn walk_options(options: &[u8]) -> Walked {
let mut walked = Walked {
layout: Vec::new(),
mss: None,
window_scale: None,
timestamps: None,
sack_permitted: false,
malformed: false,
data_after_end: false,
truncated: false,
};
let mut at = 0;
for _ in 0..MAX_OPTIONS {
let Some(&kind) = options.get(at) else {
break;
};
walked.layout.push(TcpOptionKind::from_kind(kind));
if kind == 0 {
walked.data_after_end = options[at + 1..].iter().any(|byte| *byte != 0);
break;
}
if kind == 1 {
at += 1;
continue;
}
let Some(&length) = options.get(at + 1) else {
walked.malformed = true;
break;
};
let length = usize::from(length);
if length < 2 {
walked.malformed = true;
break;
}
let Some(value) = options.get(at + 2..at + length) else {
walked.malformed = true;
break;
};
match (kind, value) {
(2, [high, low]) => walked.mss = Some(u16::from_be_bytes([*high, *low])),
(3, [shift]) => walked.window_scale = Some(*shift),
(4, []) => walked.sack_permitted = true,
(8, [v0, v1, v2, v3, e0, e1, e2, e3]) => {
walked.timestamps = Some(Timestamps {
value: u32::from_be_bytes([*v0, *v1, *v2, *v3]),
echo: u32::from_be_bytes([*e0, *e1, *e2, *e3]),
});
}
_ => {}
}
at += length;
}
walked.truncated = at < options.len() && !walked.malformed && !walked.data_after_end;
walked
}
#[cfg(test)]
mod tests {
#[test]
fn a_truncated_option_walk_says_so() {
let forty_nops = [1u8; 40];
let observed = StackObservation::from_tcp(ip(), &segment(0x12, 64_240, &forty_nops))
.expect("a well-formed header");
assert_eq!(observed.option_layout.len(), MAX_OPTIONS);
assert!(observed.quirks.options_truncated);
assert!(
!observed.quirks.malformed_options,
"nothing was malformed; the walk simply stopped"
);
assert!(observed.quirks.any());
}
#[test]
fn a_list_the_walk_reads_whole_is_not_truncated() {
let linux: [u8; 20] = [
0x02, 0x04, 0x05, 0xb4, 0x04, 0x02, 0x08, 0x0a, 0xad, 0x58, 0xa5, 0xa7, 0x64, 0x48,
0x96, 0x12, 0x01, 0x03, 0x03, 0x07,
];
let observed = StackObservation::from_tcp(ip(), &segment(0x12, 65_160, &linux))
.expect("a well-formed header");
assert_eq!(observed.layout_string(), "M,S,T,N,W");
assert!(!observed.quirks.options_truncated);
assert!(!observed.quirks.any(), "nothing odd about it");
}
#[test]
fn an_option_shorter_than_its_own_header_is_malformed() {
for length in [0u8, 1] {
let observed =
StackObservation::from_tcp(ip(), &segment(0x12, 64_240, &[2, length, 0x05, 0xb4]))
.expect("a well-formed header");
assert!(
observed.quirks.malformed_options,
"an option of length {length} describes less than its own header"
);
assert_eq!(observed.mss, None);
}
}
use super::*;
use crate::model::capture::Ipv4Observation;
fn ip() -> IpObservation {
IpObservation::V4(Ipv4Observation {
ttl: 64,
identification: 0,
dont_fragment: true,
more_fragments: false,
dscp: 0,
ecn: 0,
})
}
fn segment(flags: u8, window: u16, options: &[u8]) -> Vec<u8> {
assert_eq!(options.len() % 4, 0, "the fixture must be word-aligned");
let mut bytes = vec![0u8; 20 + options.len()];
bytes[0..2].copy_from_slice(&80u16.to_be_bytes()); bytes[2..4].copy_from_slice(&50_000u16.to_be_bytes()); bytes[4..8].copy_from_slice(&1u32.to_be_bytes()); bytes[8..12].copy_from_slice(&2u32.to_be_bytes()); bytes[12] = (((20 + options.len()) / 4) as u8) << 4; bytes[13] = flags;
bytes[14..16].copy_from_slice(&window.to_be_bytes());
bytes[20..].copy_from_slice(options);
bytes
}
const SYN_ACK: u8 = 0b0001_0010; const RST_ACK: u8 = 0b0001_0100;
mod recorded {
pub const ROUTER: [u8; 20] = [
0x02, 0x04, 0x05, 0xb4, 0x04, 0x02, 0x08, 0x0a, 0xf9, 0xc1, 0x3d, 0x9a, 0x7a, 0xfc,
0xb9, 0x37, 0x01, 0x03, 0x03, 0x07,
];
pub const OLDER_LINUX: [u8; 20] = [
0x02, 0x04, 0x05, 0xb4, 0x04, 0x02, 0x08, 0x0a, 0x09, 0x6f, 0xa4, 0xb5, 0x56, 0x09,
0x46, 0x63, 0x01, 0x03, 0x03, 0x03,
];
pub const WIDE_AREA: [u8; 20] = [
0x02, 0x04, 0x05, 0x50, 0x04, 0x02, 0x08, 0x0a, 0xdb, 0xe1, 0xf2, 0x7e, 0x7d, 0x69,
0x6f, 0x3b, 0x01, 0x03, 0x03, 0x08,
];
}
#[test]
fn a_recorded_reply_yields_its_options_in_the_order_they_arrived() {
let observed =
StackObservation::from_tcp(ip(), &segment(SYN_ACK, 65_160, &recorded::ROUTER)).unwrap();
assert_eq!(observed.layout_string(), "M,S,T,N,W");
assert_eq!(
observed.option_layout,
vec![
TcpOptionKind::MaximumSegmentSize,
TcpOptionKind::SackPermitted,
TcpOptionKind::Timestamp,
TcpOptionKind::NoOp,
TcpOptionKind::WindowScale,
]
);
assert_eq!(observed.mss, Some(1460));
assert_eq!(observed.window_scale, Some(7));
assert!(observed.sack_permitted);
assert_eq!(observed.timestamps.map(|t| t.echo), Some(0x7afc_b937));
assert!(observed.is_syn_ack() && !observed.is_reset());
assert!(
!observed.quirks.any(),
"a conformant header has no oddities"
);
}
#[test]
fn the_window_is_the_same_multiple_of_the_unit_under_either_probe() {
let mss_only = [(65_535u16, 64_240u16, 44u16), (65_535, 29_200, 20)];
for (_, window, expected) in mss_only {
let observed =
StackObservation::from_tcp(ip(), &segment(SYN_ACK, window, &[2, 4, 0x05, 0xb4]))
.unwrap();
assert_eq!(observed.effective_mss(), Some(1460));
assert_eq!(observed.window_in_units(), Some((expected, 0)));
}
let router =
StackObservation::from_tcp(ip(), &segment(SYN_ACK, 65_160, &recorded::ROUTER)).unwrap();
assert_eq!(router.effective_mss(), Some(1448));
assert_eq!(router.window_in_units(), Some((45, 0)));
let older =
StackObservation::from_tcp(ip(), &segment(SYN_ACK, 28_960, &recorded::OLDER_LINUX))
.unwrap();
assert_eq!(older.effective_mss(), Some(1448));
assert_eq!(
older.window_in_units(),
Some((20, 0)),
"the same twenty it answered the MSS-only probe with"
);
}
#[test]
fn a_window_that_is_not_a_clean_multiple_keeps_its_remainder() {
let negotiated =
StackObservation::from_tcp(ip(), &segment(SYN_ACK, 64_296, &recorded::WIDE_AREA))
.unwrap();
assert_eq!(negotiated.mss, Some(1360));
assert_eq!(negotiated.effective_mss(), Some(1348));
assert_eq!(negotiated.window_in_units(), Some((47, 940)));
let bare = StackObservation::from_tcp(ip(), &segment(SYN_ACK, 64_860, &[2, 4, 0x05, 0x50]))
.unwrap();
assert_eq!(
bare.window_in_units(),
Some((47, 940)),
"same host, same shape"
);
}
#[test]
fn each_recorded_host_reports_its_own_window_scale() {
for (options, expected) in [
(recorded::ROUTER, 7),
(recorded::OLDER_LINUX, 3),
(recorded::WIDE_AREA, 8),
] {
let observed =
StackObservation::from_tcp(ip(), &segment(SYN_ACK, 1024, &options)).unwrap();
assert_eq!(observed.window_scale, Some(expected));
}
}
#[test]
fn a_reset_carries_nothing_the_options_would_have_said() {
let observed = StackObservation::from_tcp(ip(), &segment(RST_ACK, 0, &[])).unwrap();
assert!(observed.is_reset() && !observed.is_syn_ack());
assert!(observed.option_layout.is_empty());
assert_eq!(observed.mss, None);
assert_eq!(observed.window_scale, None);
assert_eq!(observed.timestamps, None);
assert!(!observed.sack_permitted);
assert_eq!(
observed.window_in_units(),
None,
"with no announced size there is no unit to count the window in"
);
}
#[test]
fn a_length_running_past_the_end_is_kept_as_a_quirk_not_a_panic() {
let observed = StackObservation::from_tcp(
ip(),
&segment(SYN_ACK, 1024, &[2, 4, 0x05, 0xb4, 3, 64, 0, 0]),
)
.unwrap();
assert_eq!(observed.mss, Some(1460), "what was read before the defect");
assert_eq!(observed.window_scale, None);
assert!(observed.quirks.malformed_options);
}
#[test]
fn a_list_of_nothing_but_padding_terminates() {
let observed = StackObservation::from_tcp(ip(), &segment(SYN_ACK, 1024, &[1; 40])).unwrap();
assert!(observed.option_layout.len() <= MAX_OPTIONS);
}
#[test]
fn an_impossible_data_offset_is_refused() {
let mut bytes = segment(SYN_ACK, 1024, &[]);
bytes[12] = 3 << 4; assert!(StackObservation::from_tcp(ip(), &bytes).is_none());
}
#[test]
fn oddities_a_conformant_header_does_not_have_are_recorded() {
let mut bytes = segment(0, 1024, &[]); bytes[8..12].copy_from_slice(&99u32.to_be_bytes()); bytes[18..20].copy_from_slice(&7u16.to_be_bytes()); bytes[12] |= 0b0000_1110;
let observed = StackObservation::from_tcp(ip(), &bytes).unwrap();
assert!(observed.quirks.acknowledgement_without_ack);
assert!(observed.quirks.urgent_pointer_without_urg);
assert!(observed.quirks.reserved_bits_set);
assert!(observed.quirks.any());
}
#[test]
fn a_handshake_announcing_sequence_zero_is_an_oddity() {
let mut bytes = segment(SYN_ACK, 1024, &[]);
bytes[4..8].copy_from_slice(&0u32.to_be_bytes());
let observed = StackObservation::from_tcp(ip(), &bytes).unwrap();
assert!(observed.quirks.zero_sequence);
}
#[test]
fn a_reset_carrying_the_sequence_the_rfc_demands_is_not_an_oddity() {
let bytes = segment(RST_ACK, 0, &[]); let observed = StackObservation::from_tcp(ip(), &bytes).unwrap();
assert!(!observed.quirks.zero_sequence);
assert!(
!observed.quirks.any(),
"a textbook reset has nothing odd about it: {:?}",
observed.quirks
);
}
}